Tag Archives: Java

I use Glassfish for application server. Here is the EJB:
(interface)

package ejb3.bean;
import javax.ejb.Remote;

@Remote
public interface HelloEjb {
    String printHello(String name);
}

(implementation)

package ejb3.bean;
import javax.ejb.Stateless;

@Stateless( name="HelloEjb")
public class HelloEjbBean implements HelloEjb {
    public HelloEjbBean() {}

    public String printHello(String name) {
        return "Hello bro " + name + " welcome to EJB 3";
    }
}

Package it as JAR or EAR, start Glassfish( GLASSFISH_HOME/bin/asadmin start-domain DOMAIN_NAME ) then use Admin Console (default: http://localhost:4848 ) to deploy the EJB.

To call the EJB from servlet we can directly use @EJB annotations, to get the instance of the EJB. In below sample i send the EJB to JSP page:

package ejb3.servlet;

import ejb3.bean.HelloEjb;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.ejb.EJB;
import java.io.IOException;

public class HelloEjb3Servlet extends HttpServlet {
    @EJB
    private HelloEjb helloEjb;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		execute(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		execute(request, response);
	}

	private void execute(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
        	request.setAttribute("helloEjb", helloEjb);
        	request.setAttribute("printHello", helloEjb.printHello("Djunaedi"));
        	request.getRequestDispatcher("/HelloEjb3.jsp").forward(request, response);
	}
}

To get EJB instance in JSP using @EJB (inside scriplets) isn’t working, i get null instance. So i use JNDI lookup and that’s work:

<%@ page import="ejb3.bean.HelloEjb" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.Context" %>
<html>
<head><title>Hello EJB 3 !</title></head>
<body>
<%!
HelloEjb helloEjb;
%>
<%
try {
Context context = new InitialContext();
helloEjb = (HelloEjb) context.lookup(HelloEjb.class.getName());
}
catch(Exception e) {
// exception code here
}
%>
<p>
Object HelloEjb Directly : <%= helloEjb %><br>
Print Hello : <%= helloEjb.printHello("Ujang") %>

<p>
Object HeloEjb from Servlet : <%= request.getAttribute("helloEjb") %><br>
Print Hello : <%= request.getAttribute("printHello") %>
</body>
</html>

notes:
Calling EJB 3 using JNDI lookup isn’t the same between Application Server, JNDI lookup name is not standardized. Refer to this article find out more.

References:
- http://www.adam-bien.com/roller/abien/entry/ejb_3_portability_issue_why
- http://javahowto.blogspot.com/2006/09/default-jndi-name-for-resource-or-ejb.html
- https://glassfish.dev.java.net/javaee5/ejb/EJB_FAQ.html

I was trying to make an alternative of @MappedSuperclass using Hibernate XML (*.hbm.xml) files. The case is i want every persistent class have default column like ID, CREATED_ON, CREATED_BY, UPDATED_ON, UPDATED_BY – that reside on a superclass, so i don’t have to repeat those column in every mapping files. Unfortunately, basically hibernate do not support this kind of superclass mapping. Maybe the technique here will do just fine, but lack of something that i will tell later.

Nowaday programming style is coding by interface so i use interface for every persistent class and separate it’s implementation. The relationship is one-to-many between Singer and Album.

Here is BaseModel interface that every persistent class will inherits all the properties, followed by it’s concrete class and mapping:
(BaseModel.java)

package hibernate.example.model;

import java.util.Date;

public interface BaseModel {
    public Integer getId();
    public void setId(Integer id);
    public String getCreatedBy();
    public void setCreatedBy(String createdBy);
    public Date getCreatedOn();
    public void setCreatedOn(Date createdOn);
    public String getUpdatedBy();
    public void setUpdatedBy(String updatedBy);
    public Date getUpdatedOn();
    public void setUpdatedOn(Date updatedOn);
    public String getName();
    public void setName(String name);
}

(BaseModelImpl.java)

package hibernate.example.model;

import java.util.Date;

public class BaseModelImpl implements BaseModel {
    private Integer id;
    private String createdBy;
    private Date createdOn;
    private String updatedBy;
    private Date updatedOn;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    public Date getCreatedOn() {
        return createdOn;
    }

    public void setCreatedOn(Date createdOn) {
        this.createdOn = createdOn;
    }

    public String getUpdatedBy() {
        return updatedBy;
    }

    public void setUpdatedBy(String updatedBy) {
        this.updatedBy = updatedBy;
    }

    public Date getUpdatedOn() {
        return updatedOn;
    }

    public void setUpdatedOn(Date updatedOn) {
        this.updatedOn = updatedOn;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

(BaseModel.hbm.xml)

<hibernate-mapping package="hibernate.example.model">
    <class name="BaseModel" abstract="true">
        <id name="id" type="integer" column="ID">
            <generator class="increment"/>
        </id>
       <property name="createdBy" type="string" column="CREATED_BY"/>
       <property name="createdOn" type="timestamp" column="CREATED_ON"/>
       <property name="updatedBy" type="string" column="UPDATED_BY"/>
       <property name="updatedOn" type="timestamp" column="UPDATED_ON"/>
       <property name="name" type="string" column="NAME"/>
    </class>
</hibernate-mapping>

Singer Entity:
(Singer.java)

package hibernate.example.model;

import java.util.Set;

public interface Singer extends BaseModel {
    public Set<Album> getAlbums();
    public void setAlbums( Set<Album> albums );
}

(SingerImpl.java)

package hibernate.example.model;

import java.util.Set;

public class SingerImpl extends BaseModelImpl implements Singer {
    private Set<Album> albums;

    public SingerImpl() {}

    public Set<Album> getAlbums() {
        return albums;
    }

    public void setAlbums(Set<Album> albums) {
        this.albums = albums;
    }
}

(Singer.hbm.xml)

<hibernate-mapping package="hibernate.example.model">
    <union-subclass name="Singer" extends="BaseModel" abstract="true">
        <set name="albums" inverse="true" cascade="all-delete-orphan">
            <key column="ID_SINGER"/>
            <one-to-many class="Album"/>
        </set>
    </union-subclass>

    <union-subclass name="SingerImpl" extends="Singer" table="SINGER"/>
</hibernate-mapping>

Album Entity:
(Album.java)

package hibernate.example.model;

public interface Album extends BaseModel {
    public String getYear();
    public void setYear(String year);
    public Singer getSinger();
    public void setSinger(Singer singer);
}

(AlbumImpl.java)

package hibernate.example.model;

public class AlbumImpl extends BaseModelImpl implements Album {
    private Singer singer;
    private String year;

    public Singer getSinger() {
        return singer;
    }

    public void setSinger(Singer singer) {
        this.singer = singer;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }
}

(Album.hbm.xml)

<hibernate-mapping package="hibernate.example.model">
    <union-subclass name="Album" extends="BaseModel" abstract="true">
        <property name="year" type="string" column="YEAR" />

        <many-to-one name="singer" column="ID_SINGER"
            class="Singer" not-null="true" />

    </union-subclass>

    <union-subclass name="AlbumImpl" extends="Album" table="ALBUM" />
</hibernate-mapping>

Here is hibernate.cfg.xml:

<hibernate-configuration>
  <session-factory>
<!--    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/SCHEMA_NAME</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.username">username</property>
    <property name="hibernate.connection.password">password</property>
    <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
-->
    <property name="hibernate.connection.url">jdbc: oracle:thin:@localhost:1521:SID</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="hibernate.connection.username">username</property>
    <property name="hibernate.connection.password">password</property>
    <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>

    <!-- DB schema will be updated if needed -->
    <property name="hibernate.hbm2ddl.auto">update</property>

    <mapping resource="hibernate/example/model/BaseModel.hbm.xml" />
    <mapping resource="hibernate/example/model/Singer.hbm.xml" />
    <mapping resource="hibernate/example/model/Album.hbm.xml" />
  </session-factory>
</hibernate-configuration>

Simple test application can look like this:
(TestApp.java)

package hibernate.example.test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import hibernate.example.model.Singer;
import hibernate.example.model.SingerImpl;
import hibernate.example.model.Album;
import hibernate.example.model.AlbumImpl;

import java.util.Date;

public class TestApp {
    private Session session;
    private Transaction tx;

    public TestApp() {
        SessionFactory sessionFac = new Configuration().configure().buildSessionFactory();
        session = sessionFac.openSession();
    }

    public static void main(String args[]) {
        TestApp app = new TestApp();
        app.insertSinger();
        app.insertAlbum();
    }

    // insertSinger
    public void insertSinger() {
        Singer singer = new SingerImpl();
        singer.setCreatedOn( new Date() );
        singer.setCreatedBy( "admin" );
        singer.setName( "Mariah Carey" );

        tx = session.beginTransaction();
        session.save( singer );
        tx.commit();
    }

    // insertAlbum
    public void insertAlbum() {
        Singer singer = (SingerImpl) session.get( SingerImpl.class, 1 );

        Album album = new AlbumImpl();
        album.setCreatedOn( new Date() );
        album.setCreatedBy( "admin" );
        album.setName( "Rainbow" );
        album.setYear( "2000" );
        album.setSinger( singer );

        tx = session.beginTransaction();
        session.save( album );
        tx.commit();
    }
}

Result table will look like:
- Singer table
Singer table
- Album table
Album table

Here or here is full source code. Change *.odt to *.zip, then extract it. Edit hibernate.cfg.xml to match your environtment, and add required library to lib folder.

Dependency Library:
depandency's

NOTE :
Using <union-subclass> Hibernate still treat the mapping as table per concrete class. Every id’s for each persistent class will use the same generated id. And also in Oracle database it doesn’t create Singer foreign key constraint on Album table, so if we dropped Singer table it doesn’t make constraint violation error.

IntelliJ IDEA 7 work with many popular application server such as JBoss, Glassfish, Weblogic. Tomcat. It built-in plugins, ready to use after fresh installation of IntelliJ IDEA.

This article will show how to configure IntelliJ with JBoss Application Server. Major steps in this article will also work with other application server. First we need to configure web browser that we will use.

Prequisites

1. Press configure button

2. Select General button

3. Set the path of web browser, then press OK button.

Steps:

1. Create New Project

2. Create Project from scratch, Select Next

3. Set project name and path, select Java Module, select Next

4. Select Next

5. Select Web Application Checkbox, select Finish

6. Project structure will look like this

7. To begin configure application server press arrow button, then select ‘Edit Configuration’

8. Select ‘JBoss Server’, select Local

9. Set the name of application server, press configure to set application server path.

10. Select default for server instance, then press ‘Fix’ button

11. Press ‘Add Application Server specific descriptor’ button, select appropriate descriptor, press OK. Then select ‘Java EE Build Settings’ tab

12. Checks like shown in picture below. Then press OK

13. Select ‘Deployment’ tab, select Web Facets. Web Facets is web application that we want to run. Select WAR files from ‘Deployment Source’

14. Go to ‘Server’ tab, startup page will look like shown below. Then press OK

15. Press Run button to start application server and launch web application

16. The result :)

Summary

IntelliJ IDEA is really intelligence IDE. Better than Eclipse and Netbeans. You will be amazing with it plugins like Hibernate and Spring.

Servlet Filter can be used to preprocess Web application requests, therefore we can used it to secure our websites. If your web application need someone to login first before he/she can browse to another page, servlet filter can be used in such cases. Below will show how to use servlet filter to secure a web application.

Servlet filter is an interface on package javax.servlet.Filter that have three methods: init, doFilter, and destroy. We have to make our own filter class and implements Filter interface. This is the filter class called HelloFilter:

(com.halimun.filter.HelloFilter.java)

package com.halimun.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class HelloFilter implements Filter {
	private FilterConfig filterConfig;
	private String loginForm;

	// init
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		loginForm = this.filterConfig.getInitParameter("login_form");
	}

	// doFilter
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpSession session = httpRequest.getSession(false);

		if( session != null ) {
			String currentUser = (String)session.getAttribute("user");
			if (currentUser == null) {
				System.out.println("currentUser null");
				filterConfig.getServletContext().getRequestDispatcher(loginForm).forward(request, response);
			}

		}
		else{
			filterConfig.getServletContext().getRequestDispatcher(loginForm).forward(request, response);
		}

		chain.doFilter(request,response);

	}

	// destroy
	public void destroy() {}

}

