Wednesday, May 31, 2006

File Upload in Java

First u have to create a Web page frm which u select a file

call it FileUpload.html


<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252"/>
<TITLE>File Upload Page</TITLE>
</HEAD>
<BODY>Upload Files
<form name="uploadForm" action="ProcessFileUpload.jsp" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input TYPE=Button name='Upload' Value='Upload' onClick="uploadForm.Upload.value='Uploading...';document.uploadForm.action='ProcessFileUpload.jsp';document.uploadForm.submit()">
</form>
</BODY>
</HTML>

Then create a JSp page which handles the input stream

call it ProcessFileUpload.jsp

<%

response.setContentType("text/html");
response.setHeader("Cache-control","no-cache");

String err = "";

String lastFileName = "";

String contentType = request.getContentType();
String boundary = "";
final int BOUNDARY_WORD_SIZE = "boundary=".length();
if(contentType == null || !contentType.startsWith("multipart/form-data")) {
err = "Ilegal ENCTYPE : must be multipart/form-data\n";
err += "ENCTYPE set = " + contentType;
}else{
boundary = contentType.substring(contentType.indexOf("boundary=") + BOUNDARY_WORD_SIZE);
boundary = "--" + boundary;
try {
javax.servlet.ServletInputStream sis = request.getInputStream();
byte[] b = new byte[1024];
int x=0;
int state=0;
String name=null,fileName=null,contentType2=null;
java.io.FileOutputStream buffer = null;
while((x=sis.readLine(b,0,1024))>-1) {
String s = new String(b,0,x);
if(s.startsWith(boundary)) {
state = 0;
//out.println("name="+name+"<br>");
//out.println(fileName+"<br>");

name = null;
contentType2 = null;
fileName = null;


}else if(s.startsWith("Content-Disposition") && state==0) {
state = 1;
if(s.indexOf("filename=") == -1)
name = s.substring(s.indexOf("name=") + "name=".length(),s.length()-2);
else {
name = s.substring(s.indexOf("name=") + "name=".length(),s.lastIndexOf(";"));
fileName = s.substring(s.indexOf("filename=") + "filename=".length(),s.length()-2);
if(fileName.equals("\"\"")) {
fileName = null;
}else {
String userAgent = request.getHeader("User-Agent");
String userSeparator="/"; // default
if (userAgent.indexOf("Windows")!=-1)
userSeparator="\\";
if (userAgent.indexOf("Linux")!=-1)
userSeparator="/";
fileName = fileName.substring(fileName.lastIndexOf(userSeparator)+1,fileName.length()-1);
if(fileName.startsWith( "\""))
fileName = fileName.substring( 1);
}
}
name = name.substring(1,name.length()-1);
if (name.equals("file")) {
if (buffer!=null)
buffer.close();
lastFileName = fileName;
buffer = new java.io.FileOutputStream(application.getRealPath("/")+"/"+fileName);
}
}else if(s.startsWith("Content-Type") && state==1) {
state = 2;
contentType2 = s.substring(s.indexOf(":")+2,s.length()-2);
}else if(s.equals("\r\n") && state != 3) {
state = 3;
}else {
if (name.equals("file"))
buffer.write(b,0,x);
}
}
sis.close();
buffer.close();
}catch(java.io.IOException e) {
err = e.toString();
}
}
boolean ok = err.equals("");
if(!ok) {
out.println(err);
}else{
%>
<SCRIPT language="javascript">
history.back(1)
alert('Uploaded <%=lastFileName%>');
window.location.reload(false)
</SCRIPT>
<%
}
out.println("done");
%>


This code uploads file in the home directory of ur context.This has been define in Scriplet

java.io.FileOutputStream(application.getRealPath("/")+"/"+fileName);

Sunday, April 23, 2006

AJAX Getting Started

Let’s begin

Creating a request object is different depending on the users browser version. The code below checks for browsers and uses the proper request.


Next we create the AJAX request and how we want to handle the response. The sendRequest() function below will send a HTTP GET request to the server for the XML document. The handleResponse() function checks to see if the request is finished and if so returns the response.

AJAX readyState Status Codes:

0 - uninitialized 1 - loading 2 - loaded 3 - interactive 4 - complete



var req = createXMLHttpRequest();

The following can be your connect function


