Friday, October 10, 2014

Using Java Send Email Using Smtp Server(Html, Attachment, Embedded Image)

First download java mail api jar from: https://java.net/projects/javamail/pages/Home or here.
And add this to your project classpath.


package com.pritom;

import java.util.*;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;

/**
 * Created by pritom on 30/11/2016.
 */
public class SendEmailUsingSmtp {
    private static final String toAddress = "pritom@xxxxx.com";

    public static void main(String[] args) {
        google();
        //office();
        //bleep();
    }

    private static void google() {
        String host = "smtp.gmail.com";
        String port = "587";
        String userName = "xxxxx@gmail.com";
        String password = "xxxxx";
        send(host, port, userName, password);
    }

    private static void office() {
        String host = "smtp.office365.com";
        String port = "587";
        String userName = "xxxxx@office.com";
        String password = "xxxxx";
        send(host, port, userName, password);
    }

    private static void bleep() {
        String host = "bleep.xxxxx.com";
        String port = "587";
        String userName = "pritom@xxxxx.com";
        String password = "xxxxx";
        send(host, port, userName, password);
    }

    private static void send(String host, String port, String userName, String password) {
        String attachments = "attachments/Attachment_1.gif;"
                + "attachments/Attachment_2.pdf;"
                + "attachments/Attachment_3.txt;"
                + "attachments/Attachment_4.docx;"
                + "attachments/Attachment_5.jpg";


        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("https.protocols", "TLSv1,SSLv3,SSLv2Hello");
        props.put("com.sun.net.ssl.enableECC", "false");
        props.put("jsse.enableSNIExtension", "false");

        String subject = "Java send mail example - TLS Authentication";

        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        });

        MimeMessage message = new MimeMessage(mailSession) {
            protected void updateMessageID() throws MessagingException {
                if (getHeader("Message-ID") == null)
                    super.updateMessageID();
            }
        };

        try {

            /* If failed to send email then fail report delivered to following email address */
            /* But remember not all smtp server allow use different email address */
            //props.put("mail.smtp.from", "pritomkucse@gmail.com");

            message.setFrom(new InternetAddress(userName, "Pritom Kumar", "UTF-8"));
            message.setReplyTo(InternetAddress.parse(userName, false));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toAddress, "UTF-8"));

            message.setSentDate(new Date());
            message.setSubject(subject, "UTF-8");
            Multipart multipart = new MimeMultipart();

            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent("This is <b>message</b> body, pls see "
                    + "<i style='color: blue; font-size: 40px;'>attachments</i>", "text/html");
            multipart.addBodyPart(messageBodyPart);

            for( int i = 0; i < attachments.split(";").length; i++) {
                String fileName = attachments.split(";")[i];
                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(fileName);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(source.getName());
                messageBodyPart.setHeader("Content-ID", "<CONTENT_" + i + ">");
                multipart.addBodyPart(messageBodyPart);
            }

            /* Some custom headers added to email */
            message.addHeader("header-1", "header-1-value");
            message.addHeader("header-2", "header-2-value");

            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent("<h1>Attachments are added.</h1>Attached image as embedded:<br/>"
                    + "<img style='width: 50px;' src='cid:CONTENT_4'/>", "text/html");
            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart );
            println("Start sending email...");
            Transport.send(message);
            println("Mail sent with message ID=" + message.getMessageID());
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static void println(Object o) {
        System.out.println(o);
    }
}

Console output would be like following

Start sending email...
Mail sent with message ID=<2059904228.1.1477967571904.JavaMail.pritom@PRITOM-PC>

In my gmail inbox email would be render as follows:



Use following code block if you want to use SSL Authentication


props.put("mail.smtp.host", HOST);
props.put("mail.smtp.socketFactory.port", PORT);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", PORT);

GRAILS Database Data To XML File


import grails.converters.XML

grailsApplication.domainClasses.each { def domainClass ->
    dataMap[domainClass.clazz.simpleName] = domainClass.clazz.findAll();
}
String xmlString = new XML(dataMap).toString()

Read & Construct CSV File Using Java Code




