This article is for creating simple HTML Styled Email using Java. Its difficult to manage HTML code in java. It will be clumsy when its needed to place some data in that HTML code. To avoid all these problems , I have created 3 simple steps
  1. Prepare HTML mock-up of Email Body
  2. Make your data ready in POJO class
  3. Place your data in HTML code using TemplateMatcher

Prepare HTML mock-up 

First of all, prepare your HTML Email mock-up by using any online HTML editor (codepen, cssdeck etc). Lets send student's progress report as email. Find below mock-up and HTML code for Email body

Mock-up 

HTML Code

<div style="padding:20px">
<h2>Progress Report</h2>
<b>Student Name</b> : Srinivas Dasari<br/>
<b>Role No</b> : 690752021<br/>
<br/>
<table border="1" style="border-collapse:collapse;text-align:center">
  <tr>
    <th style="padding:5px">Subject</th>
    <th style="padding:5px">Grade</th>
  </tr>
  <tr>
    <td>Mathmatics</td>
    <td  style="color:blue">A</td>
  </tr>
   <tr>
    <td>Science</td>
    <td style="color:orange">C</td>
  </tr>
  <tr>
    <td>Economics</td>
    <td style="color:red">D</td>
  </tr> 
</table>
</div>

Make your Data ready 

To fill above mock-up we need student name, id and marks. Lets create pojo with those fields.
public class ProgressReport
{
    private String rollNo;

    private String mathmatics;

    private String name;

    private String economics;

    private String science;

    public String getRollNo ()
    {
        return rollNo;
    }

    public void setRollNo (String rollNo)
    {
        this.rollNo = rollNo;
    }

    public String getMathmatics ()
    {
        return mathmatics;
    }

    public void setMathmatics (String mathmatics)
    {
        this.mathmatics = mathmatics;
    }

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    public String getEconomics ()
    {
        return economics;
    }

    public void setEconomics (String economics)
    {
        this.economics = economics;
    }

    public String getScience ()
    {
        return science;
    }

    public void setScience (String science)
    {
        this.science = science;
    }
}

TemplateMatcher Introduction

To use TemplateMatcher, you need to have jlibs-core jar in build-path. You can download this jar from https://code.google.com/p/jlibs/downloads/list
  1. Create string template using TemplateMatcher
  2. Use that template in strings
  3. Replace the template with suitable data
import jlibs.core.util.regex.TemplateMatcher;

String msg = "Student Name : ${name} \n Student ID : ${id} ";
TemplateMatcher matcher = new TemplateMatcher("${", "}");
Map<String, String> vars = new HashMap<String, String>();
vars.put("name", "srinivas");
vars.put("id", "21");
System.out.println(matcher.replace(msg, vars));
Output will be
Student Name : srinivas 
Student ID : 21

Place Data in your HTML code

Its time to create templates in HTML and replace with pojo data. Lets create templates in HTML code.
<div style="padding:20px">
<h2>Progress Report</h2>
<b>Student Name</b> : ${name}<br/>
<b>Role No</b> : ${id}<br/>
<br/>
<table border="1" style="border-collapse:collapse;text-align:center">
  <tr>
    <th style="padding:5px">Subject</th>
    <th style="padding:5px">Grade</th>
  </tr>
  <tr>
    <td>Mathmatics</td>
    <td  style="color:blue">${mathmatics}</td>
  </tr>
   <tr>
    <td>Science</td>
    <td style="color:orange">${science}</td>
  </tr>
  <tr>
    <td>Economics</td>
    <td style="color:red">${economics}</td>
  </tr> 
