Thursday, October 31, 2013

How to send batch email using Gmail in Java

import java.util.Properties;

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

public class BatchEmailer {

      public static void main(String[] args) {
            Properties props = System.getProperties();
        props.put("mail.smtp.user", "abc@gmail.com");
        props.put("mail.smtp.password", "12345678");
            props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
        props.put("mail.stmp.sendpartial", "true");
       
        Session session = Session.getDefaultInstance(props);
            Message message = new MimeMessage(session);
           
            try {
                  message.setFrom(new InternetAddress("abc@gmail.com"));

                  String[] toAddress = new String[] { "aaa@aaa.com", "bbb@bbb.com", "ccc@ccc.com" };
                  for (int i = 0; i < toAddress.length; i++) {
                        InternetAddress address = new InternetAddress(toAddress[i]);
                        message.addRecipient(Message.RecipientType.TO, address);
                  }

                  message.setSubject("Batch Email Testing");
                  message.setText("Batch Email Testing 1 2 3");

                  Transport.send(message);
            } catch (MessagingException e) {
                  e.printStackTrace();
            }
      }
}

Tuesday, July 2, 2013

Generate Large Excel Report by Using Apache POI Performance Tuning

If you are using Apache POI to generate large excel file, please take note the sheet.autoSizeColumn((short) p); line because this will impact the performance.


import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class CSVToExcelConverter {

       public static void main(String args[]) throws IOException {
              ArrayList arList = null;
              ArrayList al = null;
              String fName = "test.csv";
              String thisLine;
              int count = 0;
              FileInputStream fis = new FileInputStream(fName);
              DataInputStream myInput = new DataInputStream(fis);
              int i = 0;
              arList = new ArrayList();
              while ((thisLine = myInput.readLine()) != null) {
                     al = new ArrayList();
                     String strar[] = thisLine.split(",");
                     for (int j = 0; j < strar.length; j++) {
                           al.add(strar[j]);
                     }
                     arList.add(al);
                     i++;
              }

              try {
                     HSSFWorkbook hwb = new HSSFWorkbook();
                     HSSFSheet sheet = hwb.createSheet("new sheet");
                     for (int k = 0; k < arList.size(); k++) {
                           ArrayList ardata = (ArrayList) arList.get(k);
                           HSSFRow row = sheet.createRow((short) 0 + k);
                           for (int p = 0; p < ardata.size(); p++) {
                                  HSSFCell cell = row.createCell((short) p);
                                  sheet.autoSizeColumn((short) p); // this will slow down the performance
                                  String data = ardata.get(p).toString();
                                  if (data.startsWith("=")) {
                                         cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                                         data = data.replaceAll("\"", "");
                                         data = data.replaceAll("=", "");
                                         cell.setCellValue(data);
                                  } else if (data.startsWith("\"")) {
                                         data = data.replaceAll("\"", "");
                                         cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                                         cell.setCellValue(data);
                                  } else {
                                         data = data.replaceAll("\"", "");
                                         cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                                         cell.setCellValue(data);
                                  }
                                  // */
                                  // cell.setCellValue(ardata.get(p).toString());
                           }
                           System.out.println();
                     }
                     FileOutputStream fileOut = new FileOutputStream("test.xls");
                     hwb.write(fileOut);
                     fileOut.close();
                     System.out.println("Your excel file has been generated");
              } catch (Exception ex) {
                     ex.printStackTrace();
              } // main method ends
       }
}



Hope this can save you time.

Monday, August 20, 2012

Why Bedok instead of Punggol?

Recently 1 of my friend ask me, why you want to buy a HDB Flat in Bedok instead of Punggol while Bedok Flat are more then 30 years old and Punggol Flat are less then 10 years old. The answer is very simple. I not buying the flat only, I buy with the environment.

Most of the people in Singapore are busy with their work, study and family everyday. People have not enough time for their family and friends. So I would choose a location that convenient for my daily activity to save more time.

When I choose a location to stay, I will consider the following:-

1)      Location
How far from my house to office (Raffles Place)?
How far from my house to public transport like MRT Station?
How far from my house to major express way like ECP or PIE?

2)      Food
Is there any food court or kopi tiam nearby?
Is there any wet market?
Is there any supermarket?

3)      School
Is there any child care?
Is there any primary school?
Is there any secondary school?

These 3 things I am doing everyday and will be doing for the next 10 years as well. If you find a place that make your life easy, you won’t keep on searching for house and moving around.

Hopefully this post can help someone to choose their best location to settle down.


Tuesday, March 6, 2012

How to set the PDF file show on the browser or download from the browser

Do you notice some website download the PDF file from the browser and some show the on the browser?

You can set it in your Java Servlet. Checkout the following.

This will open the PDF file on the browser.

response.setContentType("application/pdf");

