In this article I am going to explain how to read JSON with JavaScript. The basic part of the JSON is JsonElement. There are 4 types JSON elements.
  1. Json Object : Surrounded with curly braces and have child JSON elements
  2. Json Primitive Element : It contains field name and it's value
  3. Json Array Element : It contains field name and array of JSON elements.
  4. Json Null Element : It contains nothing 

Program Flow

Program flow for JSON reading is shown in the below diagram. 
  1. If element is JSON Object then iterate it into field names and JSON elements and process those JSON elements. 
  2. If element is JSON Array then iterate it into JSON elements and process those JSON elements.
  3. If element is JSON Primitive then print its value as String




JavaScript Code :

In the below example there are 4 JSON input strings, First 3 are normal JSON String, Fourth-one is Array.
checkIt - Is for to check the Object Type
readObject - Is for reading JSON Object
readArray - Is for reading JSON Array

   var object = {
        "age":23,
        "name":"srinivas",
        "blog":"http://blog.sodhanalibrary.com",
        "messages":["msg1","msg2","msg3"] 
    };

    var arrayConstructor = [].constructor;
    var objectConstructor = {}.constructor;

    var html='';

    checkIt(object);

    function checkIt(object) {
      if (object === null) {
        html += "\n\nnull \n";
      }
      else if (object === undefined) {
          html += "\n\nundefined \n";
      }
      else if (object.constructor === arrayConstructor) {
          html += "\n\nArray :: \n";
          readArray(object);
      }
      else if (object.constructor === objectConstructor) {
          readObject(object);
      }
      else {
         html += "\n\nPrimitive Datatype :: \n";
         html += object;
      }
    }
             

    function readObject(myobj) {
      html += "\n\nObject :: \n";
      html += myobj;
      for (key in myobj) {
        if (myobj.hasOwnProperty(key)) {
            html += "\n\nKey Value Pair :: \n";
            html += key + " = " + myobj[key];
            checkIt(myobj[key]);
        }
      }  
    }

    function readArray(myobj) {
      var n = myobj.length;
      html += myobj;
      for(var i=0;i<n;i++) {
        checkIt(myobj[i]);
        html += myobj[i];
      }
    }
    document.getElementById("jsonObject").innerHTML = html;

Read More
If you want to take screenshot, what will you do ? Click on printScreen button and paste in Microsoft Paint and then save that screenshot to some folder. If you are testing any software then you have to take plenty of screenshots then this process will be irritating. By using below java program you can easily take screenshots with single click.
Here the Directory Path represents destination folder to store screenshots 
import java.awt.AWTException;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Screen2Image {
    JFrame jFrame = new JFrame("Take Screen Shots");  // Create Frame        
    JLabel dirPathLb = new JLabel("Directory Path");
    JLabel error = new JLabel("");
    JTextField dirFld = new JTextField(20);
    JButton takeScrButton = new JButton("Take Screen Shot");
    int count = 0;
    
    public void showPanel() throws HeadlessException, AWTException, IOException {
        jFrame.setLayout(new FlowLayout());
        JPanel jp =new JPanel(); 
        jp.add(dirPathLb);
        jp.add(dirFld);
        dirFld.setText("C:\\");
        error.setForeground(Color.red);
        jFrame.add(jp);
        jFrame.add(takeScrButton);
        jFrame.add(error);
        jFrame.setSize(400,120);    // Set size of frame
        jFrame.setVisible(true);    // Show the window
        takeScrButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                BufferedImage image;
                try {
                    image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
                    count++;
                    String dirStr = dirFld.getText();
                    File dir = new File(dirStr);
                    if(!dir.exists()){
                        dir.mkdirs();
                    }
                    File file = new File(dir+File.separator+"screen"+count+".png");
                    if(!file.exists()) {
                        file.createNewFile();
                    }
                    ImageIO.write(image, "png", file);
                    error.setText("");
                } catch (HeadlessException e1) {
                    e1.printStackTrace();
                    error.setText(e1.getMessage());
                } catch (AWTException e1) {
                    e1.printStackTrace();
                    error.setText(e1.getMessage());
                } catch (IOException e1) {
                    e1.printStackTrace();
                    error.setText(e1.getMessage());
                }
                
                
            }
         });
        
    }

    public static void main(String[] args) throws HeadlessException, AWTException, IOException {
        new Screen2Image().showPanel();
    }
}
Read More
Recently I had one session on Business Communication
This session gave some nice tips to improve business skills

