Archive

Archive for the ‘General’ Category

FileUploadServlet

November 17, 2011 Comments off

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rapidhealth.dao.RapidHealthDAO;
import com.rapidhealth.pojo.DiscoveryConfig;
import com.rapidhealth.scp.SCPDispatcher;
import com.rapidhealth.utils.ApplicationContextHolder;

public class FileUploadServlet extends HttpServlet
{
private final Logger log = LoggerFactory.getLogger(FileUploadServlet.class);

private static final String TMP_DIR_PATH = "/tmp";
private static final String DESTINATION_DIR_PATH = "/repository";

private File tmpDir;
private File destinationDir;
private String realPath;

public void init(ServletConfig config) throws ServletException
{
super.init(config);
tmpDir = new File(TMP_DIR_PATH);
if (!tmpDir.isDirectory())
{
throw new ServletException(TMP_DIR_PATH + " is not a directory");
}
realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(realPath);
if (!destinationDir.isDirectory())
{
throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String fileName = null;

PrintWriter out = response.getWriter();
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
/*
* Set the size threshold, above which content will be stored on disk.
*/
fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
/*
* Set the temporary directory to store the uploaded files of size above
* threshold.
*/
fileItemFactory.setRepository(tmpDir);

ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try
{
/*
* Parse the request
*/
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
DiscoveryConfig config = new DiscoveryConfig();
while (itr.hasNext())
{
FileItem fi = (FileItem) itr.next();
/*
* Handle Form Fields.
*/
if ( fi.isFormField() )
{
System.out.println("File Name = " + fi.getFieldName() + ", Value = " + fi.getString());
if(fi.getFieldName().equals("sIp"))
{
config.setStartIp(fi.getString());
}else if(fi.getFieldName().equals("eIp"))
{
config.setEndIp(fi.getString());
}else if(fi.getFieldName().equals("un"))
{
config.setUserName(fi.getString());
}else if(fi.getFieldName().equals("pwd"))
{
config.setPwd(fi.getString());
}else if(fi.getFieldName().equals("dd"))
{
config.setDestFileDirLoc(fi.getString());
}
}
else
{
fileName = fi.getName();

config.setFileName(fileName);
config.setFileLoc(realPath+File.separatorChar+fileName);
config.setCreatedDateTime(System.currentTimeMillis());

File file = new File(destinationDir, fi.getName());
fi.write(file);
}
}
log.info("File {} uploaded successfully at location {}",fileName,destinationDir);

RapidHealthDAO healthDAO = (RapidHealthDAO)ApplicationContextHolder.getAppContext().getBean("rapidDAO");
healthDAO.saveorupdate(config);

log.debug("Configuration Saved to DB Successfully");

SCPDispatcher dispatcher = (SCPDispatcher)ApplicationContextHolder.getAppContext().getBean("scpPool");
dispatcher.startupload(config);
log.debug("File {} started uploading",config.getFileName());

out.print("File upload started successfully");
}
catch (Exception ex)
{
log("Error encountered while parsing the request", ex);

out.print("Failed to save data");
}
out.close();
}
}
Categories: General

javax.servlet.ServletException: Unrecognized HTTP request or response object

October 24, 2011 Comments off
Categories: General

java.lang.RuntimeException: mapped-name is required for org.apache.cxf.binding.BindingFactoryManagerImpl/bus of deployment

October 24, 2011 Comments off

For me this error occured while deploying a application.war file in the Jboss-5.1.

Solution to fix this is Add

<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-annotation_1.0_spec</artifactId>
<version>1.1.1</version>
<type>jar</type>
<scope>compile</scope>
<dependency>

Add this dependency to your  pom.xml or add this jar file to ant’s build.xml file.

 

Categories: General

Shell script to find the disk space and report when disk is full

September 29, 2011 Comments off

#!/bin/bash

# Set thresholds
min_free_space=2000
max_in_use_space=75

# Get a list of all file systems.
filesystems=`df -k | grep -v Use | grep -v none | awk ‘{ print $6 }’`

for filesystem in $filesystems
do
# Results for this file system.
entry=`df -k $filesystem | tail -1`

# Split out the amount of space free as well as in-use percentage.
free_space=`echo $entry | cut -d’ ‘ -f4`
in_use_space=`echo $entry | cut -d’ ‘ -f5 | cut -d’%’ -f1 `

# Check the file system percent in use.
if [ $(expr “$in_use_space > $max_in_use_space” ) ]
then
echo “$filesystem has only $free_space KB free at $in_use_space%.”
else
# Check the available space against threshold.
# Only make this check if the in use is OK.

result=$( echo ”
scale=2 /* two decimal places */
print $free_space < $min_free_space” | bc)

#if [ $(expr “$free_space < $min_free_space” ) ]
if [ $(expr “$result != 0” ) ]
then
echo “$filesystem has only $free KB free.”
fi
fi

done

 

URL : http://www.togotutor.com/forums/shell/58-shell-script-find-disk-space-report-when-disk-full.html

Categories: General

Very Useful Code Snippets For Web Developers

September 29, 2011 Comments off
Categories: General

Log4j Exception while reloading the application in JBoss 5

September 21, 2011 Comments off

[20 Sep 11 01:52:47,779|STDERR|http-0.0.0.0-8080-5]log4j:ERROR A “org.jboss.logging.appender.FileAppender” object is not assignable to a “org.apache.log4j.Appender” variable. [20 Sep 11 01:52:47,780|STDERR|http-0.0.0.0-8080-5]log4j:ERROR The class “org.apache.log4j.Appender” was loaded by [20 Sep 11 01:52:47,780|STDERR|http-0.0.0.0-8080-5]log4j:ERROR [WebappClassLoader [20 Sep 11 01:52:47,780|STDERR|http-0.0.0.0-8080-5]log4j:ERROR “org.jboss.logging.appender.FileAppender” was loaded by [org.jboss.system.server.NoAnnotationURLClassLoader@1bc82e7]. [20 Sep 11 01:52:47,780|STDERR|http-0.0.0.0-8080-5]log4j:ERROR Could not instantiate appender named “FILE”. [20 Sep 11 01:52:47,819|STDOUT|http-0.0.0.0-8080-5]01:52:47,819 ERROR [SpringContext] Context file is not loaded, as Context file is missing.

 

This is due to the conflict occured between the JBoss Log4j and the Log4j in used in the application.

remove Log4j from the war file before deploying.

in the Log4j.properties use Jboss Appenders insted of default log4j Appenders.

JBoss Log4j appenders can be found in conf/jbosslog4j.xml location.

 

 

 

Categories: General

Caused by: java.io.IOException: Stream is closed apache cxf

September 16, 2011 Comments off
Categories: General

java.lang.IllegalAccessError at net.sf.cglib.core.ClassEmitter.setTarget(ClassEmitter.java:47)

September 13, 2011 Comments off

Problem:

java.lang.IllegalAccessError
at net.sf.cglib.core.ClassEmitter.setTarget(ClassEmitter.java:45)
at net.sf.cglib.core.ClassEmitter.<init>(ClassEmitter.java:37)
at net.sf.cglib.core.KeyFactory$Generator.generateClass(KeyFactory.java:165)
at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:145)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:117)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104)
at net.sf.cglib.proxy.Enhancer.<clinit>(Enhancer.java:69)
at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.getProxyFactory(CGLIBLazyInitializer.java:117)
at org.hibernate.proxy.pojo.cglib.CGLIBProxyFactory.postInstantiate(CGLIBProxyFactory.java:43)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:162)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:135)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:55)

 

