Friday, July 31, 2009

@BatchSize() Annotation in hibernate

While searching on the net on how to gain perfomance in JPA/Hibernate i stumbled upon an article written on hibernate annotation batchsize and it intrigued me on how it really works. After reading on and going through the algorythm defined by Hibernated on how it works i understood that this adds a sufficient perfomance gain in the event of you having large collections within your entities.

 --------Updated on 07/30/2012 according to the clarification given by Jeremy---------

For example lets consider an Airport parent containing a collection of airlines as such;

    @OneToMany()
    List<Airlines> airlines = new ArrayList<Airlines>();
Imagine you had such a statement in one of your entities. Assume there can be 100 Airport objects at any given time.Without the BatchSize annotation, Hibernate will first retrieve the Airports separately and for each airport it will retrieve the airlines separately. Now consider the following code snippet;
    @OneToMany
    @BatchSize(size=16)
   List<Airlines> airlines = new ArrayList<Airlines>();
When you use the batch size annotation what hibernate does is it divides the number of elements that would come in the resulting query by the batch size defined. In this case its 100 / 16 so you get 6 and remainder 4. What this implies is hibernate will go to the database 6 times to fetch 16 Airport objects' with their Airlines collection initialized and then go again another time to retrieve the remaining 4 Airports again with their Airlines collection initialized. So what the @BatchSize does is decide how many collections should be initialized.

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.