Thursday, June 18, 2009
Concurrent HashMap vs HashMap
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 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 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
Hope this helps anyone else who might face this prob in the future.
Tuesday, April 28, 2009
Java regex tip
Friday, April 17, 2009
Parsing with JavaCC
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.....
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();