</table>
</div>
Use Convert HTML or Text to Javascript or Java variable - Online online tool to convert HTML into Java string, it is easier way.
Final code will be
ProgressReport pr = new ProgressReport();
pr.setName("srinivas");
pr.setRollNo("21");
pr.setMathmatics("A");
pr.setScience("C");
pr.setEconomics("D");
StringBuilder body = new StringBuilder(); 
body.append("<div style=\"padding:20px\">")
     .append("<h2>Progress Report</h2>")
     .append("<b>Student Name</b> : ${name}<br/>")
     .append("<b>Role No</b> : ${id}<br/>")
     .append("<br/>")
     .append("<table border=\"1\" style=\"border-collapse:collapse;text-align:center\">")
     .append("  <tr>")
     .append("    <th style=\"padding:5px\">Subject</th>")
     .append("    <th style=\"padding:5px\">Grade</th>")
     .append("  </tr>")
     .append("  <tr>")
     .append("    <td>Mathmatics</td>")
     .append("    <td  style=\"color:blue\">${mathmatics}</td>")
     .append("  </tr>")
     .append("   <tr>")
     .append("    <td>Science</td>")
     .append("    <td style=\"color:orange\">${science}</td>")
     .append("  </tr>")
     .append("  <tr>")
     .append("    <td>Economics</td>")
     .append("    <td style=\"color:red\">${economics}</td>")
     .append("  </tr> ")
     .append("</table>")
     .append("</div>");
TemplateMatcher matcher = new TemplateMatcher("${", "}");
Map<String, String> vars = new HashMap<String, String>();
vars.put("name", pr.getName());
vars.put("id", pr.getRollNo());
vars.put("mathmatics", pr.getMathmatics());
vars.put("science", pr.getScience());
vars.put("economics", pr.getEconomics());
String emailBody = matcher.replace(body.toString(), vars);

Java function to Send Email 

Just send email using below java function
    public static void sendMail(String mail,String sub,String mess) throws AddressException, MessagingException {
        Logger.info(className, "entering sendMail "+mail);
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
 
        Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("enter your gmail here","enter your password here");
                }
            });
 
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress("enter your email here"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(mail));
            message.setSubject(sub);
            message.setContent(mess,
                    "text/html" );
            Transport.send(message);
        Logger.info(className, "leaving sendMail");
    }
Thank you for reading. I hope it helps
Read More
This article gives fastest way to create Android, IOS, Windows App with HTML and JavaScript.

Create PhoneGap build account :

Just open https://build.phonegap.com/ and create account
Here you can create projects and you can build them and you can download install-able files.

Setup PhoneGap Project :

Download the project PhoneGap-Start-Master
/www/index.html is main file. Whatever HTML  you have, just paste in this file. Just open this file in web browser to see how your app looks like. 
/www/js for JavaScript files. 
/www/css is for CSS files. 
/www/img is for image files.

Create Project :

Create project in https://build.phonegap.com/
ZIP the www folder
Upload the zip file
Click on build
Now you can download Android, Windows, IOS install-able files. Just download those files and  install in respective smart phones

Read More
Phonegap / Cordova needs much designing work in order to make screens and icons. If you use same icon to create all different sizes of icons and screens then why you have to waste your time for changing icons and screen sizes. Here it is simple way to do it.
This program was created based on phonegap-start-master project. Download this project and you can see icons at res/icon and screens at res/screen folder. Make you app icon ready.

Java Library :

For quality image scaling, I have used java-image-scaling library.

Folder copy program :

To create destination folder from source folder, I have created one Folder copy java program. Find complete explanation at http://blog.sodhanalibrary.com/2014/09/copy-file-or-folder-in-hierarchical-way.html

Java Program to create icons :

Replace destinationDir with your own destination directory Path
Replace sourceDir with your own source directory Path
Replace appIcon with your own app icon Path
Run this program
Find destination path for new Icons
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import com.mortennobel.imagescaling.ResampleOp;

public class CreatePhoneGapIcons {
  static String destinationDir = "D:\\phonegap-start-master\\phonegap-start-master\\phonegap-start-master\\www\\copyOfResources\\res1";
  static String sourceDir = "D:\\phonegap-start-master\\phonegap-start-master\\phonegap-start-master\\www\\res\\icon";
  static String appIcon = "C:\\Documents and Settings\\srinivas\\My Documents\\My Pictures\\documentation\\mathTables.png";
  public static void main(String[] args) throws IOException {
      File file = new File(sourceDir);
      readFile(file, destinationDir);
  }
  