function AJAXRequest( method, url, data, process, async, dosend) {
// self = this; creates a pointer to the current function
// the pointer will be used to create a "closure". A closure
// allows a subordinate function to contain an object reference to the
// calling function. We can't just use "this" because in our anonymous
// function later, "this" will refer to the object that calls the function
// during runtime, not the AJAXRequest function that is declaring the function
// clear as mud, right?
// Java this ain't

var self = this;

// check the dom to see if this is IE or not
if (window.XMLHttpRequest) {
// Not IE
self.AJAX = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// Hello IE!
// Instantiate the latest MS ActiveX Objects
if (_ms_XMLHttpRequest_ActiveX) {
self.AJAX = new ActiveXObject(_ms_XMLHttpRequest_ActiveX);
} else {
// loops through the various versions of XMLHTTP to ensure we're using the latest
var versions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
"Microsoft.XMLHTTP"];

for (var i = 0; i < versions.length ; i++) {
try {
// try to create the object
// if it doesn't work, we'll try again
// if it does work, we'll save a reference to the proper one to speed up future instantiations
self.AJAX = new ActiveXObject(versions[i]);

if (self.AJAX) {
_ms_XMLHttpRequest_ActiveX = versions[i];
break;
}
}
catch (objException) {
// trap; try next one
} ;
}

;
}
}

// if no callback process is specified, then assing a default which executes the code returned by the server
if (typeof process == 'undefined' || process == null) {
process = executeReturn;
}

self.process = process;

// create an anonymous function to log state changes
self.AJAX.onreadystatechange = function( ) {
//logger("AJAXRequest Handler: State = " + self.AJAX.readyState);
self.process(self.AJAX);
}

// if no method specified, then default to POST
if (!method) {
method = "POST";
}

method = method.toUpperCase();

if (typeof async == 'undefined' || async == null) {
async = true;
}

logger("----------------------------------------------------------------------");
logger("AJAX Request: " + ((async) ? "Async" : "Sync") + " " + method + ": URL: " + url + ", Data: " + data);

self.AJAX.open(method, url, async);

if (method == "POST") {
self.AJAX.setRequestHeader("Connection", "close");
self.AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
self.AJAX.setRequestHeader("Method", "POST " + url + "HTTP/1.1");
}

// if dosend is true or undefined, send the request
// only fails is dosend is false
// you'd do this to set special request headers
if ( dosend || typeof dosend == 'undefined' ) {
if ( !data ) data="";
self.AJAX.send(data);
}
return self.AJAX;
}






function sendRequest(id) {
}

function handleResponse() {

if(req.readyState == 4){
var response = req.responseText;

}

alert("loading" + req.readyState);

}


On to the HTML

Now we need to link to the javascript sendRequest() function.

Tuesday, April 18, 2006

Producer Consumer Problem

First Create a package learning
then

create following java files
1) Shared Object
2) Producer
3) Consumer
4) Main Class

-------------------------------------------------------------------------------
package learning;

/**
*
* @author AshwinK
*/
public class Shared {

/** Creates a new instance of Shared */
public Shared() {
}

synchronized void setSharedChar(char c){
if(!writable){
try{
wait();
}catch(InterruptedException e){

}
}
System.out.println(c+"---Produced by Producer");
this.c = c;
writable = false;
notify();
}


synchronized char getSharedChar(){
if(writable){
try{
wait();
}catch(InterruptedException e){

}
}

writable = true;
System.out.println(c+"---Consumed by Consumer");
notify();
return c;
}

private char c = '\u0000';
private boolean writable = true;

}
-------------------------------------------------------------------------------
Now create producer

-------------------------------------------------------------------------------
package learning;

/**
*
* @author AshwinK
*/
public class Producer extends Thread{

private Shared s;
/** Creates a new instance of Producer */
public Producer(Shared s) {
this.s = s;
}

public void run(){
for(char ch = 'A'; ch <= 'Z';ch++){
try{
Thread.sleep((int)(Math.random()*2000));
}catch(InterruptedException e){

}
s.setSharedChar(ch);

}
}

}

-------------------------------------------------------------------------------
Now Create Consumer
-------------------------------------------------------------------------------
package learning;

/**
*
* @author AshwinK
*/
public class Consumer extends Thread{
private Shared s;
/** Creates a new instance of Consumer */
public Consumer(Shared s){
this.s = s;
}

public void run(){
char ch;
do{
try{
Thread.sleep((int)(Math.random()*1000));
}catch(InterruptedException e){

}
ch = s.getSharedChar();

}while(ch!='Z');
}
}
-------------------------------------------------------------------------------


Create Main
-------------------------------------------------------------------------------

package learning;

/**
*
* @author AshwinK
*/
public class Main {

/** Creates a new instance of Main */
public Main() {
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Shared s = new Shared();
new Producer(s).start();
new Consumer(s).start();
}

}
-------------------------------------------------------------------------------

You need basic understanding of thread's to understand this post.I'll heading with threading tutorial from tommorrow

Monday, April 17, 2006

Getting and Playing with Date in Java

Many people have been finding it difficult to format dates and have been creating parsers to format date strings.This post unleashes how a java inbuilt mechanism can be used to format date