Solution : Please add the cglib-2.2.jar and asm-3.1.jar to your class path.

Categories: General

File upload and download with Jersy and Maven

September 2, 2011 Comments off

pom.xml file

<xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
 <groupId>com.test</groupId>
 <artifactId>filedownload</artifactId>
 <version>0.0.1</version>
 <packaging>war</packaging>
 <properties>
 <apacheds.version>1.5.5</apacheds.version>
 <client.shared.version>1.0</client.shared.version>
 <password.vault.pojo.version>1.0</password.vault.pojo.version>
 <cxf.version>2.3.1</cxf.version>
 </properties>
 <dependencies>
 <dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.14</version>
 </dependency>
 <dependency>
 <groupId>org.slf4j</groupId>
 <artifactId>slf4j-log4j12</artifactId>
 <version>1.5.2</version>
 </dependency>

<dependency>
 <groupId>commons-fileupload</groupId>
 <artifactId>commons-fileupload</artifactId>
 <version>1.2.1</version>
 </dependency>
 <dependency>
 <groupId>com.sun.jersey</groupId>
 <artifactId>jersey-server</artifactId>
 <version>1.1.0-ea</version>
 </dependency>
 <!-- depend on JAXB to enable WADL support -->
 <dependency>
 com.sun.xml.bind
 <artifactId>jaxb-impl</artifactId>
 <version>2.1.10</version>
 </dependency>
 <dependency>
 <groupId>org.mortbay.jetty</groupId>
 <artifactId>servlet-api-2.5</artifactId>
 <version>6.1.14</version>
 <scope>provided</scope>
 </dependency>
 <dependency>
 <groupId>bouncycastle</groupId>
 <artifactId>bcprov-jdk15</artifactId>
 <version>140</version>
 </dependency>
 <dependency>
 <groupId>commons-io</groupId>
 <artifactId>commons-io</artifactId>
 <version>2.0.1</version>
 <type>jar</type>
 <scope>compile</scope>
 </dependency>
 </dependencies>

