JavaTechie

Its all about Technology

Display specific length string without truncating word in Java June 25, 2009

Filed under: Java, PHP — javatechie @ 5:29 am
Tags:

public static String textSubString(String text, int start, int end){

String str=”";
int limit=0;
limit=end;

if(text.length()!=0 && text!=”"){

String substr=text.substring(end,end+1);

if(substr!=”"){

while(!substr.equals(“”)){

substr=text.substring(limit,++limit);
substr=substr.trim();

}
}

str=text.substring(start,limit);

}

return str;
}

 

Java method similar to nl2br in PHP June 25, 2009

Filed under: Java, PHP — javatechie @ 5:26 am

public static String nl2br( String text){

return text.replaceAll(“\n”,”<br />”);

}

 

Serving Image from Absolute Path in Java/J2EE April 27, 2009

Filed under: Apache, Java — javatechie @ 11:20 am
Tags: , , ,

import java.io.*;
import java.net.URLDecoder;
import javax.servlet.*;
import javax.servlet.http.*;

/**
* Serving Image from Absolute Path.
*/

public class ImageServAbsolutePath extends HttpServlet {

private static final long serialVersionUID = 1L;

private static final int BUFFER_SIZE = 10240;

private String imagePath;

public void init() throws ServletException {

/*——- Image Base Path ———–*/
this.imagePath = “/images”;

}

protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
// Get requested image by path info.
String requestedImage = req.getPathInfo();

// Check if file name is there in request URI.
if (requestedImage == null) {
// if file name is not there in request URI, send 404 Error, or show default image.
res.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}

// Decode the file name (might contain spaces and on) and prepare file object.
File image = new File(imagePath, URLDecoder.decode(requestedImage, “UTF-8″));

// Check if file actually exists in filesystem.
if (!image.exists()) {
// if file not exists in filesystem send 404 Error, or show default image.
res.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}

// Get content type of Image by filename.
String contType = getServletContext().getMimeType(image.getName());

// Check if file is actually an image.
if (contType == null || !contType.startsWith(“image”)) {
// if the file is not a real image send 404 Error, or show default image.
res.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}

// Reset servlet response.
res.reset();
res.setBufferSize(BUFFER_SIZE); //set buffer size
res.setHeader(“Content-Type”, contType); //set content type
res.setHeader(“Content-Length”, String.valueOf(image.length())); //set image size
res.setHeader(“Content-Disposition”, “inline; filename=\”" + image.getName() + “\”"); //set image name

// Create streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;

try {
// Open streams.
input = new BufferedInputStream(new FileInputStream(image), BUFFER_SIZE);
output = new BufferedOutputStream(res.getOutputStream(), BUFFER_SIZE);

// Write image contents to response.
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}

output.flush();
} finally {

if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Add the following entries to the web.xml file

<servlet>
<servlet-name>ImageServAbs</servlet-name>
<servlet-class>ImageServAbsolutePath</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ImageServAbs</servlet-name>
<url-pattern>/image/*</url-pattern>
</servlet-mapping>

HOWTO USE :

<img src=”image/img.jpeg” />

 

Apache 2.x + Tomcat 4.x + Load Balancing February 12, 2009

Filed under: Apache, Java — javatechie @ 10:41 am
Tags: , ,

This article contains step by step instructions for configuring an Apache 2.x web server which handles static content and delegates JSP (Java Server Pages) and Servlet requests to two Tomcat 4.x servers using AJP 13 connectors and a load balancing worker.

Introduction

Apache 2.0 is a standards compliant, fast and mature web server which excels at delivering static content such as static HTML pages and images. The Tomcat web server is great for serving Java Server Pages and servlets, but it is not as fast as Apache for delivering static content.

In order to build a fast, scalable web application, the requirements call for an Apache server that delegates servicing of JSP and servlet requests to multiple tomcat servers by using an Apache module, mod_jk, that performs load balancing with session affinity, also known as “sticky” sessions.

Session affinity explained. When a client browser requests a JSP page for the first time, the load balancer redirects the request received by Apache to one of the two tomcat servers; further requests originating from the same client session will be automatically forwarded to the same tomcat server, so that the user’s session data is retrieved.

This document describes how I configured Apache 2.x to dispatch JSP and servlet requests to two Tomcat 4.x instances listening on different ports. This setup was done on a Linux system. Your mileage may vary.

Read more

 

how to find the last insert id in java+mysql? January 23, 2009

Filed under: Java, Mysql — javatechie @ 1:32 pm
Tags: ,

JDBC 3.0 (MySQL is has a JDBC 3 compliant driver) method as such:

Statement stat = dbConn.createStatement();
Stat.executeUpdate(“Some insert statement here”);

ResultSet rs = stat.getGeneratedKeys();
Int insertedKeyValue = rs.getInt(1);

Rs.close();
Stat.close();

 

How to Remove jsessionid from URL December 31, 2008

Filed under: Java — javatechie @ 9:05 am
Tags: ,

This is standard J2EE behavior.  When you start a HTTP session, the
session ID is appended to the URL and a cookie is set.  If the browser
has cookies enabled, the JSESSIONID is not used on subsequent requests.

Here is a urlrewrite rule to get rid of it, substitute JSESSIONID for
the name of the parameter your app server uses to track sessions.

<outbound-rule encodefirst=”true”>
<name>Strip URL Session ID’s</name>
<from>^(.*?)(?:\;JSESSIONID=[^\?#]*)?(\?[^#]*)?(#.*)?
$</from>
<to encode=”false”>$1$2$3</to>
</outbound-rule>

Just be aware that removing the session id will make sessions not work
for clients that do not support cookies.

 

Replace Single Quote in Java using str.replaceAll() December 10, 2008

Filed under: Java — javatechie @ 12:12 pm
Tags:

String input = “Replace Single Quote’s in Java”;
String output = input.replaceAll(” ‘ “, “\\\\’ “);
System.out.println(output);

 

How to calculate the difference between two dates October 17, 2008

Filed under: Java, Mysql — javatechie @ 1:06 pm
Tags: ,

long diffInMilleseconds = end.getTime() – start.getTime();

long noofdays=diffInMilleseconds/86400000;

long diffInSeconds = diffInMilleseconds/1000;
long diffInMinutes = diffInSeconds/60;
long diffInHours = diffInMinutes/60;
long diffInDays = diffInHours/24;

 

Setting cron job of java program September 22, 2008

Filed under: Java — javatechie @ 1:30 pm
Tags: ,

java -classpath  dir1:dir2:dirofclasses package.classname

if you are using mysql connection then you have to set mysql connectoe classpath also in command

eg:

java -classpath  dir1:dir2:mysqlconnectorpath:dirofclasses package.classname

 

java.lang.IllegalStateException August 8, 2008

Filed under: Java — javatechie @ 6:11 am
Tags: , ,

It is caused by the fact that response.sendRedirect is not the last statement in Servlet to be executed and its embedded in between your business logic i:e after that some function or business logic is continued. So, it should be the last statement otherwise it should return null after redirecting.

eg.

response.sendRedirect(“abc.jsp”);

return;