package com.pritom.kumar;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by pritom on 10/10/2014.
 */
public class ReadCsvFile {
    final static Charset ENCODING = StandardCharsets.UTF_8;
    private Integer maxRowSize = 0;
    List dataList = new ArrayList();
    public String DELIMITER = ",";

    public static void main(String[] args) throws Exception {
        ReadCsvFile readCsvFile = new ReadCsvFile();
        Long started = System.currentTimeMillis();
        readCsvFile.run();
        Long finished = System.currentTimeMillis();
        Long timeTaken = finished - started;
        readCsvFile.prettyPrint();
        readCsvFile.println("Time Taken: " + timeTaken + " Milli Seconds.");
        readCsvFile.println(readCsvFile.toHtml("csv-output.html"));
        readCsvFile.println(readCsvFile.toCsv("csv-output.csv"));
        System.exit(200);
    }

    public String toCsv(String fileName) throws Exception {
        File file = new File(fileName);
        List fileLines = new ArrayList();
        for (Object object : dataList) {
            fileLines.add(listToBuffer((List) object).toString());
        }
        writeStringList(fileLines, file.getAbsolutePath());
        return file.getAbsolutePath();
    }

    private StringBuffer listToBuffer(List data) {
        StringBuffer stringBuffer = new StringBuffer();
        Boolean firstValue = true;
        for (Object value : data) {
            String line = value.toString();
            if (!firstValue) {
                stringBuffer.append(DELIMITER);
            }
            stringBuffer.append("\"");
            for (Integer index = 0; index < line.length(); index++) {
                char chars = line.charAt(index);
                if (chars == '\"') {
                    stringBuffer.append("\"");
                }
                stringBuffer.append(chars);
            }
            stringBuffer.append("\"");
            firstValue = false;
        }
        return stringBuffer;
    }

    public String toHtml(String fileName) throws Exception {
        File file = new File(fileName);
        List fileLines = new ArrayList();
        for (Integer dataIndex = 0; dataIndex < dataList.size(); dataIndex++) {
            List columnData = (ArrayList) dataList.get(dataIndex);
            maxRowSize = columnData.size() > maxRowSize ? columnData.size() : maxRowSize;
        }
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("<table>");
        for (Integer dataIndex = 0; dataIndex < dataList.size(); dataIndex++) {
            List columnData = (ArrayList) dataList.get(dataIndex);
            stringBuffer.append("<tr><td>" + (dataIndex + 1) + "</td>");
            for (Integer headerIndex = 0; headerIndex < maxRowSize; headerIndex++) {
                stringBuffer.append("<td style='border: 1px solid black;'>" +(columnData.size() > headerIndex ? columnData.get(headerIndex) : "") + "&nbsp;</td>");
            }
            stringBuffer.append("</tr>\n");
            if (dataIndex % 10 == 0) {
                fileLines.add(stringBuffer.toString());
                stringBuffer = new StringBuffer();
            }
        }
        stringBuffer.append("</table>");
        fileLines.add(stringBuffer.toString());
        writeStringList(fileLines, file.getAbsolutePath());
        return file.getAbsolutePath();
    }

