Installing Java (Oracle JDK) on Linux Ubuntu

Follow these steps for installing Java (Oracle JDK) on Linux Ubuntu server using terminal.
notes : remove sudo if you are already root user.

First, open the terminal and use SSH if you’re installing on the Remote Machine.
Most of Ubuntu installation come with OpenJDK, if no, skip these 2 step.

1. For show currently installed java on system, type this on terminal :
java -version

2. This command will completely remove OpenJDK/JRE from your system, type this on terminal :
sudo apt-get purge openjdk-\*

3. create “/usr/local/java” directory, type this on terminal :
type : sudo mkdir -p /usr/local/java

4. download Java from Oracle website (url : http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html).
Usually tar.gz format (for example : “jdk-7u79-linux-x64.tar.gz”)

5. copy the downloaded file to folder /usr/local/java

6. Go to folder /usr/local/java/, type this on terminal :
cd /usr/local/java/

7. set the file owner, type this on terminal (replace “filename” with downloaded file) :
sudo chmod a+x “filename”

8. extract file, type this on terminal :
sudo tar xvzf “filename”

9. At this point, you should have an uncompressed binary directory in /usr/local/java for the Java JDK/JRE.
notes : replace “directory name” with your uncompressed binary directory name.

10. Edit the system PATH file /etc/profile and add the following system variables to your system path, type this on terminal :
sudo nano /etc/profile

11. After you open the file with nano, type this at the end of file :
JAVA_HOME=/usr/local/java/”directory name”
PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
export JAVA_HOME
export PATH

12. To finish editing the file, press “ctrl + x” on keyboard

13. for confirm saving the file, press : y

14. for Inform OS for java new installation, type this on terminal :
sudo update-alternatives –install “/usr/bin/java” “java” “/usr/local/java/”directory name”/bin/java” 1

15. Set newly installed java as default java, type this on terminal :
sudo update-alternatives –set java /usr/local/java/”directory name”/bin/java

16. Reload environment variable, type this on terminal :
/etc/profile

17. Check the newly installed java on system, type this on terminal :
java -version

Create Simple TCP / IP Client Application with Java

This some coding sample to creating socket connection in Java. This simple application will be sending message through TCP/IP connection and wait for response from server.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 *
 * @author Erwin
 */
public class SendMessage {

    public static void main(String[] args) {

        try {
            int port = 14000;

            // Create Socket address for configuring socket configuration
            SocketAddress sockaddr = new InetSocketAddress("127.0.0.1", port);

            // Create socket Object
            Socket sock = new Socket();

            // if timeout is reached and no response is received, it will throw socket exception
            int timeoutMs = 2000;   // in milliseconds

            // Initiate socket connection to server
            sock.connect(sockaddr, timeoutMs);
            try {
                
                // Create Buffered Writer object to write String or Byte to socket output stream
                BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
                String command = "Start Module";
                wr.write(command);
                System.out.println("Send String : "+command);
                
                // Flushing the writer
                wr.flush();

            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
                String str;
                while ((str = rd.readLine()) != null) {
                    System.out.println(str);
                }
                rd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            // Close socket connection after finish receiving a response
            sock.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Hope this will be helpfull. Regards, Erwin Lin

How to create simple mail client with Java

On this article, I will post some code for making simple mail client application with java to sending e-mail via gmail mail server.

Here some coding example that I make :

I use JavaMail API from oracle
http://www.oracle.com/technetwork/java/javamail/index-138643.html

import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SimpleEMailSenderClient {

public static void main(String args[]) {
try {

// Initiate Properties object for configuring the mail client
Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp.gmail.com");
//prop.put("mail.smtp.host", "66.249.93.109");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.port", "465");
prop.put("mail.smtp.socketFactory.port", 465);
prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.put("mail.smtp.socketFactory.fallback", "false");

// Create a new javax.mail.Session object
Session session = Session.getDefaultInstance(prop, new Authenticator() {

// Override method to Authanticate to mail server
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("testmail@gmail.com", "testtest");
}
});

// setDebug method fill with Boolean true that will dump trace log of Session Object to console.
session.setDebug(true);

// Initiate MimeMessage for configuring e-mail detail
MimeMessage Msg = new MimeMessage(session);

// setFrom() method is for filling the "From" field in email.
Msg.setFrom(new InternetAddress("testmail@gmail.com"));

// setRecipient() method is for filling the "to, cc, or bcc" in email. 
// The first parameter value cab be RecipientType.TO, RecipientType.CC, or Recipient Type.BCC
Msg.setRecipient(RecipientType.TO, new InternetAddress("testing@mymaildomain.com"));

// setSubject() method is for filling the "Subject" field in email.
Msg.setSubject("Message Subject");

// setSentDate() method is to inform the recipient when the mail was sent.
Msg.setSentDate(new Date());

// Initiate MimeBodyPart for filling email content
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText("Message Content");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messagePart);
Msg.setContent(multipart);

// Email Sending process
Transport.send(Msg);

// Handle whenever error is occur
} catch (MessagingException e) {
e.printStackTrace();
}
}
}

Hope this post can be helpfull.

Regards,

Erwin Lin

Real Hello World in Java

post pertama tentang bahasa pemrograman favorit gw yaitu Java ^^
simple hello world nih, bisa dibikin di IDE manapun, gw sih biasa ngoding Java slalu pake NetBeans 6, tp skrg lg pengen juga blajar pake Eclipse soalnya kliatannya lebih mudah integrasi dengan berbagai macam application server dan lebih ringan juga. Dulu pake netbeans gara2 sering berkutat di Swing jadi perlu banget pake fasilitas drag n drop nya, klo di eclipse belum nemuin plugin swing drag n drop yang cocok sih :p
eniwey ini kodenya :

/**
* statement ini adalah deklarasi kelas dalam java di mana "HelloWorld" adalah nama kelasnya dan harus sama dengan nama file source nya yang mempunyai ekstensi .java
*/
Public class HelloWorld {

    /**
     * "main" adalah method utama untuk menjalankan sbuah program java
     *  args adalah array parameter yang bertipe string dan bisa dimasukkan saat menjalankan program java.
     */
    Public static void main (String [] args) {

        /**
         * berikut adalah cara pendeklarasian variabel dalam java dimana variabel hello diisi oleh String yang berisi "Hello World".
         */
         String hello = "Hello World";

        /**
         * ini adalah perintah untuk menampilkan tulisan dalam hal ini adalah isi dari variabel hello ke console
         */
         System.out.println(hello);

    }
}