April 2012 Posts

Why Java? Buat Apa Belajar Java?

Banyak kawan gw yang bertanya, apa sih untungnya gw belajar java? Apa sih yang gw dapet dari belajar java? Kira-kira investasi waktu belajar java, menguntungkan apa engga yah?

Coba gw share apa yang gw dapet dari thread programmer java di kaskus, semoga bisa menjawab kegalauan temen-temen gw semua.

why java?

1. Java adalah bahasa pemrograman yang verbose, static dan normalnya cuma ada 1 cara untuk melakukan sesuatu.
Tidak seperti Perl yang TIMTOWTDI (There Is More Than One Way To Do It) sehingga code yang dibikin pakai Java gampang dipahami oleh orang lain yang tidak bikin code itu. Akibatnya code Java bisa dipelihara dengan mudah oleh suatu team.

2. Dukungan terhadap database dan transaksi yang sangat bagus.
Sebagai contoh Java EE dari sejak awal mendukung declarative transaction management. Ini feature penting buat enterprise yang jarang didukung platform lain.

3. Web Java berjalan dalam suatu app server.
App server ini bisa mengatur dan memonitor pemakaian resource hardware dari applikasi Java. Jadi aplikasi Java berjalan dalam suatu lingkungan yang terkelola (managed environment).

4. Language nya kaku, jadi enak buat sesuatu yang besar.
Karena ke-kaku-an ini bisa di-lihat sebagai fondasi. Name spacingnya Java bagus, portabel, enak bikin library codenya. Kekakuan ini biasanya disebut sebagai “Strong and Static typed”. Ini yang membuat compiler bisa membantu pengecekan kode developer. Jadi salah dikit-dikit error. (kalo PHP, ada salah juga gak tahu si developernya )

5. Java Stable dan robust.
Enterprise butuh sesuatu yang stabil dan handal dimana aplikasi-nya bisa jalan bertahun-tahun.

6. Scalable.
Aplikasi Java dapat dengan mudah di-scale horizontal maupun vertical. Ini sangat penting apabila bisnis yang super sibuk ingin menambah resource mesin ke apps yang sudah jalan. Dan di Java horizontal-vertical scalabity memang benar-benar mudah.

7. Open and Liberal.
Ini sangat penting apabila ada masalah dengan bahasa pemrograman, kita bisa tau dimana permasalahannya dan buka source code-nya, terus kita benerin sendiri. Ya memang gampang sih kalau ada masalah kita bisa telpon vendor-nya. Tapi dalam situasi kritis kadang kita perlu buka dan oprek sendiri. Sedangkan bahasa2 tertutup seperti VB dan Delphi hal seperti itu sangat menyulitkan ketika ada masalah dengan bahasa-nya. Itu makanya di Java ada banyak framework2, karena semua-nya terbuka.

sumber : http://www.kaskus.us/showthread.php?t=10402662

Mungkin ada kawan-kawan gw yang lain yang bersedia untuk menambahkan?

Google+

Executing EJB3 Using Glassfish 3 AppClient

On my last EJB3 tutorial, im still using the old fashioned way of EJB3. Still importing lots of jars, which is very dangerous due to the fact that sometimes i forgot which jar i need to include.

That’s why now im trying to use one of Glassfish’s feature application, appclient. It can bundle all the libraries and dependencies your EJB client needed, so it save your time from including various Glassfish’s jars to your project.

Lets start with a very simple ejb interface class,

package com.edw.facade;

public interface ConnectionFacadeRemote {
    String sayHello(String string);
    int sayAge(int age);
}

And a simple main class,

package com.edw.main;

import com.edw.facade.ConnectionFacadeRemote;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.apache.log4j.Logger;

public class Main {

    private Logger logger = Logger.getLogger(Main.class);
    
    private void connect() {
        try{
            Properties props = new Properties();
            props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");
            props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
            props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
            
            InitialContext ctx = new InitialContext();
            ConnectionFacadeRemote connectionFacadeRemote = (ConnectionFacadeRemote) ctx.lookup("com.edw.facade.ConnectionFacadeRemote");
            logger.debug(connectionFacadeRemote.sayHello("edwin ")); 
            logger.debug("my age is " + connectionFacadeRemote.sayAge(12) + " years");
        }catch(Exception ex){
            logger.error(ex,ex);
        }
    }

    public static void main(String[] args) {
        Main tejbc = new Main();
        tejbc.connect();
    }
}

After you create all classes needed, you have to build your application into .jar.
Next is to pull all the jar needed for this EJB client application to run smoothly. First go to your Server glassfish’s bin folder located in your Server glassfish installation folder, in my PC it would be (C:\Program Files\glassfish-3.0.1\glassfish\bin). And execute the package-appclient command.

C:\Program Files\glassfish-3.0.1\glassfish\bin>package-appclient
Creating C:\Program Files\glassfish-3.0.1\glassfish\lib\appclient.jar

It would create a jar file, appclient.jar, which located in your glassfish lib installation folder.

Next is copy your appclient.jar into your client computers. Extract it, and execute appclient command. The appclient format would be, appclient -jar .