  public static void readFile(File file, String path) throws IOException {
      if(file.isDirectory()) {
          System.out.println("DIR "+ file.getAbsolutePath());
          File[] files = file.listFiles();
          String destDirPath = path + "\\" + file.getName();
          File destDir = new File(destDirPath);
          if(!destDir.exists()) {
              destDir.mkdirs();
          }
          for(int i=0; i<files.length; i++) {
              readFile(files[i],destDirPath);
          }
      } else {
          String destFilePath = path + "\\" + file.getName();
          File destFile = new File(destFilePath);
          if(!destFile.exists()) {
              destFile.createNewFile();
          }
          System.out.println("File "+ file.getAbsolutePath());
          if(file.getName().endsWith(".png")) {
              copyFileUsingStream(file, destFile);
              BufferedImage sourceFileImg = ImageIO.read(file);
              BufferedImage appIconImg = ImageIO.read(new File(appIcon));
              ResampleOp  resampleOp = new ResampleOp(sourceFileImg.getWidth(), sourceFileImg.getHeight());
              BufferedImage generatedIcon = resampleOp.filter(appIconImg, null);
              ImageIO.write(generatedIcon,"png", destFile);
          } else {
              copyFileUsingStream(file, destFile);
          }
            
      }
  }  
  
  
  private static void copyFileUsingStream(File source, File dest) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }
    }

}

Java Program to create screens :

Replace destinationDir with your own destination directory Path
Replace sourceDir with your own source directory Path
Replace appIcon with your own app icon Path
Run this program
Find destination path for new Screens
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import com.mortennobel.imagescaling.ResampleOp;

public class CreatePhoneGapScreens {
  static String destinationDir = "D:\\phonegap-start-master\\phonegap-start-master\\phonegap-start-master\\www\\copyOfResources\\res1";
  static String sourceDir = "D:\\phonegap-start-master\\phonegap-start-master\\phonegap-start-master\\www\\res\\screen";
  static String appIcon = "C:\\Documents and Settings\\srinivas\\My Documents\\My Pictures\\documentation\\mathTables.png";
  public static void main(String[] args) throws IOException {
      File file = new File(sourceDir);
      readFiles(file, destinationDir);
      //setTransparentBackground("C:\\Documents and Settings\\srinivas\\My Documents\\My Pictures\\documentation\\mathTables.png");
  }
  
  public static void readFiles(File file, String path) throws IOException {
      if(file.isDirectory()) {
          System.out.println("DIR "+ file.getAbsolutePath());
          File[] files = file.listFiles();
          String destDirPath = path + "\\" + file.getName();
          File destDir = new File(destDirPath);
          if(!destDir.exists()) {
              destDir.mkdirs();
          }
          for(int i=0; i<files.length; i++) {
              readFiles(files[i],destDirPath);
          }
      } else {
          String destFilePath = path + "\\" + file.getName();
          File destFile = new File(destFilePath);
          if(!destFile.exists()) {
              destFile.createNewFile();
          }
          System.out.println("File "+ file.getAbsolutePath());
          if(file.getName().endsWith(".png")) {
              copyFileUsingStream(file, destFile);
              BufferedImage sourceScreenImage = ImageIO.read(file);
              BufferedImage appIconImg = ImageIO.read(new File(appIcon));
              BufferedImage generatedScreen =  createScreenImage(appIconImg,sourceScreenImage.getWidth(), sourceScreenImage.getHeight());
              ImageIO.write(generatedScreen,"png", destFile);
          } else if(file.getName().equals("Thumbs.db")) {
              
          } else {
              copyFileUsingStream(file, destFile);
          }
            
      }
  }  
  
