Sunday, February 26, 2012
DATABASE INITIALIZER UTILITY..
package com.dbInitializer;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.dao.ConnectionManager;
import com.propertyReader.PropertyReader;
import com.utility.MailUtil;
import com.utility.Utilities;
/**
* The Class DBInitializer.
*/
public class DBInitializer {
/**
* Instantiates a new dB initializer.
*/
public DBInitializer() {
super();
logger.info("DBInitializer instantiated..");
}
/** The logger. */
private static final Log logger = LogFactory.getLog(DBInitializer.class);
/** The Constant username. */
private static final String username=PropertyReader.getProperty("dbInitUserName");
/** The Constant password. */
private static final String password=MailUtil.getRandomString(8);
/** The Constant firstName. */
private static final String firstName=PropertyReader.getProperty("dbInitFirstName");
/** The Constant lastName. */
private static final String lastName=PropertyReader.getProperty("dbInitLastName");
/** The Constant emailId. */
private static final String emailId=PropertyReader.getProperty("dbInitEmail");
/** The Constant role. */
private static final String role=PropertyReader.getProperty("dbInitRole");
/** The Constant dbName. */
private static final String dbName=PropertyReader.getProperty("dbInitDBNAME");
/** The Constant tableName. */
private static final String tableName=PropertyReader.getProperty("dbInitTableName");
/** The Constant createDBStmt. */
private static final String createDBStmt="create database "+dbName;
/** The Constant createTableStmt. */
private static final String createTableStmt="CREATE table "+tableName+" (username varchar(50) NOT NULL,password varchar(50),firstName varchar(50),lastName varchar(50),emailId varchar(50) NOT NULL,role varchar(50),lastLogin varchar(50),forgetPassword varchar(20) DEFAULT 'false',PRIMARY KEY (emailId),UNIQUE (username))";
/** The Constant insertInitUser. */
private static final String insertInitUser="INSERT INTO "+tableName+" (username, password, firstName,lastName,emailId,role) VALUES (?, ?, ?,?,?,?)";
/** The flag. */
public static volatile boolean flag=false;
/**
* Gets the username.
*
* @return the username
*/
public static String getUsername() {
return username;
}
/**
* Gets the password.
*
* @return the password
*/
public static String getPassword() {
return password;
}
/**
* Gets the firstname.
*
* @return the firstname
*/
public static String getFirstname() {
return firstName;
}
/**
* Gets the lastname.
*
* @return the lastname
*/
public static String getLastname() {
return lastName;
}
/**
* Gets the emailid.
*
* @return the emailid
*/
public static String getEmailid() {
return emailId;
}
/**
* Creates the db and tables.
*
* @return true, if successful
* @throws SQLException the sQL exception
*/
public static boolean createDBAndTables()throws SQLException{
logger.info("Creating initial database and tables..");
boolean flagInt=false;
Connection con=ConnectionManager.getConnectionCommon();
ResultSet rs = con.getMetaData().getCatalogs();
while (rs.next()) {
if(!rs.getString("TABLE_CAT").equals(dbName)){
flagInt=true;
}
else{
flagInt=false;
}
}
if(flagInt){
createDB(con,createDBStmt);
}
else{
logger.info("Specified DB already exist!");
con.close();
}
flag=flagInt;
return flagInt;
}
/**
* Creates the db.
*
* @param dbConnection the db connection
* @param createStmt the create stmt
* @return true, if successful
* @throws SQLException the sQL exception
*/
private static boolean createDB(Connection dbConnection,String createStmt)throws SQLException{
logger.info("Creating initial database..");
boolean flagCreateDb=false;
PreparedStatement createDBPreStmt=null;
Connection commonConWithDb=null;
try{
createDBPreStmt=dbConnection.prepareStatement(createStmt);
createDBPreStmt.execute();
flagCreateDb=true;
logger.info("DB created successfully..");
}catch (SQLException e) {
dbConnection.close();
e.printStackTrace();
}
finally{
dbConnection.close();
}
if(flagCreateDb){
commonConWithDb=ConnectionManager.getConnection();
createTables(commonConWithDb,createTableStmt);
}
flag=flagCreateDb;
return flagCreateDb;
}
/**
* Creates the tables.
*
* @param dbConnection the db connection
* @param createStmt the create stmt
* @return true, if successful
* @throws SQLException the sQL exception
*/
private static boolean createTables(Connection dbConnection,String createStmt) throws SQLException{
logger.info("Creating initial table..");
boolean bCreatedTables = false;
PreparedStatement statement = null;
try {
DatabaseMetaData dbm = dbConnection.getMetaData();
String[] types = {"TABLE"};
ResultSet rs = dbm.getTables(null,null,"%",types);
String table ="";
while (rs.next())
{
table = rs.getString("TABLE_NAME");
}
if(!table.equalsIgnoreCase(tableName))
{
statement = dbConnection.prepareStatement(createStmt);
statement.execute();
logger.info("Table created successfully..");
bCreatedTables = true;
}
} catch (SQLException ex) {
dbConnection.close();
ex.printStackTrace();
}
if(bCreatedTables){
insertInitValues(dbConnection,insertInitUser);
}
flag=bCreatedTables;
return bCreatedTables;
}
/**
* Insert init values.
*
* @param dbConnection the db connection
* @param insertInitUsers the insert init users
* @return true, if successful
* @throws SQLException the sQL exception
*/
private static boolean insertInitValues(Connection dbConnection,String insertInitUsers) throws SQLException{
logger.info("Inserting initial values..");
boolean insertVal=false;
PreparedStatement insertStmt = null;
try{
insertStmt = dbConnection.prepareStatement(insertInitUsers);
insertStmt.setString(1,username);
insertStmt.setString(2,Utilities.getPassword(password));
insertStmt.setString(3,firstName);
insertStmt.setString(4,lastName);
insertStmt.setString(5,emailId);
insertStmt.setString(6,role);
insertStmt.executeUpdate();
insertVal = true;
logger.info("Values inserted successfully..");
}catch (SQLException e) {
dbConnection.close();
e.printStackTrace();
}
finally{
dbConnection.close();
}
flag=insertVal;
return insertVal;
}
}
Apache commons mail utility
Following Jar files are required:
1: commons-email-1.2
2: mail.jar (java mail api)
************************************************************************
package apacheCommonsMailUtility;
import java.net.URL;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
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;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;
/**
* The Class ApacheCommonsMailUtility.
*/
public class ApacheCommonsMailUtility {
/**
* Send simple text email via gmail.
*
* @return true, if successful
*/
public static boolean sendSimpleTextEmailViaGmail(){
boolean mailFlag=false;
try{
System.out.println("Sending email via gmail..");
/*The call to setHostName("mail.myserver.com") sets the address of the outgoing SMTP
server that will be used to send the message. If this is not set, the system property "mail.host" will be used.
*/
Email sendMail = new SimpleEmail();
sendMail.setHostName("smtp.gmail.com");
sendMail.setSmtpPort(587);// 465 or 587
sendMail.setAuthenticator(new DefaultAuthenticator("xxxxxxxx", "xxxxxxx")); //username & password
sendMail.setTLS(true);
sendMail.setFrom("strutsspringdemo@gmail.com");
sendMail.setSubject("TestMail");
sendMail.setMsg("This is a test mail ... :-)");
sendMail.addTo("abhinavmishra@gmail.com","Abhinav Mishra");
sendMail.addCc("abhinavmishra@gmail.com","Abhinav");
sendMail.addBcc("strutsspringdemo@gmail.com", "Demo");
sendMail.send();
mailFlag=true;
System.out.println("Email sent successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed..");
e.printStackTrace();
}
return mailFlag;
}
/**
* Send simple text email.
*
* @return true, if successful
*/
public static boolean sendSimpleTextEmail(){
boolean mailFlag=false;
try{
System.out.println("Sending email..");
/*The call to setHostName("mail.myserver.com") sets the address of the outgoing SMTP
server that will be used to send the message. If this is not set, the system property "mail.host" will be used.
*/
Email sendMail= new SimpleEmail();
sendMail.setHostName("10.000.0.00"); //smtp host
sendMail.setSmtpPort(25);
//NOT NEEDED FOR LOCAL ORG MAILS.
//sendMail.setAuthenticator(new DefaultAuthenticator("xxxx","xxxx"));
sendMail.setFrom("demo@demo.com");
sendMail.setSubject("TestMail..");
sendMail.setMsg("This is a test mail ... :-)");
sendMail.addTo("abhinavkumar_mishra@gmail.com","Abhinav Mishra");
sendMail.addCc("abhinavkumar_mishra@gmail.com","Abhinav");
sendMail.addBcc("akm@gmail.com", "Demo");
sendMail.send();
mailFlag=true;
System.out.println("Email sent successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed..");
e.printStackTrace();
}
return mailFlag;
}
/**
* To add attachments to an email, you will need to use the MultiPartEmail class.
* This class works just like SimpleEmail except that it adds several overloaded attach() methods to add attachments to the email.
* You can add an unlimited number of attachments either inline or attached. The attachments will be MIME encoded.
* The simpliest way to add the attachments is by using the EmailAttachment class to reference your attachments.
* In the following example, we will create an attachment for a picture. We will then attach the picture to the email and send it.
*
* @return true, if successful
*/
public static boolean sendEmailWithAttachment(){
boolean mailFlag=false;
try{
System.out.println("Sending email with attachment..");
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("test-Sequence-diagram.png"); //This image should be in root of project
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("test sequence diagram..");
attachment.setName("Sequence diagram.png");
// Create the email message
MultiPartEmail email = new MultiPartEmail();
email.setHostName("10.000.0.00"); //smtp host
email.setSmtpPort(25);
email.addTo("abhinavkumar_mishra@gmail.com", "Abhinav mishra");
email.addCc("abhinavkumar_mishra@gmail.com","Abhinav");
email.addBcc("teszt@gmail.com", "Demo");
email.setFrom("demmo@apache.org", "Demo");
email.setSubject("The picture");
email.setMsg("Here is the picture you wanted");
// add the attachment
email.attach(attachment);
// send the email
email.send();
mailFlag=true;
System.out.println("Email sent with attachment successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed with attachment..");
e.printStackTrace();
}
return mailFlag;
}
/**
* You can also use EmailAttachment to reference any valid URL for files that you do not have locally.
* When the message is sent, the file will be downloaded and attached to the message automatically.
*
* @return true, if successful
*/
public static boolean sendEmailWithAttachmentAsUrl(){
boolean mailFlag=false;
try{
System.out.println("Sending email with attachment as url..");
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setURL(new URL("http://www.apache.org/images/asf_logo_wide.gif"));
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Apache logo");
attachment.setName("Apache logo.gif");
// Create the email message
MultiPartEmail email = new MultiPartEmail();
email.setHostName("10.00.00.00"); //smtp host
email.setSmtpPort(25);
email.addTo("abhinavkumar_mishra@gmail.com", "Abhinav mishra");
email.addCc("abhinavkumar_mishra@gmail.com","Abhinav");
email.addBcc("test@gmail.com", "Demo");
email.setFrom("demmo@apache.org", "Demo");
email.setSubject("The picture");
email.setMsg("Here is the picture you wanted");
// add the attachment
email.attach(attachment);
// send the email
email.send();
mailFlag=true;
System.out.println("Email sent with attachment successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed with attachment as url..");
e.printStackTrace();
}
return mailFlag;
}
/**
* Sending HTML formatted email is accomplished by using the HtmlEmail class.
* This class works exactly like the MultiPartEmail class with additional methods to set the html content,
* alternative text content if the recipient does not support HTML email, and add inline images.
* First, notice that the call to embed() returns a String.
* This String is a randomly generated identifier that must be used to reference the image in the image tag.
* Next,there was no call to setMsg() in this example.
* The method is still available in HtmlEmail but it should not be used if you will be using inline images.
* Instead, the setHtmlMsg() and setTextMsg() methods were used.
* @return true, if successful
*/
public static boolean sendEmailHtmlFormat(){
boolean mailFlag=false;
try{
System.out.println("Sending email in html format..");
// Create the email message
HtmlEmail email = new HtmlEmail();
email.setHostName("10.000.0.00");
email.setSmtpPort(25);
email.addTo("abhinavkumar_mishra@gmail.com", "Abhinav mishra");
email.addCc("abhinavkumar_mishra@gmail.com","Abhinav");
email.addBcc("test@gmail.com", "Demo");
email.setFrom("demmo@apache.org", "Demo");
email.setSubject("The picture");
// embed the image and get the content id
URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
String cid = email.embed(url, "Apache logo");
// set the html message
email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");
// set the alternative message
email.setTextMsg("Your email client does not support HTML messages");
// send the email
email.send();
mailFlag=true;
System.out.println("Email sent in html format successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed in html format..");
e.printStackTrace();
}
return mailFlag;
}
/**
* Send emailwith embeded image using mail api.
*
* @return true, if successful
*/
public static boolean sendEmailwithEmbededImageUsingMailApi(){
boolean mailFlag=false;
try{
System.out.println("Sending email with embeded image..");
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "10.000.0.00");
props.setProperty("mail.port", "25");
props.setProperty("mail.user", "xxxx");
props.setProperty("mail.password", "xxxx");
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(true); //We can enable debugging as true..
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("HTML mail with images");
message.setFrom(new InternetAddress("abhinav@gmail.com"));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("abhinavkumar_mishra@gmail.com"));
message.addRecipient(Message.RecipientType.CC,
new InternetAddress("abhinavkumar_mishra@gmail.com"));
message.addRecipient(Message.RecipientType.BCC,
new InternetAddress("abhinavkumar_mishra@gmail.com"));
//
// This HTML mail have to 2 part, the BODY and the embedded image
//
MimeMultipart multipart = new MimeMultipart("related");
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
messageBodyPart.setContent(htmlText, "text/html");
// add it
multipart.addBodyPart(messageBodyPart);
// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource("CitationSearchModule-Sequence-diagram.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID","<image>");
// add it
multipart.addBodyPart(messageBodyPart);
// put everything together
message.setContent(multipart);
transport.connect();
transport.sendMessage(message,message.getAllRecipients());
transport.close();
mailFlag=true;
System.out.println("Email sent with embeded image successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed with embeded image..");
e.printStackTrace();
}
return mailFlag;
}
}
1: commons-email-1.2
2: mail.jar (java mail api)
************************************************************************
package apacheCommonsMailUtility;
import java.net.URL;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
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;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;
/**
* The Class ApacheCommonsMailUtility.
*/
public class ApacheCommonsMailUtility {
/**
* Send simple text email via gmail.
*
* @return true, if successful
*/
public static boolean sendSimpleTextEmailViaGmail(){
boolean mailFlag=false;
try{
System.out.println("Sending email via gmail..");
/*The call to setHostName("mail.myserver.com") sets the address of the outgoing SMTP
server that will be used to send the message. If this is not set, the system property "mail.host" will be used.
*/
Email sendMail = new SimpleEmail();
sendMail.setHostName("smtp.gmail.com");
sendMail.setSmtpPort(587);// 465 or 587
sendMail.setAuthenticator(new DefaultAuthenticator("xxxxxxxx", "xxxxxxx")); //username & password
sendMail.setTLS(true);
sendMail.setFrom("strutsspringdemo@gmail.com");
sendMail.setSubject("TestMail");
sendMail.setMsg("This is a test mail ... :-)");
sendMail.addTo("abhinavmishra@gmail.com","Abhinav Mishra");
sendMail.addCc("abhinavmishra@gmail.com","Abhinav");
sendMail.addBcc("strutsspringdemo@gmail.com", "Demo");
sendMail.send();
mailFlag=true;
System.out.println("Email sent successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed..");
e.printStackTrace();
}
return mailFlag;
}
/**
* Send simple text email.
*
* @return true, if successful
*/
public static boolean sendSimpleTextEmail(){
boolean mailFlag=false;
try{
System.out.println("Sending email..");
/*The call to setHostName("mail.myserver.com") sets the address of the outgoing SMTP
server that will be used to send the message. If this is not set, the system property "mail.host" will be used.
*/
Email sendMail= new SimpleEmail();
sendMail.setHostName("10.000.0.00"); //smtp host
sendMail.setSmtpPort(25);
//NOT NEEDED FOR LOCAL ORG MAILS.
//sendMail.setAuthenticator(new DefaultAuthenticator("xxxx","xxxx"));
sendMail.setFrom("demo@demo.com");
sendMail.setSubject("TestMail..");
sendMail.setMsg("This is a test mail ... :-)");
sendMail.addTo("abhinavkumar_mishra@gmail.com","Abhinav Mishra");
sendMail.addCc("abhinavkumar_mishra@gmail.com","Abhinav");
sendMail.addBcc("akm@gmail.com", "Demo");
sendMail.send();
mailFlag=true;
System.out.println("Email sent successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed..");
e.printStackTrace();
}
return mailFlag;
}
/**
* To add attachments to an email, you will need to use the MultiPartEmail class.
* This class works just like SimpleEmail except that it adds several overloaded attach() methods to add attachments to the email.
* You can add an unlimited number of attachments either inline or attached. The attachments will be MIME encoded.
* The simpliest way to add the attachments is by using the EmailAttachment class to reference your attachments.
* In the following example, we will create an attachment for a picture. We will then attach the picture to the email and send it.
*
* @return true, if successful
*/
public static boolean sendEmailWithAttachment(){
boolean mailFlag=false;
try{
System.out.println("Sending email with attachment..");
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("test-Sequence-diagram.png"); //This image should be in root of project
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("test sequence diagram..");
attachment.setName("Sequence diagram.png");
// Create the email message
MultiPartEmail email = new MultiPartEmail();
email.setHostName("10.000.0.00"); //smtp host
email.setSmtpPort(25);
email.addTo("abhinavkumar_mishra@gmail.com", "Abhinav mishra");
email.addCc("abhinavkumar_mishra@gmail.com","Abhinav");
email.addBcc("teszt@gmail.com", "Demo");
email.setFrom("demmo@apache.org", "Demo");
email.setSubject("The picture");
email.setMsg("Here is the picture you wanted");
// add the attachment
email.attach(attachment);
// send the email
email.send();
mailFlag=true;
System.out.println("Email sent with attachment successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed with attachment..");
e.printStackTrace();
}
return mailFlag;
}
/**
* You can also use EmailAttachment to reference any valid URL for files that you do not have locally.
* When the message is sent, the file will be downloaded and attached to the message automatically.
*
* @return true, if successful
*/
public static boolean sendEmailWithAttachmentAsUrl(){
boolean mailFlag=false;
try{
System.out.println("Sending email with attachment as url..");
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setURL(new URL("http://www.apache.org/images/asf_logo_wide.gif"));
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Apache logo");
attachment.setName("Apache logo.gif");
// Create the email message
MultiPartEmail email = new MultiPartEmail();
email.setHostName("10.00.00.00"); //smtp host
email.setSmtpPort(25);
email.addTo("abhinavkumar_mishra@gmail.com", "Abhinav mishra");
email.addCc("abhinavkumar_mishra@gmail.com","Abhinav");
email.addBcc("test@gmail.com", "Demo");
email.setFrom("demmo@apache.org", "Demo");
email.setSubject("The picture");
email.setMsg("Here is the picture you wanted");
// add the attachment
email.attach(attachment);
// send the email
email.send();
mailFlag=true;
System.out.println("Email sent with attachment successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed with attachment as url..");
e.printStackTrace();
}
return mailFlag;
}
/**
* Sending HTML formatted email is accomplished by using the HtmlEmail class.
* This class works exactly like the MultiPartEmail class with additional methods to set the html content,
* alternative text content if the recipient does not support HTML email, and add inline images.
* First, notice that the call to embed() returns a String.
* This String is a randomly generated identifier that must be used to reference the image in the image tag.
* Next,there was no call to setMsg() in this example.
* The method is still available in HtmlEmail but it should not be used if you will be using inline images.
* Instead, the setHtmlMsg() and setTextMsg() methods were used.
* @return true, if successful
*/
public static boolean sendEmailHtmlFormat(){
boolean mailFlag=false;
try{
System.out.println("Sending email in html format..");
// Create the email message
HtmlEmail email = new HtmlEmail();
email.setHostName("10.000.0.00");
email.setSmtpPort(25);
email.addTo("abhinavkumar_mishra@gmail.com", "Abhinav mishra");
email.addCc("abhinavkumar_mishra@gmail.com","Abhinav");
email.addBcc("test@gmail.com", "Demo");
email.setFrom("demmo@apache.org", "Demo");
email.setSubject("The picture");
// embed the image and get the content id
URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
String cid = email.embed(url, "Apache logo");
// set the html message
email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");
// set the alternative message
email.setTextMsg("Your email client does not support HTML messages");
// send the email
email.send();
mailFlag=true;
System.out.println("Email sent in html format successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed in html format..");
e.printStackTrace();
}
return mailFlag;
}
/**
* Send emailwith embeded image using mail api.
*
* @return true, if successful
*/
public static boolean sendEmailwithEmbededImageUsingMailApi(){
boolean mailFlag=false;
try{
System.out.println("Sending email with embeded image..");
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "10.000.0.00");
props.setProperty("mail.port", "25");
props.setProperty("mail.user", "xxxx");
props.setProperty("mail.password", "xxxx");
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(true); //We can enable debugging as true..
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("HTML mail with images");
message.setFrom(new InternetAddress("abhinav@gmail.com"));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("abhinavkumar_mishra@gmail.com"));
message.addRecipient(Message.RecipientType.CC,
new InternetAddress("abhinavkumar_mishra@gmail.com"));
message.addRecipient(Message.RecipientType.BCC,
new InternetAddress("abhinavkumar_mishra@gmail.com"));
//
// This HTML mail have to 2 part, the BODY and the embedded image
//
MimeMultipart multipart = new MimeMultipart("related");
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
messageBodyPart.setContent(htmlText, "text/html");
// add it
multipart.addBodyPart(messageBodyPart);
// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource("CitationSearchModule-Sequence-diagram.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID","<image>");
// add it
multipart.addBodyPart(messageBodyPart);
// put everything together
message.setContent(multipart);
transport.connect();
transport.sendMessage(message,message.getAllRecipients());
transport.close();
mailFlag=true;
System.out.println("Email sent with embeded image successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed with embeded image..");
e.printStackTrace();
}
return mailFlag;
}
}
Sorting a Map using map value
For sorting a java Map on values i have used Comparator. Here is the demonstration.
---------------------------------------------------------------------------------------------------------------
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class SortMapOnValues{
public static void main(String[] args){
Map<Developer,Object> map=new HashMap<Developer,Object>();
map.put(new Developer("abhi", 21, "Allahabad"), 101);
map.put(new Developer("ashu", 24, "Kanpur"), 104);
map.put(new Developer("mayank", 23, "Noida"), 102);
map.put(new Developer("naveen", 27, "Lucknow"), 103);
System.out.println("Unsorted map: "+map);
ValComparator valComp=new ValComparator(map);
Map<Developer,Object> sortedMap=new TreeMap<Developer,Object>(valComp);
sortedMap.putAll(map);
System.out.println("Sorted map on values: "+sortedMap);
}
}
class ValComparator implements Comparator<Object>{
Map<Developer,Object> m;
public ValComparator() {
super();
}
public ValComparator(Map<Developer,Object> map) {
super();
this.m=map;
}
public int compare(Object o1, Object o2) {
int sort;
if(m.get(o1).hashCode()>m.get(o2).hashCode()){
sort=1;
}else if(m.get(o1).hashCode()<m.get(o2).hashCode()){
sort=-1;
}else{
sort=0;
}
return sort;
}
}
class Developer{
String name;
int age;
String address;
public String toString(){
return "("+name+";"+age+";"+address+")";
}
public Developer(){
super();
}
public Developer(String name, int age, String address){
super();
this.name = name;
this.age = age;
this.address = address;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Developer other = (Developer) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
Output:>
Unsorted map: {(naveen;27;Lucknow)=103, (mayank;23;Noida)=102, (ashu;24;Kanpur)=104, (abhi;21;Allahabad)=101}
Sorted map on values: {(abhi;21;Allahabad)=101, (mayank;23;Noida)=102, (naveen;27;Lucknow)=103, (ashu;24;Kanpur)=104}
Sorting a Map based on values
/**
* The Class HashMapShortOnValue.
*/
class MapShortOnValue{
/**
* Gets the sorted result for hash map based on value.
*
* @return the sorted result for hash map based on value
*/
public static void getSortedResultForHashMapBasedOnValue(){
Map<PersonObject, Object> map= new HashMap<PersonObject, Object>();
map.put(new PersonObject("Abhi", 25), "Abhinav");
map.put(new PersonObject("Bishu", 21), "Vivek");
map.put(new PersonObject("Raj", 26), "Rahul");
map.put(new PersonObject("Kunnu", 28), "Kunal");
System.out.println("Unsorted hashMap: "+map);
Map<PersonObject, Object> sortedMapOnVal=new TreeMap<PersonObject, Object>(new HashMapValueComparator(map));
sortedMapOnVal.putAll(map);
System.out.println("Sorted map based on values: "+sortedMapOnVal);
}
}
/**
* The Class HashMapValueComparator.
*/
class HashMapValueComparator implements Comparator<Object>{
/** The map. */
Map<PersonObject, Object> map;
/**
* Instantiates a new hash map value comparator.
*/
HashMapValueComparator(){
super();
}
/**
* Instantiates a new hash map value comparator.
* @param map the map
*/
HashMapValueComparator(Map<PersonObject, Object> map){
super();
this.map=map;
}
/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(Object o1, Object o2){
int retType;
Object v1=map.get(o1);
Object v2=map.get(o2);
if(v1 instanceof String && v2 instanceof String){
if(v1.toString().toLowerCase().hashCode()>v2.toString().toLowerCase().hashCode()){
retType=1;
}else if(v1.toString().toLowerCase().hashCode()<v2.toString().toLowerCase().hashCode()){
retType=-1;
}
else{
retType=0;
}
}else{
if(v1.hashCode()>v2.hashCode()){
retType=1;
}else if(v1.hashCode()<v2.hashCode()){
retType=-1;
}
else{
retType=0;
}
}
return retType;
}
}
/**
* The Class Person.
*/
class PersonObject{
/** The age. */
int age;
/** The name. */
String name;
/**
* Instantiates a new person.
*/
PersonObject(){
super();
}
/**
* Instantiates a new person.
* @param name the name
* @param age the age
*/
PersonObject(String name,int age){
super();
this.name=name;
this.age=age;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString(){
return name+" | "+age;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object o){
PersonObject p=(PersonObject)o;
return this.age==p.age && this.name.equals(p.name);
}
}
Sorting a Map using key objects
package collectionFramework;
import java.util.Comparator;
import java.util.HashMap;
import java.util.TreeMap;
/**
* The Class HashMapAddSearchSort.
*/
public class HashMapAddSearchSort
{
/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args)
{
HashMapmap= new HashMap ();
map.put(new Employee("abhinav",21,24000),"INNODATA");
map.put(new Employee("abhishek",25,23000),"AIRTEL");
map.put(new Employee("ashutosh",22,22000),"VODAFONE");
map.put(new Employee("rinku",24,25000),"HCL");
map.put(new Employee("rinku",24,25000),"HCL");
System.out.println("Search for value on basis of key: >"+map.containsKey(new Employee("ashutosh",22,22000)));
System.out.println("Search for value 'INNODATA' :> "+map.containsValue("INNODATA"));
System.out.println("UNSORTED: "+map);
/*TreeMapsortedMap = new TreeMap ();
sortedMap.putAll(map);
System.out.println("SORTED USING AGE-BASED-COMPARABLE: "+sortedMap);*/
TreeMapsortedMapNameComparator = new TreeMap (new NameComparator());
sortedMapNameComparator.putAll(map);
System.out.println("SORTED USING NAME-COMPARATOR: "+sortedMapNameComparator);
TreeMapsortedMapAgeComparator = new TreeMap (new AgeComparator());
sortedMapAgeComparator.putAll(map);
System.out.println("SORTED USING AGE-COMPARATOR: "+sortedMapAgeComparator);
TreeMapsortedMapSalaryComparator = new TreeMap (new SalaryComparator());
sortedMapSalaryComparator.putAll(map);
System.out.println("SORTED USING SALARY-COMPARATOR: "+sortedMapSalaryComparator);
}
}
/**
* The Class AgeComparator.
*/
class AgeComparator implements Comparator
{
public int compare(Employee o1,Employee o2){
if(o1.age>o2.age){
return 1;
}else if(o1.age
{
public int compare(Employee o1,Employee o2){
return o1.name.compareTo(o2.name);
}
}
/**
* The Class SalaryComparator.
*/
class SalaryComparator implements Comparator
{
public int compare(Employee o1,Employee o2){
if(o1.salary>o2.salary){
return 1;
}else if(o1.salary
{
/** The name. */
String name;
/** The age. */
int age;
/** The salary. */
int salary;
/**
* Instantiates a new employee.
*/
public Employee() {
super();
}
/**
* Instantiates a new employee.
*
* @param name the name
* @param age the age
* @param salary the salary
*/
public Employee(String name, int age, int salary)
{
super();
this.name = name;
this.age = age;
this.salary = salary;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString()
{
return "\nEmployeeDetails:>> ( "+name+" :: "+age+" :: "+salary+" )";
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode()
{
int result = 1;
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object o)
{
Employee e=(Employee)o;
if(this.name.hashCode() ==e.name.hashCode() && this.age==e.age && this.salary==e.salary)
{
return true;
}
return false;
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Employee o)
{
//return this.name.compareToIgnoreCase(o.name);
/*if(this.salary>o.salary){
return 1;
}else if(this.salaryo.age){
return 1;
}else if(this.age
Serialization of a singleton Object
package designPattern;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* The Class SingletonObjectSerializing.
* If the Singleton class implements the java.io.Serializable interface, when a singleton is serialized and then deserialized more
* than once, there will be multiple instances of Singleton created. In order to avoid this the readResolve method should be
* implemented.
*/
public class SingletonObjectSerializing {
/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
System.out.println("Singleton object: "+SingletonObject.getInstance());
try {
ObjectOutputStream objOut=new ObjectOutputStream(new FileOutputStream("SingletonObject.txt"));
objOut.writeObject(SingletonObject.getInstance());
System.out.println("Singleton object serialized: "+SingletonObject.getInstance());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
ObjectInputStream objIn=new ObjectInputStream(new FileInputStream("SingletonObject.txt"));
SingletonObject sinObj=null;
try {
sinObj = (SingletonObject) objIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Singleton object deserialized: "+sinObj);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* The Class SingletonObject.
*/
class SingletonObject implements Serializable{
private static final long serialVersionUID = 1L;
/**
* Instantiates a new singleton object.
*/
private SingletonObject(){
super();
System.out.println("Instantiated..");
}
/** The instance. */
private static volatile SingletonObject instance=new SingletonObject();
/**
* Gets the single instance of SingletonObject.
*
* @return single instance of SingletonObject
*/
public static SingletonObject getInstance(){
return instance;
}
/**
* Read resolve.
* This method is called immediately after an object of this class is deserialized.
* This method returns the singleton instance.
* @return the object
*/
protected Object readResolve() {
return getInstance();
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* The Class SingletonObjectSerializing.
* If the Singleton class implements the java.io.Serializable interface, when a singleton is serialized and then deserialized more
* than once, there will be multiple instances of Singleton created. In order to avoid this the readResolve method should be
* implemented.
*/
public class SingletonObjectSerializing {
/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
System.out.println("Singleton object: "+SingletonObject.getInstance());
try {
ObjectOutputStream objOut=new ObjectOutputStream(new FileOutputStream("SingletonObject.txt"));
objOut.writeObject(SingletonObject.getInstance());
System.out.println("Singleton object serialized: "+SingletonObject.getInstance());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
ObjectInputStream objIn=new ObjectInputStream(new FileInputStream("SingletonObject.txt"));
SingletonObject sinObj=null;
try {
sinObj = (SingletonObject) objIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Singleton object deserialized: "+sinObj);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* The Class SingletonObject.
*/
class SingletonObject implements Serializable{
private static final long serialVersionUID = 1L;
/**
* Instantiates a new singleton object.
*/
private SingletonObject(){
super();
System.out.println("Instantiated..");
}
/** The instance. */
private static volatile SingletonObject instance=new SingletonObject();
/**
* Gets the single instance of SingletonObject.
*
* @return single instance of SingletonObject
*/
public static SingletonObject getInstance(){
return instance;
}
/**
* Read resolve.
* This method is called immediately after an object of this class is deserialized.
* This method returns the singleton instance.
* @return the object
*/
protected Object readResolve() {
return getInstance();
}
}
SingletonDesign Pattern
package designPattern;
import java.io.Serializable;
import java.util.Scanner;
/**
* The Class SingletonPatternMultithreaded.
*/
public class SingletonPatternMultithreaded {
/**
* The main method.
* @param args the arguments
*/
public static void main(String[] args) {
int key=0;
Scanner sc=new Scanner(System.in);
System.out.println("Get singleton object..");
System.out.println("Enter a choice for singleton object-->");
System.out.println("Choice 1:NonStatic");
System.out.println("Choice 2:Static");
System.out.println("Choice 0:Exit");
key=sc.nextInt();
switch (key) {
case 1:
new MyThread1("non-static");
new MyThread2("non-static");
new MyThread1("non-static");
new MyThread2("non-static");
System.out.println("NON-STATIC SINGLETON OBJECT ACCESSED BY main: "+MultithreadedSingletonObject.getInstance());
break;
case 2:
new MyThread1 ("static");
new MyThread2 ("static");
new MyThread1("static");
new MyThread2("static");
System.out.println("STATIC SINGLETON OBJECT ACCESSED BY main: "+MultithreadedSingletonObjectBestSolution.getInstance());
break;
default:
System.exit(0);
break;
}
}
}
/**
* The Class MultithreadedSingletonObject.
*/
class MultithreadedSingletonObject implements Serializable{
private static final long serialVersionUID = 1L;
/** The instance. */
private static MultithreadedSingletonObject instance;
/**
* Gets the single instance of MultithreadedSingletonObject.
*
* @return single instance of MultithreadedSingletonObject
*/
public static MultithreadedSingletonObject getInstance(){
if (instance == null){
synchronized(MultithreadedSingletonObject.class){
MultithreadedSingletonObject inst = instance;
if (inst == null){
synchronized(MultithreadedSingletonObject.class) {
instance = new MultithreadedSingletonObject();
}
}
}
}
return instance;
}
/**
* Read resolve.
* This method is called immediately after an object of this class is deserialized.
* This method returns the singleton instance.
* @return the object
*/
protected Object readResolve() {
return getInstance();
}
private MultithreadedSingletonObject (){}
}
/**
* The Class MultithreadedSingletonObjectBestSolution.
* Most preffered singleton pattern
*/
class MultithreadedSingletonObjectBestSolution implements Serializable{
private static final long serialVersionUID = 1L;
/** The instance. */
private static volatile MultithreadedSingletonObjectBestSolution instance=new MultithreadedSingletonObjectBestSolution();
/**
* Gets the single instance of MultithreadedSingletonObject.
*
* @return single instance of MultithreadedSingletonObject
*/
public static MultithreadedSingletonObjectBestSolution getInstance(){
return instance;
}
/**
* Read resolve.
* This method is called immediately after an object of this class is deserialized.
* This method returns the singleton instance.
* @return the object
*/
protected Object readResolve() {
return getInstance();
}
private MultithreadedSingletonObjectBestSolution (){}
}
/**
* The Class MyThread1.
*/
class MyThread1 extends Thread{
/** The mode. */
String mode;
/**
* Instantiates a new my thread1.
*
* @param mode the mode
*/
MyThread1(String mode){
super();
this.mode=mode;
setName("MyThread1");
start();
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public void run(){
if(mode.equalsIgnoreCase("non-static")){
System.out.println("NON-STATIC SINGLETON OBJECT ACCESSED BY "+getName()+": "+MultithreadedSingletonObject.getInstance());
}else{
System.out.println("STATIC SINGLETON OBJECT ACCESSED BY "+getName()+": "+MultithreadedSingletonObjectBestSolution.getInstance());
}
}
}
/**
* The Class MyThread2.
*/
class MyThread2 extends Thread{
/** The mode. */
String mode;
/**
* Instantiates a new my thread2.
*
* @param mode the mode
*/
MyThread2(String mode){
super();
this.mode=mode;
setName("MyThread2");
start();
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public void run(){
if(mode.equalsIgnoreCase("non-static")){
System.out.println("NON-STATIC SINGLETON OBJECT ACCESSED BY "+getName()+": "+MultithreadedSingletonObject.getInstance());
}else{
System.out.println("STATIC SINGLETON OBJECT ACCESSED BY "+getName()+": "+MultithreadedSingletonObjectBestSolution.getInstance());
}
}
}
import java.io.Serializable;
import java.util.Scanner;
/**
* The Class SingletonPatternMultithreaded.
*/
public class SingletonPatternMultithreaded {
/**
* The main method.
* @param args the arguments
*/
public static void main(String[] args) {
int key=0;
Scanner sc=new Scanner(System.in);
System.out.println("Get singleton object..");
System.out.println("Enter a choice for singleton object-->");
System.out.println("Choice 1:NonStatic");
System.out.println("Choice 2:Static");
System.out.println("Choice 0:Exit");
key=sc.nextInt();
switch (key) {
case 1:
new MyThread1("non-static");
new MyThread2("non-static");
new MyThread1("non-static");
new MyThread2("non-static");
System.out.println("NON-STATIC SINGLETON OBJECT ACCESSED BY main: "+MultithreadedSingletonObject.getInstance());
break;
case 2:
new MyThread1 ("static");
new MyThread2 ("static");
new MyThread1("static");
new MyThread2("static");
System.out.println("STATIC SINGLETON OBJECT ACCESSED BY main: "+MultithreadedSingletonObjectBestSolution.getInstance());
break;
default:
System.exit(0);
break;
}
}
}
/**
* The Class MultithreadedSingletonObject.
*/
class MultithreadedSingletonObject implements Serializable{
private static final long serialVersionUID = 1L;
/** The instance. */
private static MultithreadedSingletonObject instance;
/**
* Gets the single instance of MultithreadedSingletonObject.
*
* @return single instance of MultithreadedSingletonObject
*/
public static MultithreadedSingletonObject getInstance(){
if (instance == null){
synchronized(MultithreadedSingletonObject.class){
MultithreadedSingletonObject inst = instance;
if (inst == null){
synchronized(MultithreadedSingletonObject.class) {
instance = new MultithreadedSingletonObject();
}
}
}
}
return instance;
}
/**
* Read resolve.
* This method is called immediately after an object of this class is deserialized.
* This method returns the singleton instance.
* @return the object
*/
protected Object readResolve() {
return getInstance();
}
private MultithreadedSingletonObject (){}
}
/**
* The Class MultithreadedSingletonObjectBestSolution.
* Most preffered singleton pattern
*/
class MultithreadedSingletonObjectBestSolution implements Serializable{
private static final long serialVersionUID = 1L;
/** The instance. */
private static volatile MultithreadedSingletonObjectBestSolution instance=new MultithreadedSingletonObjectBestSolution();
/**
* Gets the single instance of MultithreadedSingletonObject.
*
* @return single instance of MultithreadedSingletonObject
*/
public static MultithreadedSingletonObjectBestSolution getInstance(){
return instance;
}
/**
* Read resolve.
* This method is called immediately after an object of this class is deserialized.
* This method returns the singleton instance.
* @return the object
*/
protected Object readResolve() {
return getInstance();
}
private MultithreadedSingletonObjectBestSolution (){}
}
/**
* The Class MyThread1.
*/
class MyThread1 extends Thread{
/** The mode. */
String mode;
/**
* Instantiates a new my thread1.
*
* @param mode the mode
*/
MyThread1(String mode){
super();
this.mode=mode;
setName("MyThread1");
start();
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public void run(){
if(mode.equalsIgnoreCase("non-static")){
System.out.println("NON-STATIC SINGLETON OBJECT ACCESSED BY "+getName()+": "+MultithreadedSingletonObject.getInstance());
}else{
System.out.println("STATIC SINGLETON OBJECT ACCESSED BY "+getName()+": "+MultithreadedSingletonObjectBestSolution.getInstance());
}
}
}
/**
* The Class MyThread2.
*/
class MyThread2 extends Thread{
/** The mode. */
String mode;
/**
* Instantiates a new my thread2.
*
* @param mode the mode
*/
MyThread2(String mode){
super();
this.mode=mode;
setName("MyThread2");
start();
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public void run(){
if(mode.equalsIgnoreCase("non-static")){
System.out.println("NON-STATIC SINGLETON OBJECT ACCESSED BY "+getName()+": "+MultithreadedSingletonObject.getInstance());
}else{
System.out.println("STATIC SINGLETON OBJECT ACCESSED BY "+getName()+": "+MultithreadedSingletonObjectBestSolution.getInstance());
}
}
}
Subscribe to:
Comments (Atom)