C:\Users\edw\Documents\appclient\appclient\glassfish\bin>appclient -jar "C:\Users\edw\Documents\NetBeansProjects\TestEJBClient\dist\TestEJBClient.jar"
Apr 19, 2012 6:28:03 PM com.sun.enterprise.transaction.JavaEETransactionManagerSimplified initDelegates
INFO: Using com.sun.enterprise.transaction.jts.JavaEETransactionManagerJTSDelegate as the delegate
2012-04-19 18:28:10,067 [Main] DEBUG com.edw.main.Main:22 - hello edwin
2012-04-19 18:28:10,072 [Main] DEBUG com.edw.main.Main:23 - my age is 24 years

You can see the server side’s source code here. And here is my netbeans project structure

Not too hard right ;-)

Google+

Beginning REST Using JBoss RESTEasy

On today’s demo im trying to use RESTEasy to handle multiple REST requests. According to Wikipedia, REST (Representational state transfer) is a style of software architecture for distributed hypermedia systems such as the World Wide Web. While RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS specification. JAX-RS is a new JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol.

On this project, im trying to create 2 different services. 1 service to get all objects, while another one for fetching a single objects. I create 2 different responses type for each service, JSON and XML. Okay, so lets try with 2 simple javabeans.

package com.edw.bean;

import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Student {

    private String name;
    private String address;
    private int age;

    @XmlElement(name="book")
    @XmlElementWrapper(name = "books")
    private List<Book> books;

    public Student() {
    }

    public Student(String name, String address, int age, List<Book> books) {
        this.name = name;
        this.address = address;
        this.age = age;
        this.books = books;
    }

	// other setter getter

    @Override
    public String toString() {
        return "Student{" + "name=" + name + ", address=" + address + ", age=" + age + ", books=" + books + '}';
    }
}
package com.edw.bean;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Book {

    private String title;
    private double price;

    public Book() {
    }

    public Book(String title, double price) {
        this.title = title;
        this.price = price;
    }

	// other setter getter

    @Override
    public String toString() {
        return "Book{" + "title=" + title + ", price=" + price + '}';
    }
}

Now, you need to create a java class to handle all REST services,

package com.edw.rest;

import com.edw.bean.Book;
import com.edw.bean.Student;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/service/student")
public class StudentRest {

    @GET
    @Path("/json")
    @Produces(MediaType.APPLICATION_JSON)
    // path would be http://localhost:8080/YourProject/service/student/json
    public List<Student> getStudentsJSON() {
        return getStudents();
    }

    @GET
    @Path("/xml")
    @Produces(MediaType.APPLICATION_XML)
    // path would be http://localhost:8080/YourProject/service/student/xml
    public List<Student> getStudentsXML() {
        return getStudents();
    }

    @GET
    @Path("/json/{name}")
    @Produces(MediaType.APPLICATION_JSON)
    // path would be http://localhost:8080/YourProject/service/student/json/insertyournamehere
    public Student getStudentJSON(@PathParam("name") String name) {
        return new Student(name, name + " Address", 10, getBooks());
    }

    @GET
    @Path("/xml/{name}")
    @Produces(MediaType.APPLICATION_XML)
    // path would be http://localhost:8080/YourProject/service/student/xml/insertyournamehere
    public Student getStudentXML(@PathParam("name") String name) {
        return new Student(name, name + " Address", 10, getBooks());
    }

    private List<Book> getBooks() {
        List<Book> books = new ArrayList<Book>();
        books.add(new Book("Harry Potter", 100d));
        books.add(new Book("Lord of the Ring", 120d));
        books.add(new Book("Chicken Soup", 20d));
        books.add(new Book("Doraemon", 190d));
        books.add(new Book("Laskar Pelangi", 200d));
        return books;
    }

    private List<Student> getStudents() {
        List<Student> students = new ArrayList<Student>();
        students.add(new Student("Edwin", "Jakarta", 25, getBooks()));
        students.add(new Student("Kamplenk", "Ciledug", 29, getBooks()));
        students.add(new Student("Tebek", "Pamulang", 38, getBooks()));
        students.add(new Student("Syamsu", "Bandung", 60, getBooks()));
        return students;
    }
}

And dont forget to register your service class

package com.edw.config;

import com.edw.rest.StudentRest;
import java.util.Set;
import java.util.HashSet;
import javax.ws.rs.core.Application;

public class ApplicationConfig extends Application {

    private Set<Object> singletons = new HashSet<Object>();
    private Set<Class<?>> empty = new HashSet<Class<?>>();

    public ApplicationConfig() {
        singletons.add(new StudentRest());
    }

    @Override
    public Set<Class<?>> getClasses() {
        return empty;
    }

    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
}

And last, register all in your web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Resteasy</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.edw.config.ApplicationConfig</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>Resteasy</servlet-name>
        <url-pattern>/service/*</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Here are some screenshots,

Have fun with RESTEasy ;)

Google+

Welcome Home, My New XBox360

This is my brother’s birthday present, happy birthday bro. Wish you all the best ;)

My New XBox360

Google+