  private static BufferedImage createScreenImage(BufferedImage appIconImg, int width, int height) throws IOException {
      int type = appIconImg.getType() == 0? BufferedImage.TYPE_INT_ARGB : appIconImg.getType();
      BufferedImage newPGScreen = new BufferedImage(width, height, type);
      Graphics2D g = newPGScreen.createGraphics();
      g.setColor(new Color(255,255,255));
      g.fillRect(0, 0, width, height);
      double minSize = 0, tw = (double)width, th = (double)height;
      if(tw < th) {
          minSize = tw;
      } else {
          minSize = th;
      }
      minSize = minSize / 4;
      ResampleOp  resampleOp = new ResampleOp((int)(minSize*2), (int)(minSize*2));
      BufferedImage resizedIcon = resampleOp.filter(appIconImg, null);
      g.drawImage(resizedIcon, (int)((tw/2) - minSize), (int)((th/2) - minSize) , null);
      g.dispose();
      return newPGScreen;
  }


  private static void copyFileUsingStream(File source, File dest) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }
    }
  
}
Read More
This tutorial teaches how to read and differentiate different type of XML Nodes. You might also interested to read parsing JSON tutorial  at Read JSON with JAVA using Google-gson library.
There are 3 important XML data parts.
  1. Element - Elements have tags. In above example bookstore, book, title, author are elements
  2. Attribute - These are attributes for Elements. In above example category is attribute.
  3. Text - Simple text surrounded by tags

Program Flow :

  1. Read ROOT Element as Node
  2. If it is Text, go to 3rd step else go to 4th step.
  3. print text value
  4. If it is Element, print all attributes and list children and send them to 2nd step

XOM Java Library :

By using traditional DOM and SAX parser we cannot implement above program flow. We need XOM parser. You can download XOM at http://www.cafeconleche.org/XOM/xom-1.2.10.jar

Java Code :

import java.io.*;
import java.nio.charset.StandardCharsets;
import nu.xom.*;

public class XOMParserXML {

  public static void main(String[] args) {
    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><bookstore>" + "\n<!-- Servlets --><book category=\"CHILDREN\">"
            + "\n    <title>Harry Potter</title>"
            + "\n    <author>J K. Rowling</author>"
            + "\n    <year>2005</year>" + "\n    <price>29.99</price>"
            + "\n  </book>" + "\n  <book category=\"WEB\">"
            + "\n    <title>Learning XML</title>"
            + "\n    <author>Erik T. Ray</author>"
            + "\n    <year>2003</year>" + "\n    <price>39.95</price>"
            + "\n  </book>" + "\n</bookstore>";
    System.out.println(xml);
    
    // Remove All Spaces
    xml = trimSpaces(xml);
    try {
      Builder builder = new Builder();
      InputStream stream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
      Document doc = builder.build(stream);
      // Get Root Element
      Element root = doc.getRootElement();
      // List Children for Root Element
      listChildren(root, 0);      
    }
    catch (ParsingException ex) { 
      System.out.println(args[0] + " is not well-formed.");
      System.out.println(ex.getMessage());
    }  
    catch (IOException ex) { 
      System.out.println(ex);
    }  
  
  }
  
  public static void listChildren(Node current, int depth) {
   
    printSpaces(depth);
    String data = "";
    // If it is element
    if (current instanceof Element) {
        Element temp = (Element) current;
        data = ": " + temp.getQualifiedName();
        // print Attributes
        for (int i = 0; i < temp.getAttributeCount(); i++) {
          Attribute attribute = temp.getAttribute(i);
          String attValue = attribute.getValue();
          attValue = attValue.replace('\n', ' ').trim();
          if (attValue.length() >= 20) {
            attValue = attValue.substring(0, 17) + "..."; 
          }
          data += "\r\n    ";
          data += attribute.getQualifiedName();
          data += "=";
          data += attValue;
        }
        System.out.println(current.getClass().getName() + data);
        
        // iterate child nodes
        for (int i = 0; i < current.getChildCount(); i++) {
            listChildren(current.getChild(i), depth+1);
        }
    }
    //If it is text
    else if (current instanceof Text) {
        String value = current.getValue();
        value = value.replace('\n', ' ').trim();
        data = ": " + value;
        System.out.println(current.getClass().getName() + data);
    }
    
  }
 