At first The mentor asked us to discuss below points.

  1. Everything we do communication
  2. The way we begin the message, often effects the outcome of communication
  3. The way message is delivered, often effects the message is delivered
  4. The actual communication is the message received , not the message intended
  5. Communication is two way street, we need to give as well as gather
  6. Communication is dance

Everything we do communication

Communication can be done by voice, text, email, phone call, body language...etc
Suppose you are talking with someone with no interest then your body language will tell that.
Your facial expression will tell the intention behind your words.

The way we begin the message, often effects the outcome of communication

For example...you have to talk with new person and you don't know his name.
How will you know his name ?
If you ask him directly "what is your name", It will be informal.
To know his name you have to introduce yourself with your name, Then He will introduce himself with his name.
This approach will be polite and formal.
There is a saying in English "first impression is best impression", so you have to create some good impression with introduction itself, Later communication will go smoothly.

The way message is delivered, often effects the message is delivered

We can deliver one message in so many ways (Email , SMS, voice message, Direct conversation)
If you want to tell something to your manager, how will tell ?

  •    No Important message - Simply send one Email
  •    Important message - Call and tell
  •    Very Important - Approach directly

Here message delivery process describes its urgency

The actual communication is the message received , not the message intended

No need to explain. It is not important that what we want to tell, but What other person understood is really matters

The actual communication is the message received , not the message intended

Communication is two way street, we need to give as well as gather
No need to explain. The above sentence itself will tell the meaning

Communication is dance

Dancer dances to music. If the dancer don't dance according to the music, It will be very bad to seen and spectaculars will throw some stones on dancer soon.
In the same way, if you speak irrelevantly with others, then the communication will be failed.

Lets discuss some real life situations

Introducing :

Suppose you got a situation to introduce yourself, how will you do ?
I am Srinivas - Correct
This is Srinivas - in phone conversations
My name is Srinivas -  Childish
Myself srinivas - Wrong

Making request :

If you want to request some one to do some thing, How will you ask ?

I request you to
I would like you to ....please
Could you ask....to....for me
Do you think you could....

Disagreement

You have to disagree in such a way that others should not upset .
Your project manager asked you come early in the morning by 7:00 AM in the morning to finish the task, Now yo have to disagree because you have appointment with doctor at 9:00 AM. Now how will you disagree ?

Your disagree statement should contain Politeness, Reason, Offer other alternative.

I am sorry, I couldn't come by 8:00 AM because I have an appointment with doctor but i can finish the task by working extra hours in office.

Clarification

You need some clarification on requirements given by client. How will you ask ?
You need some clarification on requirements given by client. How will you ask ?

Can i clarify this ?
I am sorry I am not able to catch up with ?
Would you like to call back later ?
I am sorry , I am not sure about the meaning of the term
So you mean to say that
As I understand it
Lets sum up then, you propose
could we go through that again ?
Could you explain that point again ?
Could I ask few questions ?
to see whether I understood your position ?
Do you  mean that...?
I am sorry, whether you you want me to do ?

Asking Apology 

I am sorry
I apologize for the mistake
Please accent our apologies for....
Read More
For creating Facebook App, we need Icons and banners for the app with defined sizes. At the time of development ,we don't concentrate on Icons and Banners design. At the starting stage we need rough Icons and Banners. If you are a java developer you can create these Icons and Banners in a minute. You can find the basic Idea of this app at http://blog.sodhanalibrary.com/2014/09/create-phonegapcordova-icons-and.html

Java Library :

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

Java Program to create icons :