response.setHeader("Content-Disposition", "inline; filename=abc.pdf);

This will download the PDF file from the browser.

response.setContentType("application/x-download");

response.setHeader("Content-Disposition", "attachment; filename=abc.pdf);

Friday, February 24, 2012

How to add your sitemap file located in Amazon S3 into Google Webmaster tools

If you hosted your rails website in Heroku, you are most properly using https://github.com/kjvarga/sitemap_generator gem to dynamically generate your sitemap file.

I won’t go into the details of how to use sitemap_generator, there are many website guide you for this, just google it.

Once you got your sitemap generated and uploaded to Amazon S3 successfully, you might want to track your sitemap in Google Webmaster Tools as well.

First, add your Amazon S3 site into Google Webmaster Tools. For example, http://s3.amazonaws.com/mybucket/sitemaps


Second, verify your Amazon S3 site by copy the googleXXXXX.html file into your bucket and give the permission accordingly.


Third, go into your Amazon S3 site in Google Webmaster Tools. Navigate to Site Configuration > Sitemaps, add the sitemap located in Amazon S3 for your Rails website.


Done! That All.

Google can accept “Cross-site submissions” for your sitemap.

http://googlewebmastercentral.blogspot.com/2007/10/dealing-with-sitemap-cross-submissions.html

Wednesday, February 22, 2012

How to merge multiple reports into a single report in JasperReports


import java.io.FileOutputStream;

import java.util.ArrayList;

import java.util.HashMap;

import net.sf.jasperreports.engine.JREmptyDataSource;

import net.sf.jasperreports.engine.JRExporter;

import net.sf.jasperreports.engine.JRParameter;

import net.sf.jasperreports.engine.JRPrintPage;

import net.sf.jasperreports.engine.JasperFillManager;

import net.sf.jasperreports.engine.JasperPrint;

import net.sf.jasperreports.engine.JasperReport;

import net.sf.jasperreports.engine.export.JRPdfExporter;

import net.sf.jasperreports.engine.export.JRPdfExporterParameter;

import net.sf.jasperreports.engine.fill.JRFileVirtualizer;

import net.sf.jasperreports.engine.util.JRLoader;

public class JasperReportMerge {

ArrayList reportsList = new ArrayList();

HashMap params = new HashMap();

JasperPrint jrPrint = new JasperPrint();

public void buildReport() throws Exception {

String templateFile = "C://Testing//MergeReportTemplate.jasper";

JasperReport jrReport = (JasperReport) JRLoader.loadObject(templateFile);

JRFileVirtualizer virtualizer = null;

JasperPrint jp = null;

for(int i=0; i<5; i++) {

virtualizer = new JRFileVirtualizer(2, "C://tmp");

virtualizer.setReadOnly(true);

params.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);

// Create dummy data for the each report

params.put("name", "Hello " + i);

params.put("ic", "IC " + i);

params.put("address", i + " Address");

jp = JasperFillManager.fillReport(jrReport, params, new JREmptyDataSource());

reportsList.add(jp); // adding the report into list

// Clean the virtualizer.

// If you didnt clean it, you might encounter error such as

// "The virtualizer is used by more contexts than its in-memory cache size XXX"

virtualizer.cleanup();

}

if (reportsList != null && reportsList.size() > 0) {

jrPrint = mergeReport(); // merge the report

} else {

jrPrint = JasperFillManager.fillReport(jrReport, params, new JREmptyDataSource());

}

exportReport();

}

protected JasperPrint mergeReport() throws Exception {

JasperPrint jrPrint = new JasperPrint();

JasperPrint jp = null;

jp = (JasperPrint) reportsList.get(0);

// set the report layout

jrPrint.setOrientation(jp.getOrientation());

jrPrint.setLocaleCode(jp.getLocaleCode());

jrPrint.setPageHeight(jp.getPageHeight());

jrPrint.setPageWidth(jp.getPageWidth());

jrPrint.setTimeZoneId(jp.getTimeZoneId());

jrPrint.setName(jp.getName());

// get each report and merge it 1 by 1

for(int i=0; i<reportsList.size(); i++) {

jp = (JasperPrint) reportsList.get(i);

ArrayList list = (ArrayList) jp.getPages();

// Merging the reports into 1 single report

for(int j=0; j

jrPrint.addPage((JRPrintPage) list.get(j));

}

}

return jrPrint;

}

protected void exportReport() throws Exception {

FileOutputStream fileOut = new FileOutputStream("C://Testing//MergeReportTemplate.pdf");

JRExporter exporter = new JRPdfExporter();

exporter.setParameter(JRPdfExporterParameter.FORCE_LINEBREAK_POLICY, Boolean.TRUE);

exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM, fileOut);

exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT, jrPrint);

System.out.println("Exporting...");

exporter.exportReport();

fileOut.flush();

fileOut.close();

}

public static void main(String[] args) throws Exception {

JasperReportMerge jem = new JasperReportMerge();

jem.buildReport();

System.out.println("Done");

}

}