Friday, December 6, 2013

Google GSON - Example Usage In Java

If you're a Java Developer like me then I'm certainly sure that you have heard about Google's GSON. Well, it's develop to provide a simple yet efficient way to create JSON in Java. JSON means Javascript Object Notation. It is a data interchange which is same as the old XML.

In this tutorial, we are going to implement Google's GSON to our Java application. First, you need to create a simple class that JSON data can represent:



import java.util.ArrayList;
import java.util.List;



public class MyData{
 
 public String message = "Hello, World!";
 private List messages = new ArrayList(){
  {
   add("Message for friends");
   add("Message for family");
   add("Message for girlfriends");
   add("Message for strangers");
  }
 };
 
 public String toString(){
  return "MyData[message=" + message + ", messages=" + messages + "]";
 }
}
It represents our JSON data. So now we want to convert this object into JSON format. How should we do that? Please copy & paste the example below:

import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;
 
public class Main {
    public static void main(String[] args) {
 
 MyData obj = new MyData();
 Gson gson = new Gson();
 String json = gson.toJson(obj);
 try {
  FileWriter writer = new FileWriter("C:\\data.json");
  writer.write(json);
  writer.close();
 } catch (IOException e) {
  e.printStackTrace();
 }
 System.out.println("JSON:" + json);
 
    }
}
The trick here is to call the Gson class' toJson method. It will going to return the JSON encoded object as String. Very handy! Now the next lines are just the method to save it to a file called "data.json". Do not forget to close your resources to free up some memories.

Now that you have already your json file, you probably want it to send over the network. You need now to convert the JSON encoded format back to a simple java object. Here's the code for that:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
 
public class Main {
    public static void main(String[] args) {
  Gson gson = new Gson();
  try {
   BufferedReader br = new BufferedReader( new FileReader("C:\\data.json"));
   MyData data = gson.fromJson(br, MyData.class);
   System.out.println(data);
  
  } catch (IOException e) {
   e.printStackTrace();
  }
    }
}

Play around this wonderful library by Google and I'm sure in one day you will get the hang of it! Easy right?
Thanks for reading all my stuff here in Geek Stuff!

Save Object State - How To Use Java Serialization

Object serialization in Java is one of the advanced topic in Java. In this tutorial, I'm going to show you the basic on how to serialize a simple object and then deserialize it later.

First, you want to create a simple object in which you wanted to be serialized. By the way, when I say serialize, Java will store the "state" of the particular object in bytes like saving it into a file.

Please copy & paste the source code below:

public class Hero {
 
 private int energy, life, locationx, locationy = 0;

 public Hero(){
  
 }
 
 public void setEnergy(int e){
  energy = e;
 }
 
 public void setLife(int l){
  life = l;
 }
 
 public void setLocation(int x, int y){
  locationx = x;
  locationy= y;
 }
 
 public int getLocationX() { return locationx; }
 public int getLocationY() { return locationy; }
 public int getLife() { return life; }
 public int getEnergy() { return energy; }

}

Our hero class will be serialize by creating an instance of it and using the ObjectOutputStream bundled in the Java foundation class. See example below to change the state of the Hero class and save it to a file called "hero.dat":

public class Main {
 
 public static void main(String args[]){
  Hero hero = new Hero();
  hero.setLife(100);
  hero.setEnergy(99);
  hero.setLocation(1,1);
  
  try {
         FileOutputStream fOut = new FileOutputStream("C:\\hero.dat");
         ObjectOutputStream oOut = new ObjectOutputStream(fOut);
         oOut.writeObject(e);
         oOut.close();
         fOut.close();
         System.out.printf("Success! Object has been saved.");
     }catch(Exception e){
           e.printStackTrace();
     }
 }
}
Now check out your C:\ directory and most certainly you will find a file named hero.dat which our Hero object has been stored and saved.


Now you wanted to "load" the state of our Hero class back to your application probably because you wanted to change the state. This is where the ObjectInputStream class comes into play. To deserialize our object, please run this example code given below:


public class Main {
 