<repositories>
 <repository>
 <id>maven2-repository.dev.java.net</id>
 <name>Java.net Repository for Maven</name>
 <url>http://download.java.net/maven/2/</url>
 <layout>default</layout>
 </repository>
 </repositories>

<build>
 <plugins>
 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-compiler-plugin</artifactId>
 <version>2.0.2</version>
 <configuration>
 <source>1.6</source>
 <target>1.6</target>
 <optimize>true</optimize>
 <showDeprecations>true</showDeprecations>
 <encoding>ISO-8859-1</encoding>
 </configuration>
 </plugin>
 <plugin>
 <groupId>org.mortbay.jetty</groupId>
 <artifactId>maven-jetty-plugin</artifactId>
 <version>6.1.16</version>
 <configuration>
 <scanIntervalSeconds>60</scanIntervalSeconds>
 <contextPath>/${project.artifactId}</contextPath>
 <systemProperties>
 <systemProperty>
 <key>jetty.port</key>
 <value>7009</value>
 </systemProperty>
 </systemProperties>
 </configuration>
 </plugin>
 </plugins>
 </build>
 </project>

Java Source code.

package com.test;
import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.util.List;

import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.Consumes;
 import javax.ws.rs.GET;
 import javax.ws.rs.POST;
 import javax.ws.rs.Path;
 import javax.ws.rs.Produces;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.Response.ResponseBuilder;
 import javax.ws.rs.core.Response.Status;

import org.apache.commons.fileupload.FileItem;
 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
 import org.apache.commons.fileupload.servlet.ServletFileUpload;

@Path("/config")
 public class FileDownloadUpLoadTest
 {
 private static final int MAX_FILE_SIZE = 2 * 1024 * 1024;

@GET
 @Path("downloadFile")
 @Produces("application/octet-stream")
 public Response downloadKeyStore()
 {
 ResponseBuilder builder = Response.status( Status.OK );
 try
 {
 File file = new File("/home/mindtree/Desktop/jxbrowser-2.9.jar");
 FileInputStream fis = new FileInputStream(file);
 ByteArrayOutputStream bos = new ByteArrayOutputStream();
 byte[] buf = new byte[1024];
 for (int readNum; (readNum = fis.read(buf)) != -1;)
 {
 bos.write(buf, 0, readNum);
 }
 builder.entity(bos.toByteArray());

} catch (IOException ex)
 {
 ex.printStackTrace();
 }

return builder.build();
 }

@POST
 @Path("uploadFile")
 @Consumes("multipart/form-data")
 @Produces("text/html")
 public String uploadKeystore( @Context HttpServletRequest request )
 {
 byte[] data = null;
 String fileName = null;
 try
 {
 DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
 fileItemFactory.setRepository(new File("/tmp"));

ServletFileUpload fileUpload = new ServletFileUpload( fileItemFactory );
 fileUpload.setSizeMax( 2 * MAX_FILE_SIZE ); // set the request max size to twice the max file size

List fileItems = fileUpload.parseRequest( request );

for ( FileItem fi : fileItems )
 {
 if ( fi.isFormField() )
 {
 System.out.println( "form field "+ fi );
 }
 else
 {
 String fieldName = fi.getFieldName();
 System.out.println("fieldName"+fieldName);

fileName = fi.getName();
 System.out.println("fileName"+fileName);

String contentType = fi.getContentType();
 System.out.println("contentType"+contentType);

boolean isInMemory = fi.isInMemory();
 System.out.println("isInMemory"+isInMemory);

long sizeInBytes = fi.getSize();
 System.out.println("sizeInBytes"+sizeInBytes);

data = fi.get();
 }
 }

//below is the different part
 File someFile = new File(fileName);
 FileOutputStream fos = new FileOutputStream(someFile);
 fos.write(data);
 fos.flush();
 fos.close();

System.out.println("uploaded successfully");
 }
 catch ( Exception e )
 {
 e.printStackTrace();
 }

return "uploaded successfully";
 }
 }