The UserLogin action servlet is invoke when user press submit button at login form. It’s check wether user is exist in databases and match the password. Acctually it’s only dummy database, I use HashMap to store username (as the key) and password.

(com.halimun.servlet.UserLogin)

package com.halimun.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserLogin extends HttpServlet {
	private static final long serialVersionUID = -3955012280873977969L;
	private static final Map<String, String> users = new HashMap<String, String>();

	public void init() throws ServletException {
		users.put("admin", "secret");
		users.put("david", "password");
		users.put("gardiary", "gardiary");
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		execute(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		execute(request, response);
	}

	private void execute(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		String userPassword = users.get(username);

		if(userPassword!=null && userPassword.equals(password)) {
			request.getSession().setAttribute("user", username);
			response.sendRedirect( request.getContextPath() );
		}
		else {
			request.setAttribute("message", "Invalid username or password");
			getServletContext().getRequestDispatcher("/loginForm.jsp")
				.forward(request, response);
		}
	}
}

UserLogout action servlet is for logout from the application, it’s remove the session and redirect to login form.

(com.halimun.servlet.UserLogout.java)

package com.halimun.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserLogout extends HttpServlet {
	private static final long serialVersionUID = 5073946739765619794L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException
	{
		execute(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException
	{
		execute(request, response);
	}

	private void execute(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException
	{
		request.getSession().invalidate();
		response.sendRedirect( request.getContextPath() );
	}
}

Here is login form using JSP. We can see that the form action is “userlogin.action” which is a UserLogin action servlet.

(loginForm.jsp)

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="css/format.css" rel=stylesheet type="text/css">
<title>Login Form</title>
</head>
<body>
<form method="POST" action="userlogin.action">
	<table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse">
		<tr>
			<td>Username :</td>
			<td><input type="text" name="username"></td>
		</tr>
		<tr>
			<td>Password :</td>
			<td><input type="password" name="password"></td>
		</tr>
		<tr>
			<td>&nbsp</td>
			<td><b>
				<%= (request.getAttribute("message")==null ? "&nbsp" : request.getAttribute("message")) %>
			</b></td>
		</tr>
		<tr>
			<td colspan="2" align="center">
				<input type="submit" value="Login">
				<input type="reset" value="Cancel">
			</td>
		</tr>
   </table>
</form>
<br>
<a href="index.jsp">index page</a> - <a href="error.jsp">error page</a> -
<a href="dummy.jsp">dummy page</a>
</body>
</html>

Index.jsp is default page after user has succeed login. You can make another pages to check if the security is working.

(index.jsp)

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="css/format.css" rel=stylesheet type="text/css">
<title>Index Page</title>
</head>
<body>
	<h2>Heloooo <%= session.getAttribute("user") %>...</h2>
	<br>
	<a href="error.jsp">error page</a> - <a href="dummy.jsp">dummy page</a> -
	<a href="loginForm.jsp">login form</a>- <a href="userlogout.action">logout</a>
</body>
</html>

And here is the web.xml:

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

<web-app>
	<description>Web Application Security</description>
	<display-name>Web Application Security</display-name>

	<filter>
		<filter-name>HelloFilter</filter-name>
		<filter-class>com.halimun.filter.HelloFilter</filter-class>
		<description>
			This Is Hello Filter
		</description>
		<init-param>
			<param-name>login_form</param-name>
			<param-value>/loginForm.jsp</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>HelloFilter</filter-name>
		<url-pattern>*.jsp</url-pattern>
	</filter-mapping>

	<servlet>
		<servlet-name>userlogin</servlet-name>
		<description>User Login Controller</description>
		<servlet-class>com.halimun.servlet.UserLogin</servlet-class>
	</servlet>
	<servlet>
		<servlet-name>userlogout</servlet-name>
		<description>User Logout Controller</description>
		<servlet-class>com.halimun.servlet.UserLogout</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>userlogin</servlet-name>
		<url-pattern>/userlogin.action</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>userlogout</servlet-name>
		<url-pattern>/userlogout.action</url-pattern>
	</servlet-mapping>

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

<filter-mapping>
   <filter-name>HelloFilter</filter-name>
   <url-pattern>*.jsp</url-pattern>
</filter-mapping>

This mapping means that request to every JSP file will be filtered first, in this case will invoke HelloFilter filter. HelloFilter filter will be processes before and after run the JSP’s files.
Acctually we can mapped filter to every requests by specifying “/*” in url-pattern of filter-mapping. In that case, every request to every resources (such as *.action, *,css, *.js, etc) will also invoke the filter.

<servlet-mapping>
   <servlet-name>userlogin</servlet-name>
   <url-pattern>/userlogin.action</url-pattern>
</servlet-mapping>
<servlet-mapping>
   <servlet-name>userlogout</servlet-name>
   <url-pattern>/userlogout.action</url-pattern>
</servlet-mapping>

In this servlet mappings, we mapped UserLogin action servlet with url-pattern “/userlogin.action” and UserLogout action servlet with url-pattern “/userlogout.action“.

Summary

So the web application structure will look like this:

[ContextRoot]\index.jsp
[ContextRoot]\loginForm.jsp
[ContextRoot]\error.jsp
[ContextRoot]\dummy.jsp
[ContextRoot]\css\format.css
[ContextRoot]\WEB-INF
[ContextRoot]\WEB-INF\classes\com\halimun\filter\HelloFilter.class
[ContextRoot]\WEB-INF\classes\com\halimun\servlet\UserLogin.class
[ContextRoot]\WEB-INF\classes\com\halimun\servlet\UserLogout.class

Complete source code is this, change the extention to .war (coz free wordpress doesnt support WAR files :( ), then deploy in your favorite application server. Try to access error page or dummy page without entering username/password in login form. For login account, you can use admin/secret, david/password, or gardiary/gardiary.

When we develop an application, sometimes we need to read a file from disk. Not only character based files, but also byte/binary based files. To read/write character based files we use Writer and Reader class hierarchy, to read byte/binary based files we use InputSteam and OutputStream class hierarchy.

This article will show how to read binary files such as EXE, PDF, and make a copy of that file on different location on disk. We will open the file, read byte by byte, and write all the bytes we get to make a copy of that file.

I use three different way to get the bytes from the file as far as i know. I dont know which one is the best based on the performance or algorithm :p.

(Way 1)


File file = new File(PATH_TO_FILES);

fis = new FileInputStream(file);
dis = new DataInputStream(new BufferedInputStream(fis));

fos = new FileOutputStream(DESTINATION_PATH_AND_FILE_NAME);
dos = new DataOutputStream(new BufferedOutputStream(fos));

byte b;
try{
	while(true){
		b = (byte) dis.readByte();

		dos.write(b);
	}
}
catch(EOFException e){
	System.err.println("Finish read end of file...");
}
finally{
        dos.close();
}

(Way 2)

File file = new File(PATH_TO_FILES);

fis = new FileInputStream(file);
dis = new DataInputStream(new BufferedInputStream(fis));

fos = new FileOutputStream(DESTINATION_PATH_AND_FILE_NAME);
dos = new DataOutputStream(new BufferedOutputStream(fos));

byte[] b = new byte[(int) file.length()];

for(int i=0; i<b.length-1; i++)
{
	b[i] = dis.readByte();
}

dos.write(b);
dos.close();

(Way 3)

File file = new File(PATH_TO_FILES);

fis = new FileInputStream(file);
dis = new DataInputStream(new BufferedInputStream(fis));

fos = new FileOutputStream(DESTINATION_PATH_AND_FILE_NAME);
dos = new DataOutputStream(new BufferedOutputStream(fos));

ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[200];

while(true){
	int length = dis.read(b);

	System.out.println("read : " + length);

	if (length < 0) {
		break;
	}

	if(length > 0){
		baos.write(b, 0, length);
	}

}

dos.write(baos.toByteArray());
dos.close();

(Full source code)

/**
 * @author	: gardiary
 * @Waktu	: Jul 28, 2008, 4:33:14 PM
 *
 * StreamSample.java
 */
package test.filehandling;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class StreamSample {
	private File file;
	private FileInputStream fis;
	private FileOutputStream fos;

	private DataInputStream dis;
	private DataOutputStream dos;

	public StreamSample()
	{
		file = new File("input/ajax-tutorial.pdf");
	}

	public static void main(String args[])
	{
		StreamSample app = new StreamSample();

		app.copyFile1();
		System.out.println("Done copy file 1...");

		app.copyFile2();
		System.out.println("Done copy file 2...");

		app.copyFile3();
		System.out.println("Done copy file 3...");

		try{
			app.dis.close();
			app.fis.close();
		}
		catch(IOException ioe){
			ioe.printStackTrace();
		}
	}

	// copy file first way
	public void copyFile1()
	{
		openFileInput();

		try{
			fos = new FileOutputStream("output/copy-of-ajax-tutorial-1.pdf");
			dos = new DataOutputStream(new BufferedOutputStream(fos));

			byte b;
			try{
				while(true){
					b = dis.readByte();

					dos.write(b);
				}

			}
			catch(EOFException e){
				System.err.println("Finish read end of file...");
			}

		}
		catch(IOException e){
			System.err.println("IOException...1");
		}
		finally{
			closeOutputStream(dos);
			closeOutputStream(fos);
		}
	}

	// copy file second way
	public void copyFile2()
	{
		openFileInput();

		try{
			fos = new FileOutputStream("output/copy-of-ajax-tutorial-2.pdf");
			dos = new DataOutputStream(new BufferedOutputStream(fos));

			byte[] b = new byte[(int) file.length()];

			for(int i=0; i<b.length-1; i++)
			{
				b[i] = dis.readByte();
			}

			dos.write(b);
		}
		catch(IOException e){
			System.err.println("IOException...2");
			e.printStackTrace();
		}
		finally{
			closeOutputStream(dos);
			closeOutputStream(fos);
		}
	}

	// copy file third way
	public void copyFile3()
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] b = new byte[200];

		openFileInput();

		try{
			fos = new FileOutputStream("output/copy-of-ajax-tutorial-3.pdf");
			dos = new DataOutputStream(new BufferedOutputStream(fos));

			while(true){
				int length = dis.read(b);

				System.out.println("read : " + length);

				if (length < 0) {
			        break;
				}

				if(length > 0){
					baos.write(b, 0, length);
				}

			}

			dos.write(baos.toByteArray());
		}
		catch(IOException e){
			System.err.println("IOException...3");
		}
		finally{
			closeOutputStream(dos);
			closeOutputStream(fos);
		}
	}

	// open file for input
	public void openFileInput()
	{
		try{
			fis = new FileInputStream(file);
			dis = new DataInputStream(new BufferedInputStream(fis));
		}
		catch(FileNotFoundException e){
			System.err.println("File Not Found...!");
		}
	}

	// close output stream
	public void closeOutputStream(OutputStream os)
	{
		try{
			os.close();
		}
		catch(IOException ioe){
			System.err.println("Exception closing output stream");
		}

	}
}

I think people must to consider on using Hibernate as their database layer. You will learn knowledge about object oriented paradigm using Hibernate. How every entity in database act as an object that related each other.

This code show the most basic CRUD using Hibernate, not using complex relationship, only one entity. For GUI I use my favorite SWT framework. Download and change the extension to .zip. Then extract it and open using Eclipse.

Before run the application edit hibernate.cfg.xml to match your environment.

(screenshot)

This is application that i had developed (for learning purposes) on 2006. I use SWT for GUI, I dont use any framework just plain java code. Feel free to explore and enjoyed. The codes is very old style (newbie style) :D , that’s why i called it old version. Next time i’ll come with different version of Sistem Lagu Top (Top Songs System) :D .. Thanks!

This is the source, after download change the extension to .zip. Extract then open and run it using Eclipse.

This is the databases, using oracle. After download change the extension to .dmp. Then import to your schema using this command (in the command line):

imp user/password@tns_name FILE=’sistemlagudb2008.dmp’ FULL=Y

Main class is org.halimun.SistemLaguTop. You may want to change class org.halimun.form.FormUtama line 59 and 61 to match your environment.

(Main Form)

Main

(Form Data Lagu – Songs Window)

Data Lagu

(Form Data Album – Albums Window)

Data Album

(Form Data Penyanyi – Singers Window)

Data Penyanyi

(Form Tipe Lagu – Genre Window)

Tipe Lagu