 public static void main(String args[]){
  Hero hero = null;
  
  
  try {
         FileInputStream fIn = new FileInputStream("C:\\hero.dat");
         ObjectInputStream oIn = new ObjectInputStream(fIn);
         hero = (Hero) oIn.readObject();
         fIn.close();
         oIn.close();
         System.out.printf("Success! Object has been restored.");
     }catch(Exception e){
           e.printStackTrace();
     }
     
     System.out.println("Hero Life: " + hero.getLife());
     System.out.println("Hero Energy: " + hero.getEnergy());
     System.out.println("Hero X: " + hero.getLocationX());
     System.out.println("Hero Y: " + hero.getLocationY());
 }
}

Voila! You just made your first Java serialization/deserialization tutorial. I hope you enjoyed my post and thank you for reading my tutorials. Please comment below if you have some questions regarding this post.
Have a nice day!

Wednesday, December 4, 2013

Protect Your Documents - Use Jasypt For Java

Do you have that one family member who always messes up with your documents on your computer? Well, if you're looking for a library in Java, you can give a try to Jasypt. I always use this library in every of my projects because not only it is super easy to implement and use but many of Developers are now using this wonderful library. Give it a try! Download it now!

I use this library mostly when I make apps that need an internet connection. Because we have no idea that someone is intercepting our communication and stealing our data. This is what we called Man-in-the-middle attack. You can google about that type of attack over the network.
But with the help of Jasypt, the chance of being MiM the network gets slimmer. Just take this example, please make a new project with new class and copy paste this code:

public class Main {
 public static void main(String arg){
  BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
  textEncryptor.setPassword("MySecretPasswordOnlyTrustedFriendsKnow");
  String myEncryptedText = textEncryptor.encrypt("MySecretMessageToMyFriends");
 }
}

And on the machine that receive the message, he needs to decrypt the message using the same password used to encrypt it.

textEncryptor.setPassword("MySecretPasswordOnlyTrustedFriendsKnow");
textEncryptor.decrypt(myEncryptedText);
Just toy around to that easy-to-use security library and in no time you will get the hang of it.
Having a good security to your application is vital.
Thanks for reading!

How To Use Apache Log4j In Your Java Application

Hi guys, being able to log what your applications behave since its first released or under development is one of the great things you need to consider being a Developer. So in this tutorial, I'm going to show you the basic on how to install Apache Log4j to your own java application.

First, download the library and create a new project in Eclipse then add the log4j to your classpath.
Make a new class by right clicking the src folder and select New > Class and name your class an appropriate name.

In log4j, there are a lot of levels, namely:

  1. DEBUG
  2. ERROR
  3. FATAL
  4. INFO
  5. TRACE
  6. WARN
Now copy and paste this code:

import org.apache.log4j.Logger;
public class MyLogger{
   private static Logger log = Logger.getLogger(LogClass.class);
   public static void main(String[] args) {
      log.trace("Trace Message..");
      log.debug("Debug Message..");
      log.info("Info Message..");
      log.warn("Warn Message..");
      log.error("Error Message..");
      log.fatal("Fatal Message..");
   }
}
Output:
Debug Message..
Info Message..
Warn Message..
Error Message..
Fatal Message..
Depending on how crucial the application is executing you will use the right level for your application.
Say for example, your application is trying to write to a file but it there's not enough permission, you can then log it and be like:
ERROR: Unable to write to a file: 'C:\updates.json'
That's it! I hope you learned something new about this wonderful library! Thanks for reading guys. If you have questions then feel free to contact me or post your problems here regarding this library.

How To Use Ini4j To Your Java Application

You can use ini4j to your project to make some changes on your application settings even without recompiling it. The ini4j tutorial can make you up and running using this library as well.

The first thing we want to do is to download the library and integrate it with our favorite IDE. I recommend Eclipse IDE as you can easily add up additional libraries on your project without getting any trouble.


Simple Windows .ini file

This will be our very simple .ini file we are using throughout this tutorial. Please copy/paste this to your empty config/settings.ini file.

[main]
window-color = 00ffff
splash = true
[others]
version = 0.1
developer = Jim

Reading from .ini file


import java.io.File;
import java.io.IOException;

import org.ini4j.InvalidFileFormatException;
import org.ini4j.Wini;


public class Main {
 