Replace destinationDir with your own destination directory Path
Replace appIcon with your own app icon Path
Add dimension of the Icon you want to dimensions
Run this program
Find destination path for new Icons
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import com.mortennobel.imagescaling.ResampleOp;

public class CreateFbAppIcons {
  static String destinationDir = "C:\\fbIcons";
  static String appIcon = "C:\\icon.png";
  static ArrayList<Dimension> dimensions = new ArrayList<Dimension>();
  
  public static void main(String[] args) throws IOException {
      dimensions.add(new Dimension(1024,1024));
      dimensions.add(new Dimension(16,16));
      readFile(destinationDir);
  }
  
    public static void readFile(String path) throws IOException {
        File destDir = new File(destinationDir);
        if(!destDir.exists()) {
            destDir.mkdirs();
        }
        BufferedImage appIconImg = ImageIO.read(new File(appIcon));
        for(Dimension dim : dimensions) {
            String destFilePath = destinationDir+"\\icon"+(int)dim.getWidth()+"X"+(int)dim.getHeight()+".png";
            File destFile = new File(destFilePath);
            if(!destFile.exists()) {
                  destFile.createNewFile();
            }
            System.out.println("File "+ destFile.getAbsolutePath());
            ResampleOp resampleOp = new ResampleOp((int)dim.getWidth(),(int)dim.getHeight());
            BufferedImage generatedIcon = resampleOp.filter(appIconImg, null);
            ImageIO.write(generatedIcon, "png", destFile);  
        }
    } 
  
}

Java Program to Create Banners :

Run this program
Find destination path for new Banners
If you want any banner with specific size then you can add those dimension to dimensions
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import com.mortennobel.imagescaling.ResampleOp;

public class CreateFbBanners {
  static String destinationDir = "C:\\fbIcons";
  static String appIcon = "C:\\icon.png";
  static ArrayList<Dimension> dimensions = new ArrayList<Dimension>();
  
  public static void main(String[] args) throws IOException {
      dimensions.add(new Dimension(800,150));
      dimensions.add(new Dimension(1200,627));
      dimensions.add(new Dimension(1848,682));
      dimensions.add(new Dimension(155,100));
      readFile(destinationDir);
  }
  
    public static void readFile(String path) throws IOException {
        File dir = new File(destinationDir);
        if(!dir.exists()) {
            dir.mkdirs();
        }
        BufferedImage appIconImg = ImageIO.read(new File(appIcon));
        for(Dimension dim : dimensions) {
            String destFilePath = destinationDir+"\\icon"+(int)dim.getWidth()+"X"+(int)dim.getHeight()+".png";
            File destFile = new File(destFilePath);
            if(!destFile.exists()) {
                  destFile.createNewFile();
            }
            System.out.println("File "+ destFile.getAbsolutePath());
            ImageIO.write(createScreenImage(appIconImg,(int)dim.getWidth(),(int)dim.getHeight()), "png", 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;
      }

}
Read More
Recently I worked with Eclipse plugin development. While I tried run Ecipse plugin project, I got "PermGen space - OutOfMemory Error". I just googled and read some online resources and solved that problem.

Why this Error

Whenever we tried to run the plugin project, Ecipse will open new Eclipse with new work-space. This new work-space will run on new JVM. Generally this JVM memory space is 64mb. This memory is not sufficient to run Eclipse. This is why it throws "PermGen space - OutOfMemory Error".
To avoid this exception, we need to increase PermGen space.

Increase in PermGen Space

Go to Eclipse menu bar and click on
Window > Preferences > Java > Installed JREs > Select the JDK > Edit >
Enter "-XX:MaxPermSize=256m" in "Default VM Arguments" field.
Now the JVM to run Eclipse plugin will have 256MB memory. It is sufficient to run Eclipse. If 256m is not sufficient then make it as 512m.
Read More
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

Search This Blog

Loading...

Blogroll

Srinivas Dasari
find me on facebook
follow me on twitter

Follow this blog by Email

Popular Posts