  // Method to remove all space and new lines
  public static String trimSpaces(String input) {
        BufferedReader reader = new BufferedReader(new StringReader(input));
        StringBuffer result = new StringBuffer();
        try {
            String line;
            while ( (line = reader.readLine() ) != null)
                result.append(line.trim());
            return result.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
   }
  
  // Method to print spaces
  private static void printSpaces(int n) {
    for (int i = 0; i < n; i++) {
      System.out.print("  "); 
    }
    
  }

}

Read More
Here in this tutorial I will explain how to copy files or folders by reading them in a hierarchical way.

Program Flow : 

  1. Read Input File or Directory  path and Destination path
  2. Is input File is Directory or real File ?
  3. If it is directory, then create destination directory and list all files and send them to 2nd step
  4. If it is file, then create destination file and copy

Java Code :

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFiles {
   public static void main(String args[]) throws IOException {
       String source="D:\\Gate", destination = "D:\\Gate1";
       File file = new File(source);
       copyFiles(file, destination);     
   }
   
   public static void copyFiles(File file, String path) throws IOException {
          if(file.isDirectory()) {
              System.out.println("DIR "+ file.getAbsolutePath());
              File[] files = file.listFiles();
              String destDirPath = path + "\\" + file.getName();
              File destFile = new File(destDirPath);
              if(!destFile.exists()) {
                  destFile.mkdirs();
              }
              for(int i=0; i<files.length; i++) {
                  copyFiles(files[i],destDirPath);
              }
          } else {
              String destFilePath = path + "\\" + file.getName();
              File destFile = new File(destFilePath);
              if(!destFile.exists()) {
                  destFile.createNewFile();
              }
              System.out.println("File "+ file.getAbsolutePath());
              copyFileUsingStream(file, destFile);
          }
      }
   
   private static void copyFileUsingStream(File source, File dest) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }
    }

}
Read More
To convert money from one currency to another currency,  we need Currency Exchange Rate Value. Yahoo is providing an online API to get currency exchange rates. Here in below example I explained how to convert Money from one currency to other using Yahoo Finance API.

Steps to Convert Currency :

Yahoo Finance API :

Observe below GET request URL. You can see the query in q parameter. Here the Currency codes were paired. Click on below link to see output XML format.

Example :

If you want to get US dollar value in Indian rupees then you have to form below URL
String url ="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDINR%22)&env=store://datatables.org/alltableswithkeys"; 
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);

// Send request
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode + "\n\n");
BufferedReader in = new BufferedReader(
       new InputStreamReader(con.getInputStream()));
String outputLine;

// reading output from Request
StringBuffer response = new StringBuffer(); 
while ((outputLine = in.readLine()) != null) {
   response.append(outputLine);
}
in.close();

Convert XML Response to POJO class :

// Converting XML to JSON and then JSON to POJO Classes
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
QueryPojo mp = gson.fromJson(Utility.convertXMLtoJSON(response.toString()), QueryPojo.class);

Convert Currency With Exchange Rate :

String exchangeRate = mp.getQuery().getResults().getRate().getRate();
BigDecimal amountOne = new BigDecimal(amout);
BigDecimal rate = new BigDecimal(exchangeRate);
System.out.println(amountOne.multiply(rate));
Read More
AngularJS supports some jQuery methods known as jqLite. Here you can find tutorials how to use those jQuery methods with AngularJS. These articles are basic tutorials...That's why I provided TryItYourSelf editor.



  1. .append(), .prepend()  -   Append or Prepend html to div using AngularJS
  2. .addClass(), .removeClass(), .toggleClass()Add Class, Remove Class or Toggle Class to div using AngularJS
  3. .text(), .html()Set Text or Html to div using AngularJS
  4. .attr()Set Attribute or Remove Attribute using AngularJS
  5. .css()Change CSS of an element using AngularJS
  6. .prop() - Read And Set Property to an element using AngularJS
  7. .empty(), .remove() - Empty or Remove an Element using AngularJS
  8. .val()Read and Set Input Value using AngularJS
  9. .wrap() - Wrap HTML Structure around an Element using AngularJS
  10. .clone()Cloning elements using AngularJS
Read More

Search This Blog

Loading...

Blogroll

Srinivas Dasari
find me on facebook
follow me on twitter

Follow this blog by Email

Popular Posts