 public static void main(String args[]){
  try{
   Wini ini;
   /* Load the ini file. */
   ini = new Wini(new File("config/settings.ini"));
   /* Extract the window color value.*/
   int windowColor = ini.get("main", "window-color", int.class);
   /* Extract the splash screen status. */
   boolean splashScreen = ini.get("main", "splash", boolean.class);
   
   /* Show to user the output. */
   System.out.println("Your default window color is: " + windowColor);
   if(splashScreen){
    System.out.println("You have your splash screen activated.");
   }else{
    System.out.println("You have your splash disabled.");
   }
  } catch (InvalidFileFormatException e) {
   System.out.println("Invalid file format.");
  } catch (IOException e) {
   System.out.println("Problem reading file.");
  }
 }
The code above is pretty self explanatory and you could easly guess what the line of code does just by looking at it. We just basically read the settings.ini file from config directory and parse the windowColor value and splashScreen status to show to user.

Writing to windows .ini file


import java.io.File;
import java.io.IOException;

import org.ini4j.InvalidFileFormatException;
import org.ini4j.Wini;


public class Main {
 
 public static void main(String args[]){
 Wini ini;
 try {
  ini = new Wini(new File("config/settings.ini"));
  ini.put("main", "window-color", 000000);
  ini.put("main", "splash", false);
  ini.store();
 } catch (InvalidFileFormatException e) {
  System.out.println("Invalid file format.");
 } catch (IOException e) {
  System.out.println("Problem reading file.");
 }
  
 }
The code above couldn't get any simpler. We are basically overwriting the value of window-color and splash in main section. Then we invoke the Wini.store() method to update our ini file.

This simple tutorial can make you up and running using this wonderful library. Thank you for reading, have a nice day everybody!

Monday, December 2, 2013

How To Send An Email - Java

Hi guys! I found this snippet a while ago that really works if you want your application to send an email to an email address. You can use this as a feature on your application. Say for example, you want your users to send a bug report or suggestions to your application, then this code might come in handy for you.

Please see the below code:


import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
public class aa {
 public static void main(String[] args) {
  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("EmailAddressHere","PasswordHere");
    }
   });
 
  try {
 
   Message message = new MimeMessage(session);
   message.setFrom(new InternetAddress("MyEmail@gmail.com"));
   message.setRecipients(Message.RecipientType.TO,
     InternetAddress.parse("friend@gmail.com"));
   message.setSubject("Testing Subject");
   message.setText("Dear Mail Crawler," +
     "\n\n No spam to my email, please!");
 
   Transport.send(message);
 
   System.out.println("Done");
 
  } catch (MessagingException e) {
   throw new RuntimeException(e);
  }
 }
}
I guess that this code is pretty much explanatory yourselves. If you could, all you have to do is to change the username and password for you to be logged in.
Then change the "From", "To", "Subject" and finally the "Body" of the email you are constructing.
This can be a really cool feature anyway. If you have trouble adding this snippet on your current project, please feel free to comment here and I will do my best to fix it. Thanks for reading!

Create Your Own Proxy Checker In Java

Being able to check whether a proxy is alive or not is a good advantage if you want speed you're ever wanting. So in this post I'm gonna show you how you would be able to create one in Java.

