Thursday, June 18, 2009

Concurrent HashMap vs HashMap

So today i looked into these two Map types to use in the multi threaded application im working on. It was really confusing to understand the exact differences between the two but after some research this is my vedict;

Use ConcurrentHashMap if you only want to concurrently add and remove values and do not want to access the map while concurrent additions and modifications go on. But if you do want to access data while concurrent additions and modifications are going on then its better to use Collections.synchronizedHashMap() and make the iteration code block thread safe in order to avoid race conditions.

Wednesday, June 17, 2009

Simple Java Mail SMTP Client

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

class SimpleMail {
static Message emailMessage;

public static void main(String[] args) {

try {

emailMessage = new MimeMessage(createSession());
// replace this with the TO mail address
InternetAddress add = new InternetAddress("receipeicnt@abc.com");
InternetAddress[] addresses = new InternetAddress[1];
addresses[0] = new InternetAddress("d");
emailMessage.setFrom(add);
emailMessage.setRecipients(javax.mail.Message.RecipientType.TO,
addresses);
emailMessage.setSubject("My Subject ");
emailMessage.setContent("My First Mail", "text/plain");
emailMessage.saveChanges();

Transport.send(emailMessage);

} catch (AddressException e) {

e.printStackTrace();
} catch (MessagingException e) {

e.printStackTrace();
}

}

private static Session createSession() {

Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "your_mail_server_IP");

// If your sending multiple mails and even if one mail fails this by
// setting
// this property all the other mails except that mail will still be
// delievered
props.put("mail.smtp.sendpartial", "true");

Authenticator authenticator = null;

props.put("mail.smtp.auth", "true");
// enter your mail address and password here
authenticator = new MessagingAuthenticator("xxx@abc.com", "password");

return Session.getDefaultInstance(props, authenticator);
}
}

class MessagingAuthenticator extends Authenticator {
private String userName;
private String password;

public MessagingAuthenticator(String userName, String password) {
this.userName = userName;
this.password = password;
}

public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}

Simple Java Mail Pop 3 client

import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;

public class POP3Client {

public static void main(String args[]) throws Exception {
String host = "your_mail_server_ip";

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


Session session = Session.getDefaultInstance(props, null);

// Get the store
Store store;
store = session.getStore("pop3");
store.connect(host, "xxx@abc.com", "password");

// Get inbox folder

Folder folder = store.getDefaultFolder().getFolder("INBOX");
folder.open(Folder.READ_WRITE);


// Get directory
Message message[] = folder.getMessages();
for (int i = 0, n = message.length; i < n; i++) {

System.out.println(i + ": Subject" + message[i].getFrom()[0] + "\t"
+ message[i].getSubject());
String content = message[i].getContent();


System.out.print(content);
//This will delete the mail from the inbox after you close the folder
message[i].setFlag(Flags.Flag.DELETED, true);
}

// Close connection
folder.close(true);
store.close();

}

}

Small glitch in the Java Mail API when used in the Linux Environment

I was writing a Java Mail POP3 client recently and was reading both multi part and plain text mails, getting the body text and persisting that text to the database. This worked fine when i tested it in the Windows environment. But when we deployed the application in a Linux environment we saw that the database had one extra blank line coming in between each new line. When we debugged this it came down to the point where we get the body text from the message using the getContent() method provided by the Java Mail API. And in this too it was showing a new line in between each line and hence i had to write a regex to get rid of that extra line before persisting to the database.

Hope this helps anyone else who might face this prob in the future.

Tuesday, April 28, 2009

Java regex tip

While working on a message parser based on java regex i had the need of breaking down messages and being able to ignore certain results from the group because i did not want those values to be considered. Searching on the net did not yield any results hence i went to one of my superiors at work and got to know the answer to this and hence wanted to share it with all of you so that the next time any one does search for a similar problem they might stumble upon this blog ;) ... So the solution is as follows;
 
String simplReg = ([A-B]{4} (?:(0-9){2}));
 
The '?:' operators are used in the second group to specify to java regex that the second group should be ignored from the final result. Thats it guys... Until my next post its adios from my side :D

