JavaTechie

Its all about Technology

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” />

 

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;

 

How can you set the session timeout in tomcat higher? July 4, 2008

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

You can specify the timeout of a session in the deployment descriptor of your web application (web.xml):

<web-app>
  <session-config>
    <session-timeout>60</session-timeout>
  </session-config>

  ...
</web-app>

The number within the session-timout element must be expressed in minutes.

 

Integrating Apache 1.3.x and Tomcat 4.x with mod_jk on Linux July 2, 2008

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

This FlashGuideTM covers integrating Apache 1.3.x and Tomcat 4.x on Unix via mod_jk. These instructions have been tested on SuSE 9.0, Red Hat 6.2 and Fedora Core 2. There are two ways to integrate Apache and Tomcat: mod_jk and mod_jk2. Mod_jk is the older but more stable version, which supports load balancing and non-standard web application locations. Mod_jk2 is newer, has bugs, and, as of 11/15/04, is no longer being actively developed.

These instructions are for the current version of Tomcat 4.1.31, but have worked the same for all previous versions of Tomcat.

If you are using an older version of Tomcat, note that there are known bugs when using mod_jk and Tomcat 4.0.1 or 4.0.2, so you must use 4.0.3 or greater.

1. Building Apache 1.3.x on Linux

Unless you can find a binary distribution of Apache with DSO support enabled, you will have to follow these instructions to build it yourself.

1. Check your prerequisites:

1. You will need GCC installed
2. You will need /usr/ccs/bin and the gcc executables in your $PATH

2. Download the latest Apache source from http://httpd.apache.org/download.cgi – currently, the latest is 1.3.33.
3. Unpack the distribution into a development directory (I used /usr/local)

The distribution directory will be something like apache_1.3.33
4. Cd into the distribution directory (e.g. /usr/local/apache_1.3.33)
5. Configure the makefile:

./configure –with-layout=Apache –prefix=/usr/local/apache –enable-rule=SHARED_CORE –enable-module=so

Read More

 

HttpSessionListener in Servlets June 12, 2008

Filed under: Java — javatechie @ 5:16 am
Tags:
public interface HttpSessionListener
extends java.util.EventListener

Implementations of this interface are notified of changes to the list of active sessions in a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.

sessionCreated

public void sessionCreated(HttpSessionEvent se)

Notification that a session was created.
Parameters:
se – the notification event

sessionDestroyed

public void sessionDestroyed(HttpSessionEvent se)

Notification that a session is about to be invalidated.
Parameters:
se – the notification event