Create a project in Eclipse (I'm pretty sure you already know this, if not, please proceed to my other posts regarding to this matter) and paste this code:


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
 


public class ClassicPC {
 
 public static List check(List proxies){  
  List wProxies = new ArrayList();
  for(JProxy p : proxies){
   try{
    System.out.println("Checking " + p.getHost() + ":" + p.getPort() + " ...");
    String h = p.getHost(); // "122.192.166.70"; 
    int port = Integer.parseInt(p.getPort()); 
    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(h, port));
    URL url = new URL("http://www.google.com");
    URLConnection http = url.openConnection(proxy);
    http.connect(); 
    System.out.println("SUCCESS!");
    wProxies.add(new JProxy(h, String.valueOf(port))); 
   }catch(Exception e){
    System.out.println("ERROR: " + e.getMessage());
   } 
  }   
  return wProxies;
 }

 public static void main(String args[]) throws IOException{
  List proxies = readList();
  List wProxies = check(proxies);
  System.out.println("WORKING PROXIES:");
  BufferedWriter writer = new BufferedWriter(
    new FileWriter(new File("C:\\wProxies.txt")));
  for(JProxy p : wProxies){
   writer.write(p.getHost() + ":" + p.getPort());
   writer.write(System.getProperty("line.separator"));
  }
  writer.close();
 }
 
 public static List readList(){
  try{
   File f = new File("C:\\tocheck.txt");
   List proxies = new ArrayList();
   BufferedReader reader = new BufferedReader(
     new FileReader(f));
   String proxy = null;
   while( (proxy = reader.readLine()) != null){ 
    //System.out.println("Proxy: " + proxy);
    proxies.add(new JProxy(proxy.split(":")[0]
                          ,proxy.split(":")[1]));
   }
   reader.close();
   return proxies;
  }catch(Exception e){
   e.printStackTrace();
  }
  return null;
 }
 
 static class JProxy{
  public JProxy(String h, String p){
   host = h;
   port = p;
  }
  private String host, port;
  public String getHost() { return host; }
  public String getPort() { return port; }
 }
}

Let's start off with the main function:
We have create proxies instance to read a list of proxies inside a text file called tocheck.txt.
Then we have create a wProxies instance to get all the working proxies when the check() method arrives.

So what's the check method has and how will it find out which proxies are alive?
What it does is that, it first loops thru the proxies we have just get from the text file and fetched to get the ip and the port. Then created a Proxy instance and a URL instance to open a connection to google.com with the proxy specified. If it successfully opens the Google.com website then the proxy is said to be alive and being populated to the wProxies. Right after all the proxies to check is finished it will then be returned back to the calling variable with only proxies alive! Finally, the program will create a new file called wProxies.txt with all the alive proxies.

If you have any questions, please comment here. Thanks for reading my posts.

Java Thread - Producer and Consumer

Making a multi-tasking application in Java has never been an easy task before. That's why they have updated the Thread framework since Java 7. Today, I will show you guys how you can achieve a multi-tasking application which is synchronized with each other called the Producer/Consumer.

Think of a Producer as a thread that supplies a stock of food to all of its clients called Consumer. It produces foods only if the Consumer needs it. Otherwise, it will not produce. The Consumer then consumes what the Producer has produce then notify it that it needs to produce.

Please examine the following codes:

package conc;

import java.util.concurrent.ArrayBlockingQueue;

public class BlockingQueue {

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

     java.util.concurrent.BlockingQueue queue = new ArrayBlockingQueue(100);

        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);

        new Thread(producer).start();
        new Thread(consumer).start();

        Thread.sleep(4000);
    }
}
===============================
package conc;

public class Consumer implements Runnable{

    java.util.concurrent.BlockingQueue queue = null;