Friday, April 17, 2009

Parsing with JavaCC

Currently i am working on deciphering a message with a certain format and filling in some DTOs(Data transfer objects) which were then sent to be stored in the database. First i looked at using java regex to do the task but found it was getting way too complicated and the code was not much readable which would result in maintenance problems in the future. After searching around on the net for a few minutes i stumbled upon a library which was originally developed by Sun called JavaCC which is basically a lexical analyser and parser generator. After going through some samples i was able to figure out the expressions used and was able to decipher the message and store releavant data in respective DTO attributes to be sent to the DB.
 
Following i have given a sample code which i used in the early stages to try out a HelloWorld kind of scenario.
 

options{

STATIC=false;

}

PARSER_BEGIN(FLW)

import java.io.*;

public class FLW{

public static void main(String ar[]){

CustomerDTO dtos = getDTO("xxxx 40,dddddddddd eeeeeeeeeer");

System.out.println("First Name: "+dtos.getFName());

System.out.println("Last Name: "+dtos.getLName());

System.out.println("Address : "+dtos.getAddress());

}

static CustomerDTO getDTO(String inString){

Reader reader = new StringReader(inString);

FLW parser = new FLW(reader);

StringBuffer buf = new StringBuffer();

try{

return parser.parse();

}

catch(Exception e){

System.out.println("exception");

e.printStackTrace();

}

return null;

}

}

PARSER_END(FLW)

TOKEN:{<SPACE:" ">}

TOKEN:{<#COMMA:",">}

TOKEN:{<FIRST_NAME:(<LETTER>){4}>}

TOKEN:{<ADDRESS:(<NUMBER>){2}(<COMMA>){1}(<LETTER>){10}>}

TOKEN:{<LAST_NAME:(<LETTER>){11}>}

TOKEN:{<#LETTER:["a"-"z","A"-"Z"]>}

TOKEN:{<#NUMBER:["0"-"9"]>}

CustomerDTO parse():

{

Token fName;

Token lName;

Token address;

CustomerDTO cusDTO = new CustomerDTO();

}

{

(

((fName=<FIRST_NAME>

{cusDTO.setFName(fName.image);}))

<SPACE>

(address=<ADDRESS>)

{cusDTO.setAddress(address.image);}

<SPACE>

(lName=<LAST_NAME>)

{cusDTO.setLName(lName.image);}

)

{return cusDTO;}

}

 

Note that you have to first install JavaCC and also create the CustomerDTO which is in the default class path in the above example and store this in a file named xxx.jj. What the above code does is basically break down the string message passed in the main method and put the relevant data in the relvant attributes of the DTO. Note that JavaCC automatically hanldes EOF(End of file). Hope this helps anyone who is looking at how to use JavaCC for such scenario.


Wednesday, April 8, 2009

JFreeChart For The Web Cont.....

Ok my last post showed you guys as to how to display JFreeCharts in your web application. One issue with that code that i later realized that was it does not support concurrency due to the fact that it creates a temporary file with the same name and if two pepole requests for the same chart at the same time there might be unpredictable outputs and hence i went throught their API again and found a way to resolve this issue. Use the following code if you need to support concurrency when genearating reports and this method anyway is much better performance vice as it does not include any I/O operations which is always an overhead to the application.
 

JFreeChart chart = ChartFactory.createBarChart(chartTitle,

xAxisName, yAxisName, dataSet, PlotOrientation.VERTICAL,

false, true, false);

 

OutputStream outStream = response.getOutputStream();

ByteArrayOutputStream byteArray = new ByteArrayOutputStream();

ChartUtilities.writeChartAsPNG(byteArray, chart, 800, 500);

byte[] byteStream = null;

byteStream = byteArray.toByteArray();

response.setContentType("image/png");

response.setContentLength((int) byteStream.length);

response

.setHeader("Cache-Control",

"no-store, no-cache, must-revalidate, post-check=0, pre-check=0");

response.setHeader("Pragma", "no-cache");

outStream.write(byteStream);

outStream.flush();

outStream.close();