web.xml file

<?xml version="1.0" encoding="UTF-8"?>

<!--DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
 <web-app>

<listener>
 <listener-class>
 org.apache.commons.fileupload.servlet.FileCleanerCleanup
 </listener-class>
 </listener>

<servlet>
 <servlet-name>Jersey-REST-servlet</servlet-name>
 <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
 <init-param>
 com.sun.jersey.config.property.packages
 <param-value>com.test</param-value>
 </init-param>
 </servlet>

<servlet-mapping>
 <servlet-name>Jersey-REST-servlet</servlet-name>
 /pv/*
 </servlet-mapping>

<welcome-file-list>
 config.html
 </welcome-file-list>
 </web-app>

HTML File.
This includes Jquery files.Download jquery and add to the project path.

<!--DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>File download and upload sample</title>
 css" href="css/jquery-ui-1.7.2.custom.css"
 rel="stylesheet" />
 <script type="text/// <![CDATA[
 javascript" src="js/jquery-1.3.2.min.js">
 // ]]>
 <script type="text/// <![CDATA[
 javascript" src="js/jquery-ui-1.7.2.custom.min.js">
 // ]]>
 <script type="text/javascript">
 $(function()
 {
 $("#tabs").tabs();
 });

$(document).ready(function()
 {
 $("#submitFrame").load(function(){
 var jsonResult = jQuery(submitFrame.document.body).html();
 showDialog( jsonResult );
 } );
 });
 function showDialog( text )
 {
 $("#dialog").attr({ innerHTML: text });
 $("#dialog").dialog(
 {
 bgiframe: true,
 modal: false,

});
 $("#dialog").dialog( 'open' );
 }
 </script>
 </head>
 <body>
 <div>
<div>20px; padding: 0 .7em;"></div>
<p align="center">File Download and Upload Sample</p>
 </div>
 </div>
 <br />
 <div id="tabs">
 <ul>
 <li><a href="#tabs-1">Download File</a></li>
 <li><a href="#tabs-2">Upload File</a></li>
 </ul>
<div id="tabs-1">1px solid black; text-align: left;"></div>
<a href="pv/config/downloadFile"> Click here to download the file</a>
 </div>
<div id="tabs-2">1px solid black; text-align: left;"></div>
<form id="uploadKeyForm" method="post" enctype="multipart/form-data" action="pv/config/uploadFile" target="submitFrame">
 <table width="100%">
 <tr>
 <td>
 <table>
 <tr>
 <td>File:</td>
 <td><input id="ks" name="ks" type="file"></td>
 </tr>
 <tr>
 <td><input type="submit" id="uploadKey" value="Upload Keys"></td>
 </tr>
 </table>
 </td>
 </tr>
 </table>
 </form>
 <iframe id="submitFrame" name="submitFrame"
 style="display: none; visibility: hidden"> </iframe></div>
 </div>
 </div>
 <!-- end of tabs div -->
 <div id="dialog" title="Vault Configurator"></div>
 </body>
 </html>
Categories: General

Adding file to Maven Repository with Maven

July 21, 2011 Comments off

Maven has made compiling Java projects almost an effortless job. You no longer need to worry about placing all the required class files in your classpath. All you have to do is to include dependencies in your POM file and Maven takes care of the rest. It automatically downloads the jar file that your project depends on and include them in your build classpath. But what if you want to include a jar file that is not available from Maven repositories? To include such jar files you will have to manually install the jar into your local maven repository. Let say you need Oracle driver which is included in ojdbc14.jar. Download the jar file from Oracle and then execute following command.

C:\>mvn install:install-file -Dfile=ojdbc14.jar -DgroupId=com.oracle -DartifactId=ojdbc14 -Dversion=10.2.0 -Dpackaging=jar

Then add this dependency to your project POM file.

      com.oracle
      ojdbc14
      10.2.0
      compile
Now when you build your project ojdb14.jar will be available.

You can follow the same steps for your own jar files. For example if you have created a jar file (e.g. utils.jar) of helper classes and need that jar file in some other project you will first install the jar to your repository and then add the dependency in your POM file.

C:\>mvn install:install-file -Dfile=utils.jar -DgroupId=com.zparacha.example -DartifactId=utils -Dversion=1.0 -Dpackaging=jar

And the dependency for your POM will be like

      com.zparacha.example
      utils
      1.0.0
      compile

And all the class files will become available to your project.
Enjoy.

 

Reference : http://www.zparacha.com/include-externaljar-file-in-maven/

Categories: General