Archive for the 'Java' Category



26
Nov
07

Struts flow diagram

struts-flow.gif

Advertisements
22
Nov
07

When hibernate and struts working together, i distrated

I was studied hibernate, i got the point. And now i want to build a web application using hibernate and collaborating it with Struts. Struts framework is new for me so i don’t understand and really don’t know where i should start to working with it. Xml file configuration and mapping configuration that needed by hibernate are done. I’m stuck. 👿

22
Nov
07

Multithreading is working out on RMI issue

Check out this post! It’s RMI stuff.

https://n3tg33ks.wordpress.com/2007/11/18/ketemu-masalah-lagi-di-rmi/

actually i juz want to say that it’s work, the issue has been solved by multithreading 😈

server.png

Those 3 running server are use their own thread and image below

result.png

is result of two methods that placed on different class.

20
Nov
07

Introduction to Java RMI

Overview

Remote Method Invocation (RMI) facilitates object function calls between Java Virtual Machines (JVMs). JVMs can be located on separate computers – yet one JVM can invoke methods belonging to an object stored in another JVM. Methods can even pass objects that a foreign virtual machine has never encountered before, allowing dynamic loading of new classes as required. This is a powerful feature!

Consider the follow scenario :

  • Developer A writes a service that performs some useful function. He regularly updates this service, adding new features and improving existing ones.
  • Developer B wishes to use the service provided by Developer A. However, it’s inconvenient for A to supply B with an update every time.

Java RMI provides a very easy solution! Since RMI can dynamically load new classes, Developer B can let RMI handle updates automatically for him. Developer A places the new classes in a web directory, where RMI can fetch the new updates as they are required.

rmidiagr.gif (6734 bytes)
Figure 1 – Connections made when client uses RMI

Figure 1 shows the connections made by the client when using RMI. Firstly, the client must contact an RMI registry, and request the name of the service. Developer B won’t know the exact location of the RMI service, but he knows enough to contact Developer A’s registry. This will point him in the direction of the service he wants to call..

Developer A’s service changes regularly, so Developer B doesn’t have a copy of the class. Not to worry, because the client automatically fetches the new subclass from a webserver where the two developers share classes. The new class is loaded into memory, and the client is ready to use the new class. This happens transparently for Developer B – no extra code need to be written to fetch the class.

Writing RMI services

Writing your own RMI services can be a little difficult at first, so we’ll start off with an example which isn’t too ambitious. We’ll create a service that can calculate the square of a number, and the power of two numbers (238 for example). Due to the large size of the numbers, we’ll use the java.math.BigInteger class for returning values rather than an integer or a long.

Writing an interface

The first thing we need to do is to agree upon an interface, An interface is a description of the methods we will allow remote clients to invoke. Let’s consider exactly what we’ll need.

  1. A method that accepts as a parameter an integer, squares it, and returns a BigInteger
    public BigInteger square ( int number_to_square );
  2. A method that accepts as a parameter two integers, calculates their power, and returns a BigInteger
    public BigInteger power ( int num1, int num2 );

Once we’ve decided on the methods that will compose our service, we have to create a Java interface. An interface is a method which contains abstract methods; these methods must be implemented by another class. Here’s the source code for our service that calculates powers.

import java.math.BigInteger;
import java.rmi.*;

//
// PowerService Interface
//
// Interface for a RMI service that calculates powers
//
public interface PowerService extends java.rmi.Remote
{
	// Calculate the square of a number
	public BigInteger square ( int number )
		throws RemoteException;

	// Calculate the power of a number
	public BigInteger power  ( int num1, int num2)
		throws RemoteException;
}

Our interface extends java.rmi.Remote, which indicates that this is a remote service. We provide method definitions for our two methods (square and power), and the interface is complete. The next step is to implement the interface, and provide methods for the square and power functions.

Implementing the interface

Implementing the interface is a little more tricky – we actually have to write the square and power methods! Don’t worry if you’re not sure how to calculate squares and powers, this isn’t a math lesson. The real code we need to be concerned about is the constructor and main method.

We have to declare a default constructor, even when we don’t have any initialization code for our service. This is because our default constructor can throw a java.rmi.RemoteException, from its parent constructor in UnicastRemoteObject. Sound confusing? Don’t worry, because our constructor is extremely simple.