/*
* ShowToday.java
*
* Created on March 31, 2006, 2:06 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

package learning;

/**
*
* @author AshwinK
*/
import java.util.*;
import java.text.*;

public class GetToday {
public static void main(String args[]) {
GetToday gt = new GetToday();
gt.test();
}
public void test() {
System.out.println(testDateFormat("dd MMMMM yyyy"));
System.out.println(testDateFormat("yyyyMMdd"));
System.out.println(testDateFormat("dd.MM.yy"));
System.out.println(testDateFormat("MM/dd/yy"));
System.out.println(testDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z"));
System.out.println(testDateFormat("EEE, MMM d, ''yy"));
System.out.println(testDateFormat("h:mm a"));
System.out.println(testDateFormat("H:mm:ss:SSS"));
System.out.println(testDateFormat("K:mm a,z"));
System.out.println(testDateFormat("yyyy.MMMMM.dd GGG hh:mm aaa"));
}

public String testDateFormat (String format) {
Date today = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(format);
String datenewformat = formatter.format(today);
return datenewformat;
}
}


Java assign's each alphabet to corresponding date part for example

y -- Year
M -- Month
d -- Day
h -- Hour
m -- Minute
s -- Second

if we give format as yyyymmddhhmmss and date is 2005-04-12 12:12:12

output would be like 20050412121212

If any doubt's mail me at ashwin.rayaprolu@gmail.com

Dynamic Compilation in java

Many guyz may have faced problem while compiling Java file using Runtime.exec as it creates unnessary process. Here is a way which is pure java version as on how to compile and Load compiled java butecode dynamically.

Here is the sample code for it

import sun.tools.javac.Main;
import java.util.*;
import java.lang.*;
import java.io.*;


/**
* To use the DynamicCompiler you simply add it to your program
* and add an interface for selecting the macro, then use the simple
* methods of this class to compile and execute a macro.
* The class offers several features:
* 1. Interaction with your application.
* 2. The full power you had writing the application will be available
* to your users.
* 3. You can add a sandbox to block some functionality.
* 4. You can ship upgrades/fixes as plugins.
* 5. Other vendors and users can easily write plugins.
* 6. Plugins will be fully integrate, cross platform and run in the
* same speed as the VM.
* It is recommended you expose some of your software's internals
* to your users to make this tool more effective.
**/
public class DynamicCompiler extends ClassLoader
{
MacroExtension()
{
compilerClass = new sun.tools.javac.Main(System.out,"");
}

/**
* This method accepts a class file as parameter
* and returns an instance of it.
**/
public Object getObject(String fileName)
throws java.lang.ClassNotFoundException,
java.lang.InstantiationException,
java.lang.IllegalAccessException
{
Class classInstance = getClass();
return(classInstance.forName(fileName).newInstance());
}

/**
* This method accepts a java file as parameter and compiles it.
* It returns true if compilation was successful and false otherwise.
**/
public boolean compile(String fileName)
{
String [] stringArr = new String[1];
stringArr[0] = fileName;
return(compilerClass.compile(stringArr));
}

/**
* This method returns a vector in which all
* the compilation errors are stored as strings.
**/
public Vector getCompilationErrors()
{
return(dataStream.getStringsWritten());
}

/**
* The main method is conveniently located here for testing purposes.
**/
public static void main(String argv[])
{
MacroExtension m = new MacroExtension();
//m.compile("HelloWorld.java");
System.out.println("After compiling"+m.compile("HelloWorld.java"));
m.loadObject("HelloWorld");
}

/**
* creates an instance of a class by getting its name
* and returns that instance, or null if none were found.
**/
public Object loadObject(String className)
{
try
{
loadClass(className, true);
return(getObject(className));
}
catch(java.lang.ClassNotFoundException e)
{
System.out.println("Class not found exception: " + e.getMessage());
}
catch(java.lang.InstantiationException e)
{
System.out.println("Instantiation exception: " + e.getMessage());
}
catch(java.lang.IllegalAccessException e)
{
System.out.println("Illegal access exception : " + e.getMessage());
}
catch(Exception e)
{
System.out.println("An exception was thrown: " + e.getMessage());
}
return(null);
}


protected Class loadClass(String className, boolean callReslove)
{
Class returnValue = (Class) classCache.get(className);

if(returnValue != null)
return(returnValue);

String classFullName;

try
{
File classFile;
if (!className.endsWith(".class"))
classFullName = className + ".class";
else
{
className = className.substring(0, className.length() - 5);
System.out.println("Class name is: " + className);
classFullName = className + ".class";
}

classFile = new File(classFullName);

FileInputStream inFile = new FileInputStream(classFile);
byte[] classData = new byte[(int)classFile.length()];

inFile.read(classData);

inFile.close();

returnValue = defineClass(className, classData, 0, classData.length);

classCache.put(className, returnValue);
}
catch(IOException ioerr)
{
try
{
returnValue = findSystemClass(className);
return(returnValue);
}
catch (Exception anyException)
{
System.out.println("File access error: " + anyException.getMessage());
return(null);
}
}

if(callReslove)
{
resolveClass(returnValue);
}

return(returnValue);
}

/**
* Notice the long name. It's here to avoid namespace
* problems with another Main
**/
private sun.tools.javac.Main compilerClass;
private OutputStream dataStream = System.out;
private Hashtable classCache = new Hashtable();
}

Send outlook Meeting from java

First you whould add a MIME type in activation.jar and mail.jar called "text/calendar". It's quite simple, treat them like plain text.

in activation/META-INF/mimetypes.default add:
text/calendar ics ICS

and in mail/META-INF/mailcap add:
text/calendar;; x-java-content-handler=com.sun.mail.handlers.text_plain



/*
* EmailMeeting2.java
*
* Created on April 18, 2006, 10:12 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

package javamail;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
*
* @author AshwinK
*/
public class EmailMeeting2 {

/** Creates a new instance of EmailMeeting2 */
public EmailMeeting2() {
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try
{
EmailMeeting2 email = new EmailMeeting2();
email.send();
}
catch (Exception e)
{
e.printStackTrace();
}
}


public void send() throws Exception {

try {
String host = "server.interrait.com";
String from = "ashwink@interrait.com";
String to = "ashwink@interrait.com";

// Get system properties
Properties props = System.getProperties();

// Setup mail server
props.put("mail.smtp.host", host);

// Get session
Session session = Session.getInstance(props, null);

// Define message
MimeMessage message = new MimeMessage(session);
message.addHeaderLine("method=REQUEST");
message.addHeaderLine("charset=UTF-8");
message.addHeaderLine("component=vevent");
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(from));
message.setSubject("Outlook Meeting Request Using JavaMail");

StringBuffer sb = new StringBuffer();

StringBuffer buffer = sb.append("BEGIN:VCALENDAR\n"+
"PRODID:-//Microsoft Corporation//Outlook 9.0 MIMEDIR//EN\n"+
"VERSION:2.0\n"+
"METHOD:REQUEST\n"+
"BEGIN:VEVENT\n"+
"ATTENDEE;CN=\"SVGK, Raju (Raju)\";ROLE=REQ-PARTICIPANT;MAILTO:ashwink@interrait.com\n"+
"ATTENDEE;CN=\"SV, Raj (Raj)\";ROLE=OPT-PARTICIPANT;MAILTO:ashwink@interrait.com\n"+
"ORGANIZER:MAILTO:ashwink@interrait.com\n"+
"DTSTART:20050406T073000Z\n"+
"DTEND:20050406T080000Z\n"+
"LOCATION:conf\n"+
"TRANSP:OPAQUE\n"+
"SEQUENCE:0\n"+
"UID:040000008200E00074C5B7101A82E00800000000A0A742E5073AC5010000000000000000100\n"+
" 0000029606C073D82204AB6C77ACE6BC2FBE2\n"+
"DTSTAMP:20050405T122004Z\n"+
"CATEGORIES:Meeting\n"+
"DESCRIPTION:What are you doing?\n\n"+
"SUMMARY:How are you?\n"+
"PRIORITY:5\n"+
"CLASS:PUBLIC\n"+
"BEGIN:VALARM\n"+
"TRIGGER:PT1440M\n"+
"ACTION:DISPLAY\n"+
"DESCRIPTION:Reminder\n"+
"END:VALARM\n"+
"END:VEVENT\n"+
"END:VCALENDAR\n");

// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();

messageBodyPart.setHeader("Content-Class", "urn:content-classes:calendarmessage");
messageBodyPart.setHeader("Content-ID","calendar_message");
messageBodyPart.setContent(buffer.toString(), "text/calendar");
// Fill the message
messageBodyPart.setText("You are requested to participlate in the review meeting.");

// Create a Multipart
Multipart multipart = new MimeMultipart();

// Add part one
multipart.addBodyPart(messageBodyPart);

// Part two is attachment
// Create second body part
messageBodyPart = new MimeBodyPart();
String filename = "How are you.ics";
messageBodyPart.setFileName(filename);
messageBodyPart.setContent(buffer.toString(), "text/plain");

// Add part two
multipart.addBodyPart(messageBodyPart);

// Put parts in message
message.setContent(multipart);

// send message
Transport.send(message);
} catch (MessagingException me) {
me.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Monday, March 06, 2006