    public Boolean writeStringList(List<String> aLines, String aFileName) throws IOException {
        try {
            Path path = Paths.get(aFileName);
            Files.write(path, aLines, ENCODING);
            return true;
        }
        catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public void prettyPrint() {
        for (Integer dataIndex = 0; dataIndex < dataList.size(); dataIndex++) {
            List columnData = (ArrayList) dataList.get(dataIndex);
            print((dataIndex + 1) + ": ");
            for (Integer headerIndex = 0; headerIndex < columnData.size(); headerIndex++) {
                print("<" + columnData.get(headerIndex) + ">");
                if (headerIndex + 1 < columnData.size()) {
                    print(", ");
                }
            }
            println("");
        }
    }

    public void run() throws Exception {
        String csvFile = "input.csv";
        BufferedReader br = null;
        FileReader fileReader = new FileReader(csvFile);
        String line = "";
        try {
            br = new BufferedReader(fileReader);
            while ((line = br.readLine()) != null) {
                if (line.trim().length() > 0) {
                    List tempDataList = parseLine(line.trim());
                    maxRowSize = tempDataList.size() > maxRowSize ? tempDataList.size() : maxRowSize;
                    dataList.add(tempDataList);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private List parseLine(String string) throws Exception{
        InputStream stream = new ByteArrayInputStream(string.getBytes("UTF-8"));
        Reader fr = new InputStreamReader(stream, "UTF-8");
        int chars = fr.read();
        while (chars == '\r') {
            chars = fr.read();
        }
        if (chars < 0) {
            return new ArrayList();
        }
        List dataList = new ArrayList();
        StringBuffer stringBuffer = new StringBuffer();
        Boolean inQuotes = false, lineStarted = false;
        while (chars > 0) {
            if (inQuotes) {
                lineStarted = true;
                if (chars == '\"') {
                    inQuotes = false;
                }
                else {
                    stringBuffer.append((char) chars);
                }
            }
            else {
                if (chars == '\"') {
                    inQuotes = true;
                    if (lineStarted) {
                        stringBuffer.append('\"');
                    }
                }
                else if (chars == DELIMITER.charAt(0)) {
                    dataList.add(stringBuffer.toString());
                    stringBuffer = new StringBuffer();
                    lineStarted = false;
                }
                else if (chars == '\r') {

                }
                else if (chars == '\n') {
                    break;
                }
                else {
                    stringBuffer.append((char) chars);
                }
            }
            chars = fr.read();
        }
        dataList.add(stringBuffer.toString());
        return dataList;
    }

    private void print(Object object) {
        System.out.print(object);
    }

    private void println(Object object) {
        System.out.println(object);
    }
}

Output would be like this:


1: <permalink>, <company>, <numEmps>, <category>, <city>, <state>, <fundedDate>, <raisedAmt>, <raisedCurrency>, <round>
2: <lifelock>, <LifeLock Limited,Company">, <>, <web>, <Tempe>, <AZ>, <1-May-07>, <6850000>, <USD>, <b>
....................
1459: <myrio>, <Myrio>, <75>, <software>, <Bothell>, <WA>, <1-Jan-01>, <20500000>, <USD>, <unattributed>
1460: <grid-networks>, <Grid Networks>, <>, <web>, <Seattle>, <WA>, <30-Oct-07>, <9500000>, <USD>, <a>
1461: <grid-networks>, <Grid Networks>, <>, <web>, <Seattle>, <WA>, <20-May-08>, <10500000>, <USD>, <b>
Time Taken: 96 Milli Seconds.
C:\codes\javap\csv-output.html
C:\codes\javap\csv-output.csv

Java Code for Calculating HMAC-SHA1 & HMAC-SHA256 Signature

package com.pritom.kumar;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by pritom on 09/10/2014.
 */
public class HmacSha1 {
    public static void main(String[] args) {
        System.out.println(hmacSha1("mykey", "helloworld"));
        System.out.println(hmacSha256("mykey", "helloworld"));
    }

    public static String hmacSha1(String KEY, String VALUE) {
        return hmacSha(KEY, VALUE, "HmacSHA1");
    }

    public static String hmacSha256(String KEY, String VALUE) {
        return hmacSha(KEY, VALUE, "HmacSHA256");
    }

    private static String hmacSha(String KEY, String VALUE, String SHA_TYPE) {
        try {
            SecretKeySpec signingKey = new SecretKeySpec(KEY.getBytes("UTF-8"), SHA_TYPE);
            Mac mac = Mac.getInstance(SHA_TYPE);
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(VALUE.getBytes("UTF-8"));

            byte[] hexArray = {
                    (byte)'0', (byte)'1', (byte)'2', (byte)'3',
                    (byte)'4', (byte)'5', (byte)'6', (byte)'7',
                    (byte)'8', (byte)'9', (byte)'a', (byte)'b',
                    (byte)'c', (byte)'d', (byte)'e', (byte)'f'
            };
            byte[] hexChars = new byte[rawHmac.length * 2];
            for ( int j = 0; j < rawHmac.length; j++ ) {
                int v = rawHmac[j] & 0xFF;
                hexChars[j * 2] = hexArray[v >>> 4];
                hexChars[j * 2 + 1] = hexArray[v & 0x0F];
            }
            return new String(hexChars);
        }
        catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}

Output would be like this:

74ae5a4a3d9996d5918defc2c3d475471bbf59ac
7fdfaa9c9c0931f52d9ebf2538bc99700f2e771f3af1c1d93945c2256c11aedd

Saturday, September 27, 2014

GRAILS Render Or Display XML In Browser


import groovy.xml.XmlUtil
....
def xmlString = "YOUR XML STRING";
def xmlAsText = XmlUtil.serialize(xmlString)
render(text: xmlAsText, encoding:"UTF-8", contentType:"text/xml")

GRAILS Custom Codec Example

All custom codec must be in grails-app/utils folder in any package.
Suppose I first created a package named 'pritom.kumar.codecs'.
Then created a groovy (not other type of class) class inside the package such named 'UpperCodec'.groovy
Class name must be end with 'Codec'.
My custom codec groovy class look like this:
package pritom.kumar.codecs

/**
 * Created by pritom on 05/09/2014.
 */
class UpperCodec {
    static encode = { target ->
        return target != null && target instanceof String ? target.toString().toUpperCase() : target
    }
}
Now you can use this as code in controller, service, other java or groovy classes, views and other places like this.

println "i am pritom kumar".encodeAsUpper();

Will print the following:

I AM PRITOM KUMAR

Basically you can do various things using custom codec.

Friday, September 19, 2014

Spring MVC - Custom Exception Handling & Send Appropriate Error Code

Download full source code


Create a custom exception handler class as follows:


package com.pkm.maven.exception;

public class SpringException extends RuntimeException {
    private String exceptionMsg;
    
    public SpringException(String exceptionMsg) {
        this.exceptionMsg = exceptionMsg;
    }
    
    public String getExceptionMsg() {
        return this.exceptionMsg;
    }
    
    public void setExceptionMsg(String exceptionMsg) {
        this.exceptionMsg = exceptionMsg;
    }
}

Add following lines of code to your XXX-servlet.xml under WEB-INF


<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="com.pkm.maven.exception.SpringException">ExceptionPage</prop>
        </props>
    </property>
    <property name="defaultErrorView" value="error"/>
</bean>

Create a jsp page named 'ExceptionPage.jsp' defined in previous XXX-servlet.xml file under WEB-INF folder.


<h3 class="error">${exception.exceptionMsg}</h3>

Also create a file named 'error.jsp' under WEB-INF/jsp/ folder


<h3>General Error Page</h3>

Now time to throw custom exception

From method1 & method2 i am throwing my custom error so rendering my custom error page 'ErrorPage.jsp' & in method4, I am not throwing any exception but when invoking the line 'nullString.length()', it automatically throwing general exception, so rendering 'error.jsp' as defined in XXX-servlet.xml.


package com.pkm.maven.controller;

import com.pkm.maven.exception.SpringException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

/**
 * Controller action would be like this
 * public (ModelAndView | Map | String | void) actionName(HttpServletRequest, HttpServletResponse [,HttpSession] [,CommandObject]);
 * @author Pritom K Mondal
 */

public class CustomerController extends MultiActionController {    
    public ModelAndView method1(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );
        throw new SpringException("Error from customer controller and method1() action.");
        //return new ModelAndView("CustomerPage", "msg", "method1() method"); 
    }
 
    public ModelAndView method2(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );
        throw new Exception("Error from customer controller and method2() action.");
        //return new ModelAndView("CustomerPage", "msg", "method2() method"); 
    }
 
    public ModelAndView method3(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        return new ModelAndView("CustomerPage", "msg", "method3() method"); 
    }
 
    public ModelAndView method4(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        String nullString = null;
        Integer length = nullString.length();
        return new ModelAndView("CustomerPage", "msg", "method4() method"); 
    }
}

Output would be like this in browser if you browse 'customer/method1' or 'customer/method2':


Output would be like this in browser if you browse 'customer/method4':