public PowerServiceServer () throws RemoteException
{
super();
}

Our implementation of the service also needs to have a main method. The main method will be responsible for creating an instance of our PowerServiceServer, and registering (or binding) the service with the RMI Registry. Our main method will also assign a security manager to the JVM, to prevent any nasty surprises from remotely loaded classes. In this case, a security manager isn’t really needed, but in more complex systems where untrusted clients will be using the service, it is critical.

public static void main ( String args[] ) throws Exception
{
// Assign a security manager, in the event that dynamic
// classes are loaded

if (System.getSecurityManager() == null)
System.setSecurityManager ( new RMISecurityManager() );

// Create an instance of our power service server …
PowerServiceServer svr = new PowerServiceServer();

// … and bind it with the RMI Registry
Naming.bind (“PowerService”, svr);

System.out.println (“Service bound….”);
}

Once the square and power methods are added, our server is complete. Here’s the full source code for the PowerServiceServer.

import java.math.*;
import java.rmi.*;
import java.rmi.server.*;

//
// PowerServiceServer
//
// Server for a RMI service that calculates powers
//
public class PowerServiceServer extends UnicastRemoteObject
implements PowerService
{
    public PowerServiceServer () throws RemoteException
    {
        super();
    }

    // Calculate the square of a number
    public BigInteger square ( int number )
    throws RemoteException
    {
        String numrep = String.valueOf(number);
        BigInteger bi = new BigInteger (numrep);

        // Square the number
        bi.multiply(bi);

        return (bi);
    }

    // Calculate the power of a number
    public BigInteger power ( int num1, int num2)
    throws RemoteException
    {
        String numrep = String.valueOf(num1);
        BigInteger bi = new BigInteger (numrep);

	bi = bi.pow(num2);
	return bi;
    }

    public static void main ( String args[] ) throws Exception
    {
        // Assign a security manager, in the event that dynamic
	// classes are loaded
        if (System.getSecurityManager() == null)
            System.setSecurityManager ( new RMISecurityManager() );

        // Create an instance of our power service server ...
        PowerServiceServer svr = new PowerServiceServer();

        // ... and bind it with the RMI Registry
        Naming.bind ("PowerService", svr);

        System.out.println ("Service bound....");
    }
}

Writing a RMI client

What good is a service, if you don’t write a client that uses it? Writing clients is the easy part – all a client has to do is call the registry to obtain a reference to the remote object, and call its methods. All the underlying network communication is hidden from view, which makes RMI clients simple.

Our client must first assign a security manager, and then obtain a reference to the service. Note that the client receives an instance of the interface we defined earlier, and not the actual implementation. Some behind-the-scenes work is going on, but this is completely transparent to the client.

// Assign security manager
if (System.getSecurityManager() == null)
{
System.setSecurityManager (new RMISecurityManager());
}