    public Consumer(java.util.concurrent.BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
         while(true){
          System.out.println("drugs taking out..");
          System.out.println("TAKE: " + queue.take());
         }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
==============================
package conc;

public class Producer implements Runnable{

 java.util.concurrent.BlockingQueue queue = null;

    public Producer(java.util.concurrent.BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
         while(true){
          System.out.println("loading drugs..");
          queue.put("drugs loaded!"); 
          Thread.sleep(2000);
         }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
The main function makes an instance of java.util.concurrent.BlockingQueue<Stringwhich is used as a medium or buffer for the two threads. It also creates the two threads - Producer and Consumer threads and then fire it up using their respective start method. If you will try to analyze the two threads' overriden method, there is an infinite loop with two second interval, this is where the fun begins. The Producer only need to make a call queue's "put" method while the Consumer thread only needs to call the queues' "get" method and the new framework does all the heaving coding to make it synchronized for you. From the source code above, you can then make serious applications that needs a multitasking features without getting into trouble from thread coding. Have fun coding and thank you for reading my post! Till next time! :)

How To Use JFreeChart In Java

Do you want to visualize your data from your database in Java? Well some guy started to develop a FREE and very good chart library in Java. The good thing about this is that is it free and open source, so anytime you want to change something you want to meet your needs is just like a piece of cake.

First, you have to download the library itself JFreeChart download note it is being hosted on SourceForge.
If you're using Eclipse IDE this my post might come in handy to adding library to your classpath.

Create a new project and new class then copy/paste this code which I will be explaining later:


import javax.swing.JFrame;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;


public class HelloChart extends JFrame {
 
 private static final long serialVersionUID = 1L;

 public HelloChart(String applicationTitle, String chartTitle) {
        super(applicationTitle);
        PieDataset dataset = createDataset();
        JFreeChart chart = createChart(dataset, chartTitle);
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(chartPanel);

    }
    
    private  PieDataset createDataset() {
        DefaultPieDataset result = new DefaultPieDataset();
        result.setValue("McDonalds", 40);
        result.setValue("Jolibee", 11);
        result.setValue("Subway", 9);
        return result;
        
    }

    private JFreeChart createChart(PieDataset dataset, String title) {
        JFreeChart chart = ChartFactory.createPieChart3D(title, dataset, true, true, false);
        PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setStartAngle(290);
        plot.setDirection(Rotation.CLOCKWISE);
        plot.setForegroundAlpha(0.5f);
        return chart;
    }
    public static void main(String args){
     HelloChart demo = new HelloChart("Comparison", "Which fast food are the best?");
        demo.pack();
        demo.setVisible(true);
 }
   
} 

Basically, what we need to render our chart is to make a dataset. In this example, we want created a DefaultPieDataSet and add some values in it. Then we make an instance of JFreeChart and customize it along with the dataset we have just created. Finally, we give it to our JFrame's  content pane for the user to see it. Here are one of the examples when you downloaded the library with demo file.

Try to explore the whole demo application and get helped in its forum and some tutorials. Thank you for reading my post!

How To Add Library In Eclipse

Last week, a friend of mine decided to learn programming and I told him to start off programming in Java. He went level up in just a couple of weeks and then he eventually asked me to add library in Eclipse (the IDE he choosed to work with)

So now I'm gonna share you all the basic things you need to do in order to have your library "linked" to your project.

Download Eclipse IDE


First, download Eclipse IDE I prefer Helios version as I'm already get used to it since back when I was just learning in my college.

Fire it up


After you finished downloading Eclipse, you need to fire it up, there's no installation needed!
Note: First, you have to choose the working directory for your projects. Just click OK.


Create a Project

Now that you have your Eclipse up and running, you will be needing to create your own project in it.
To create, just click File > New > Java Project.
Project Name: Use a suitable name for the project name.
The rest, leave everything as is.
Then click Finish.
You will see your project on the project explorer:


Adding External Library

Now that you have your Java project, we need to add our library downloaded from the internet.
A very good example is Google Guava. You have to download it first before adding it to your classpath.
Now right click on your project then choose Properties. Click Java Build Path, on the tab click Libraries, finally click the button Add External Jars.. and locate the library you just downloaded. See the below picture:

Finally, click on OK. Voila! You can now use the libraries classes all you want to your project.
Thank you for reading my post! :)

Play Media Files With VLCJ in Java

Hello, today I will teach you how to work with your media files like video or music formats.
There is JMF in Java but it seems to be outdated and very old so some people who works on an open source projects started to develop and port the famous VLC library from C++ called vlcj.
It is currently being hosted on Google Code and they're updating it from time to time.

I will show you a quick example on how to use this wonderful library. Just copy and paste this code to your favorite IDE like Eclipse. Note that you should first need to download the library and add it to your project classpath.


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;

import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;

    public class VideoExample {

        private final EmbeddedMediaPlayerComponent mediaPlayerComponent;

        public static void main(final String[] args) {
         NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files\\VideoLAN\\VLC");
         Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new VideoExample(args);
                }
            });
        }

        private VideoExample(String[] args) {
            JFrame frame = new JFrame("vlcj Tutorial");

            mediaPlayerComponent = new EmbeddedMediaPlayerComponent();

            frame.setContentPane(mediaPlayerComponent);

            frame.setLocation(100, 100);
            frame.setSize(500, 500);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);

            mediaPlayerComponent.getMediaPlayer().playMedia("D:\\video.avi");
            
        }
    }
Output:

Voila! With just a few lines of code, you may have your own media player like this. You can now start to explore more tutorials on Google and start to read the library's documentation online of offline to develop your own program that suite to your own needs.
Thanks for reading!