// Call registry for PowerService
PowerService service = (PowerService) Naming.lookup
(“rmi://” + args[0] + “/PowerService”);

To identify a service, we specify an RMI URL. The URL contains the hostname on which the service is located, and the logical name of the service. This returns a PowerService instance, which can then be used just like a local object reference. We can call the methods just as if we’d created an instance of the remote PowerServiceServer ourselves.

// Call remote method
System.out.println (“Answer : ” + service.square(value));

// Call remote method
System.out.println (“Answer : ” + service.power(value,power));

Writing RMI clients is the easiest part of building distributed services. In fact, there’s more code for the user interface menu in the client than there is for the RMI components! To keep things simple, there’s no data validation, so be careful when entering numbers. Here’s the full source code for the RMI client.

import java.rmi.*;
import java.rmi.Naming;
import java.io.*;

//
//
// PowerServiceClient
//
//
public class PowerServiceClient
{
	public static void main(String args[]) throws Exception
	{
		// Check for hostname argument
		if (args.length != 1)
		{
			System.out.println
			("Syntax - PowerServiceClient host");
			System.exit(1);
		}

		// Assign security manager
		if (System.getSecurityManager() == null)
		{
			System.setSecurityManager
			(new RMISecurityManager());
		}

		// Call registry for PowerService
		PowerService service = (PowerService) Naming.lookup
			("rmi://" + args[0] + "/PowerService");

		DataInputStream din = new
			DataInputStream (System.in);

		for (;;)
		{
			System.out.println
			  ("1 - Calculate square");
			System.out.println
			  ("2 - Calculate power");
			System.out.println
			  ("3 - Exit"); System.out.println();
			System.out.print ("Choice : ");

			String line = din.readLine();
			Integer choice = new Integer(line);

			int value = choice.intValue();

			switch (value)
			{
			case 1:
			  System.out.print ("Number : ");
			  line = din.readLine();System.out.println();
			  choice = new Integer (line);
			  value  = choice.intValue();

			  // Call remote method
			  System.out.println
			  ("Answer : " + service.square(value));

			  break;
			case 2:
			  System.out.print ("Number : ");
			  line = din.readLine();
			  choice = new Integer (line);
			  value  = choice.intValue();

			  System.out.print ("Power  : ");
			  line = din.readLine();
			  choice = new Integer (line);
			  int power = choice.intValue();

			  // Call remote method
			  System.out.println
		("Answer : " + service.power(value, power));

			  break;
			case 3:
			  System.exit(0);
			default :
			  System.out.println ("Invalid option");
			break;
			}
		}
	}

}

Running the client and server

Our example was extremely simple. More complex systems, however, might contain interfaces that change, or whose implementation changes. To run this article’s examples, both the client and server will have a copy of the classfiles, but more advanced systems might share the code of the server on a webserver, for downloading as required. If your systems do this, don’t forget to set the system property java.rmi.server.codebase to the webserver directory in which your classes are stored!

You can download all the source and class files together as a single ZIP file. Unpack the files into a directory, and then perform the following steps.

  1. Start the rmiregistry

    To start the registry, Windows users should do the following (assuming that your java\bin directory is in the current path):-

    start rmiregistry

    To start the registry, Unix users should do the following:-

    rmiregistry &

  2. Compile the server

    Compile the server, and use the rmic tool to create stub files.

  3. Start the server

    From the directory in which the classes are located, type the following:-

    java PowerServiceServer
  4. Start the client

    You can run the client locally, or from a different machine. In either case, you’ll need to specify the hostname of the machine where you are running the server. If you’re running it locally, use localhost as the hostname.

    java PowerServiceClient localhost

TIP – If you running the client or server with JDK1.2, then you’ll need to change the security settings. You’ll need to specify a security policy file (a sample is included with the source code and classes) when you run the client and server.The following changes should be made when running the serverjava -Djava.security.policy=java.policy PowerServiceServer

The following changes should be made when running the client

java -Djava.security.policy=java.policy PowerServiceClient localhost

Summary

Java RMI is a useful mechanism for invoking methods of remote objects. Java RMI allows one Java Virtual Machine to invoke methods of another, and to share any Java object type, even if client or server has never come across that object type before.

ps: source http://www.javacoffeebreak.com/articles/javarmi/javarmi.html

20
Nov
07

JavaME is *not* dead!

It’s growing up. Sheesh. Some folks are far too eager to misinterpret statements and put words in my mouth. The early versions of JavaME were very simple and limited, a direct reflection of the fact that early phones themselves were simple and limited: we had to work with what we had. But as time has passed, and cell phones have become more powerful and capable, JavaME has grown up too. Cell phones are becoming the new desktop. We’ve been saying this for years. Over time, it’s pretty clear that JavaME and JavaSE will converge and become largely indistinguishable. It goes both ways: JavaSE has a much more sophisticated graphics API, and JavaME is growing there. JavaME has a location API (GPS) and one could easily make the argument that it should be available in JavaSE.

This is a process of evolution, not “out with the old, in with the new”.

JavaFX mobile contains within it an implementation of JavaME. It is not some weird new beast.

ps: source ➡ http://blogs.sun.com/jag/

18
Nov
07

Ketemu masalah lagi di RMI

Ada 3 tabel dalam database ➡ berita, kategori dan anggota. Tiap tabel saya buatin interface sendiri untuk yang nantinya juga akan di implementasikan ke tiga class berbeda, berita, anggota dan kategori. Implementasi dari ketiga interface itu adalah method-method yang digunakan untuk berinteraksi dengan database, misalnya implementasi dari interface berita adalah method-method yang digunakan untuk mengambil, menyimpan dan menghapus data khusus dari tabel berita. Begitu juga yang lainnya.

Karena ada tiga interface berbeda, berarti saya juga harus buatin rebind dengan nama yang berbeda. Misalnya untuk anggota saya rebind dengan nama Anggota


try {
	AnggotaInterface anggota = new AnggotaController();
	Naming.rebind("Anggota", anggota);
} catch(Exception ex) {
	ex.printStackTrace();
}

untuk berita saya rebind dengan nama Berita


try {
	BeritaInterface berita = new BeritaController();
	Naming.rebind("Berita", berita);
} catch(Exception ex) {
	ex.printStackTrace();
}

begitu pula untuk kategori. Kemudian saya pikir bagaimana untuk menjalankan ketiganya bersamaan? Pisahkan ketiga rebinding itu dalam tiga class yang masing mengimplementasikan Runnable, anda tau maksud saya 😈 Setelah itu buatkan satu class master, dimana dari class itu akan dibuatkan thread untuk masing” object dari ketiga class sebelumnya.


package server;

/**
 *
 * @author JollkY
 */
public class MasterServer {

    /** Creates a new instance of MasterServer */
    public MasterServer() {
        // buatkan object masing""
        BeritaServer berita = new BeritaServer();
        AnggotaServer anggota = new AnggotaServer();
        KategoriServer kategori = new KategoriServer();

        // buatkan thread masing""
        Thread threadBerita = new Thread(berita);
        Thread threadAnggota = new Thread(anggota);
        Thread threadKategori = new Thread(kategori);

        // jalankan thread" tersebut
        threadBerita.start();
        threadAnggota.start();
        threadKategori.start();
    }    

}

Sebenarnya, saya belum coba apakah ini berhasil atau tidak 😯 :mrgreen: ini kan baru idenya aja tapi sudah ditulis dan belum di eksekusi, saya was” soalnya 😐

Jalan gak yak 👿

15
Nov
07

Java-Hibernate Codes [technical]

2 Hal yang saya suka menggunakan framework hibernate, Pertama-saya gak perlu bikin database secara langsung, cukup bikin designnya aje pake DBDesigner ➡ bikin class untuk modelnya/setter-getter ➡ bikin file hibernate.cfg.xml yang bakalan ngasih tahu apa aja properties dari app itu skalian ama keterangan koneksi ke database dan nama databasenya supaya databasenya langsung dibuatin secara otomatiiiis 😈 and xml untuk tiap table supaya table-table-nya juga ikut dibuatin. Jadi waktu yang biasa dipake untuk bikin database, bisa dialihkan untuk boker yang laen :mrgreen: . Kedua-codingnya relatif lebih dikit, dan mudah untuk maintainance.

OK dah saya mulai dengan buat hibernate.cfg.xml dulu:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- DB Connection Setting -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/mybook</property>
        <property name="connection.username">dbuser</property>
        <property name="connection.password">dbpass</property>

        <!-- SQL Dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- JDBC Connection pool -->
        <property name="connection.pool_size">1</property>

        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.timeout">1800</property>
        <property name="hibernate.c3p0.max_statements">50</property>

        <!-- Enable hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

	<!-- Show the sql query when it executed -->
	<property name="show_sql">true</property>

        <property name="hbm2ddl.auto">update</property>

        <mapping resource="model/Buku.hbm.xml"/>
        <mapping resource="model/Category.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

tahap satu selesai, lanjut ke tahap 2 ➡ skarang saya bikin file xml untuk tiap table. Yang pertama dan terakhir 😯 table Buku [ ex]:


<?xml version="1.0" encoding="UTF-8"?>

<!--
    Document   : Buku.hbm.xml
    Created on : September 3, 2007, 11:29 PM
    Author     : JollkY
    Description:
        Purpose of the document follows.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="model.Buku" table="BUKU">
        <id name="id" column="ID" type="java.lang.Long">
            <generator class="native"/>
        </id>
        <property name="title" column="TITLE" type="java.lang.String" length="100"/>
        <property name="page" column="PAGE" type="java.lang.Integer" length="5"/>
        <property name="publisher" column="PUBLISHER" type="java.lang.String" length="100"/>
        <property name="writer" column="WRITER" type="java.lang.String" length="100"/>
    </class>
</hibernate-mapping>

Perhatikan code di atas, untuk name=”model.Buku” menyatakan <namaPaket>.<namaClass> sedangkan table=”BUKU” merupakan name tabelnya. Kemudian untuk name=”id” menyatakan nama variable untuk id pada class Buku dalam paket model. Sedangkan column=”TITLE” akan menjadi salah satu nama kolom saat table BUKU diciptakan.

tahap 3 ➡ bikin class model untuk table Buku:


package model;

/**

*

* @author JollkY

*/

public class Buku {

private long id;

private String title;

private int page;

private String publisher;

private String writer;

/**

* Creates a new instance of Buku

*/

public Buku() {

}

public long getId() {

return id;

}

public void setId(long id) {

this.id = id;

}

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

public int getPage() {

return page;

}

public void setPage(int page) {

this.page = page;

}

[...bleh...bleh...bleh...]

}

tahap 4 ➡ class yang akan berinteraksi dengan DB:


package dao;

import java.util.ArrayList;
import java.util.List;
import model.Buku;
import org.hibernate.Session;

/**
 *
 * @author JollkY
 */
public class BukuDAO {

    /** Creates a new instance of BukuDAO */
    public BukuDAO() {
    }

    public Buku getBuku(long id, Session session) {
        Buku book = (Buku) session.load(Buku.class, id);
        return book;
    }

    public List getBooks(String publisher, Session session) {
        List listBook = new ArrayList();
        listBook = session.createQuery("SELECT buku FROM Buku buku WHERE buku.publisher= :input").setParameter("input", publisher).list();
        return listBook;
    }

}

satu lagi:


package dao;

import org.hibernate.Session;

/**
 *
 * @author JollkY
 */
public class ObjectDAO {

    /** Creates a new instance of ObjectDAO */
    public ObjectDAO() {
    }

    public void save(Object obj, Session sess) {
        sess.save(obj);
    }
    public void delete(Object obj, Session sess) {
        sess.delete(obj);
    }
    public void update(Object obj, Session sess) {
        sess.update(obj);
    }
 }

tahap 5 ➡ class percobaannya:


package tester;

import dao.BukuDAO;
import dao.ObjectDAO;
import java.util.List;
import model.Buku;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author JollkY
 */
public class tester {

    /** Creates a new instance of tester */
    public tester() {
    }

    public static void main(String[] args) {
        SessionFactory sessFactory = new Configuration().configure().buildSessionFactory();
        Session sess = sessFactory.getCurrentSession();
        sess.beginTransaction();
        BukuDAO dao = new BukuDAO();
//        Buku buku = dao.getBuku(1, sess);
//        System.out.print(buku.getTitle()+" | ");
//        System.out.print(buku.getWriter()+" | ");
//        System.out.print(buku.getPublisher()+" | ");
//        System.out.println(buku.getPage());

        List<Buku> listBuku = (List<Buku>)dao.getBooks("Andi Publisher", sess);
        for(Buku b:listBuku) {
            System.out.print(b.getTitle()+" | ");
            System.out.print(b.getWriter()+" | ");
            System.out.print(b.getPublisher()+" | ");
            System.out.println(b.getPage());
        }

//        Buku book = new Buku();
//        book.setId(3);
//        book.setTitle("Fedora Core 4");
//        book.setWriter("Sto");
//        book.setPublisher("Andi Publisher");
//        book.setPage(240);
//        new ObjectDAO().update(book,sess);
        sess.getTransaction().commit();
    }

}

💡 Maap buru” jadi penjelasannya kurang, nanti deh abis kuliah saya edit lagi nih posting. later budy 😈




December 2018
S S M T W T F
« Feb    
1234567
891011121314
15161718192021
22232425262728
293031  

Top Clicks

  • None

Blog Stats

  • 18,051 hits
Advertisements