Showing posts with label NetBeans. Show all posts
Showing posts with label NetBeans. Show all posts

Wednesday, January 09, 2008

My X-Mas Presies

I hope your Christmas holidays were also as recreative as mine were although I had a lot of university work to do and still I haven't finished all of it. I'm really looking forward to February because in that month I'm going to post a lot of code and new developing-experiences since I have got a lot of new books for Christmas. This post will be a short one and I only want to list my presies which I got. Here we go:




So that's about it although I bought myself a book a couple of weeks ago about the NetBeans Platform. This is also the book which I'm currently reading. It's about developing a RCP Application on top of the NetBeans Platform. It's very well written I've already learned about the Platform's architecture, the concept about the Module System, Actions, Application design, the Lookup concept, the data-representation and currently I'm reading about how to create graphical components such as custom dialogs, wizards and Multi View Top Components. The next chapter is about the Visual Library which I really look forward to learn about.


In other news. Check out this website. It provides 24 new german developing books by Entwickler Press (=publisher). This was a Christmas present from the mentioned publisher but each book only was online for one day. A very friendly developer put those books on a public share so now you will be able to download them whenever you want. Also check out this message about the collaboration work from my university (TU-Vienna) and the MSDN AA and how you (all TU-students) will be able to download free MS Software (e.g. Visual Studio 2008 !!!!!!) Hurray!!!!

Cheers

Saturday, December 08, 2007

NetBeans 6.0 | A little JPA Example

In this post I'd like to show you how to use JPA in NetBeans within a Java SE application. First of all you have to create a database and call it something like TestDB. I called my database 'Medienverwaltung' because I did a small JPA-tutorial from the new Javamagazin which had exactly the same database.





Create a very simple table without any references on other tables and call it 'ACTOR'. That's all you need for a first little JPA test. Now, create a JavaApplication in NetBeans. I called my application 'JPAGenTest'.



The next step is to generate an Actor-Entity-Class which will map the data into the corresponding 'ACTOR'-table in your database. A lot of errors will show up. That's because the necessary libraries are still missing.











You can import them by configure your libriaries within the IDE or you create the persistent-unit and the libs will be imported automatically. You have to create this persistent unit anyway so I've decided to create it to import the missing libs.







Now all errors are gone and you will be able to create more JPA functionality. The next step is to implement a Manager-Class which handles the JPA persistence-context. That means this class is responsible to provide CRUD functionality for your actor-instances and to communicate with your database.



I've named this kind of class 'ActorManager' and implemented the following typically methods to interact with my database:
  • createActor
  • findById
  • findByFirstname (NamedQuery)
  • findByLastname (NamedQuery)
  • updateActor
  • removeActor
  • getAll
  • removeAll

NamedQuery is a JPA-Feature which was automatically created by NetBeans when you've created your Enitity-Class. It's a simple JPQL statement which usually will be used more often in your application.

Here is the code from the ActorManager:



package com.blogspot.sageniuz;

import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

/**
* Actor-Manager
* @author Claus Polanka
*/
public class ActorManager {

private EntityManager em;

public ActorManager(EntityManagerFactory emf) {
em = emf.createEntityManager();
}

public void createActor(ActorGenEntity actor) {
em.getTransaction().begin();
em.persist(actor);
em.getTransaction().commit();
}

public ActorGenEntity findById(Integer id) {
return em.find(ActorGenEntity.class, id);
}

public List findByFirstname(String firstname) {
Query query = em.createNamedQuery("ActorGenEntity.findByFirstname");
query.setParameter(firstname, em);
List listOfActors = query.getResultList();
return listOfActors;
}

public List findByLastname(String lastname) {
Query query = em.createNamedQuery("ActorGenEntity.findByLastname");
query.setParameter(lastname, em);
List listOfActors = query.getResultList();
return listOfActors;
}

public void updateActor(ActorGenEntity actor) {
em.getTransaction().begin();
em.merge(actor);
em.getTransaction().commit();
}

public void removeActor(ActorGenEntity actor) {
em.getTransaction().begin();
em.remove(actor);
em.getTransaction().commit();
}

public List getAll() {
Query query = em.createQuery("select a from ActorGenEntity a");
List list = query.getResultList();
return list;
}

public void removeAll() {
em.getTransaction().begin();
Query query = em.createQuery("select a from ActorGenEntity a");
List list = query.getResultList();
Iterator it = list.iterator();
while (it.hasNext()) {
ActorGenEntity actor = it.next();
em.remove(actor);
}
em.getTransaction().commit();
}

public void close() {
em.close();
}
}





Testing the application is the next thing to do, so let's create a JUnit test-clase. Before you start implementing it check if you have already imported you database-driver or you will get an exception when executing your JUnit-test.





Here is the code for my test-class:



package com.blogspot.sageniuz;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import junit.framework.TestCase;

/**
* CRUD Test for Actor-Class.
* @author Claus Polanka
*/
public class TestActorManager extends TestCase {

private ActorManager am;
private EntityManager em;
private EntityManagerFactory emf;

private static final ActorGenEntity TESTACTOR1 = new ActorGenEntity(1, "Claus", "Polanka");
private static final ActorGenEntity TESTACTOR2 = new ActorGenEntity(2, "Barbara", "Ebinger");
private static final ActorGenEntity TESTACTOR3 = new ActorGenEntity(3, "Irene", "Polanka");

public TestActorManager(String testName) {
super(testName);
}

@Override
protected void setUp() throws Exception {
emf = Persistence.createEntityManagerFactory("pu-medienverwaltung");
em = emf.createEntityManager();
am = new ActorManager(emf);
}

@Override
protected void tearDown() throws Exception {
am.close();
em.close();
emf.close();
}

public void testCRUD() {
am.createActor(TESTACTOR1);
ActorGenEntity actor = am.findById(1);
assertEquals(actor.getFirstname(), "Claus");

actor.setFirstname("Barbara");
am.updateActor(actor);

actor = am.findById(1);
assertEquals(actor.getFirstname(), "Barbara");

am.createActor(TESTACTOR2);
am.createActor(TESTACTOR3);

List list = am.getAll();
assertEquals(list.size(), 3);

am.removeAll();
list = am.getAll();
assertEquals(list.size(), 0);
}
}

The following picture shows my project-tree and how your project-structure should also look like.



After running your test you should see something like the following.



In the next days I will test more of the JPA features like support for derived Entities and stuff like that.

Cheers

Monday, November 12, 2007

RMI with NetBeans 6 Beta 2

Please don't let mislead you because of this post's title. NetBeans doesn't have any special features for RMI support. I've only chosen this title because I'm going to develop my RMI-Service in NetBeans 6 Beta 2 which is my favourite IDE.

I won't explain every detail of RMI because you will find a lot of good tutorials on the web anyway. So, the first step is to open your IDE and develop the Interface for your RemoteService:



Second step: Write your service implementation class.





package at.ac.tuwien.ds.lab2.rmi.server;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

/**
* Implementation of ICustomRemot Interface.
* @author Claus Polanka
*/
public class CustomRemoteImpl extends UnicastRemoteObject implements ICustomRemote {

/**
* Necessary because Super-Class constructor throws RemoteException.
* @throws java.rmi.RemoteException Will be thrown if there are some network
* errors.
*/
public CustomRemoteImpl() throws RemoteException {
}

/**
* Returns a string which say 'Hello World with NetBeans 6 Beta2 and RMI.'
* @return the string which holds the value.
* @throws java.rmi.RemoteException Will be thrown if there are some network
* problems.
*/
public String sayHello() throws RemoteException {
return "Hello World in NetBeans 6 Beta 2 with RMI.";
}
}


Next step ist to implement a class who starts your remote service:





package at.ac.tuwien.ds.lab2.rmi.server;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
* Starts the CustomRemote Service.
* @author Claus Polanka
*/
public class StartRemoteService {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
ICustomRemote service = new CustomRemoteImpl();
Naming.rebind("HelloWorldService", service);
} catch (RemoteException ex) {
Logger.getLogger(StartRemoteService.class.getName())
.log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(StartRemoteService.class.getName())
.log(Level.SEVERE, null, ex);
}
}

}


Now, after you have finished the serverside of your RMI application, it's time to develop the client who calls the service.





package at.ac.tuwien.ds.lab2.rmi.client;

import at.ac.tuwien.ds.lab2.rmi.server.ICustomRemote;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
* Calls my RemoteService.
* @author Claus Polanka
*/
public class Client {

/**
* Makes a lookup and gets the String of the RemoteServcie.
*/
public void run() {
try {
ICustomRemote remoteService = (ICustomRemote)
Naming.lookup("rmi://127.0.0.1/HelloWorldService");

// Calls remote method.
String remoteString = remoteService.sayHello();

System.out.println(remoteString);

} catch (NotBoundException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} catch (RemoteException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Client client = new Client();
client.run();
}
}



Now, compile everything and you should see something like the following output:





So, if you have the same environment as I have (only one machine ;-) you don't have to copy anything to another location. Just generate the Service Stub-Class, start the rmiregistry and start your service. Then your client should be able to execute the Service and print out it's result which is in my case a simple string.

Generate Stub-Class:




Now, you should be able to see a new generated class in corresponding package where you have generated the Stub.



Start the RMI-Registry to register the Service.



Start your service and bind it to your registry.



Let's run the Client.



And see the result.



Hope you liked it.

Cheers

How To Rename Colums in Derby DB and NetBeans 6 Beta 2

Yesterday, I showed you how to create foreign keys in Derby DB within NetBeans 6 Beta 2 database tools. After I thought I had finished this tutorial I noticed a little mistake in my 'PRUEFEN' table of my database.

The primary key or better the foreign key 'PERNR' had the wrong name. The right name should have been 'PERSNR' which is a reference to the primary key 'PERSNR' of my 'PROFESSOREN' table. So, how can I refactore this little (I thought it was little but it wasn't) mistake.

The first step I have done was to search for a solution in the Derby documentation and it's SQL implementation and feature support. Today I've finally realised that something like 'ALTER TABLE RENAME COLUMN OLDNAME TO NEWNAME' isn't supported by Derby so I tried to figure out an alternative way to find a solution for my problem. Here's what I did:

I've created a backup of my table and with this backup I'm able to recreate my table again. The idea was to delete the old 'PRUEFEN' table and create a new one by recreating the old table.

This will open a dialog with a SQL command which will set up my new table (=> simple CREATE TABLE statement). So, the advantage of this workaround is, I just have to rename my column in the SQL-statement and I would have found a solution for my problem... BUT... (keep on reading ;o)

First of all you'll be able to backup your table by right clicking it and execute the 'Grab Structure...' command. A save-dialog will pop up and there you can choose a place to save your table structure.





No you will be able to grab this structure of your old table and recreate a new one by right clicking the Table folder und select the 'Recreate Table...' button. Of course you have to rename your table if you haven't deleted the old 'PRUEFEN' table to something like 'PRUFENNEW'.



This will open up a new diaolog with the CREATE TABLE statement. Now by clicking the 'Edit table script' button you will be able to change your column name. If you have already forgotten... that's why I've started to write this tutorial ;-)





Have you recognized the table script in the above picture? Where have all the foreign keys gone? Hmmmmmm.... So now I have the same work as yesterday. Hopefully in the final release this problem will be solved. I changed my table script so all my requirements are implemented and that is what it looks like:



Finished! No.... I've forgotton the PERSNR foreign key. Damn it! But I have to do the whole work again anyway because I don't want to have the '...NEW' in my table's name. Ahhhh ;o)

Finally: My Script and my Table view




So, what do you think...? I think that's not a quite easy and effective workaround. Hopefully we will see some improvements in the final release of NetBeans 6.

Cheers

Sunday, November 11, 2007

Foreign Keys in Derby with NetBeans 6 Beta 2

Although NetBeans 6 Beta 2 provides several convenient tools for working with databases it was not possible to create a table and set foreign keys without using SQL statements.

So how did I set those foreign keys in my tables using the integrated Derby database which comes out fo the box with Netbeans. So first of all I've created my tables using the 'Create Table' tool of NetBeans by right clicking my 'Tables' folder of a connected database and execute the 'Create Table...' command.




Then you will be able configure you table by editing your table scheme. In my case I have a 'PRUEFEN' table which represents a relation between students (N), lectures (N) and teachers (1) so I have three foreign keys: MATRNR (students), VORLNR (lectures) and PERNR (teachers) but you won't be able to set those foreign keys with this database tool.



So, after clicking the 'OK' button your table will be created but no foreign keys will be set. If you click on your foreign keys folder in your table structure you won't find any. So, you have to additionally add them by executing the corresponding SQL ALTER statements.



Right click your foreign keys folder and press the 'Execute Statement...' command.



Then type the following command: ALTER TABLE PRUEFEN ADD FOREIGN KEY(MATRNR) REFERENCE STUDENTEN; as you can see in the next picture and run the command by clicking the little run-button which you can find over the sql statement.



So, if there are no errors you should see something like the following screen shows in your output window.



Then you have to refresh your table by right clicking it and press the 'Refresh' button. Now you should be able to see the new foreign key reference. You have to repeat this approach for every foreign key in your table.







Finally you should have successfully configured all foreign keys but hold on I've found a little mistake in my table: PERNR should be renamed to PERSNR. But this is the topic of my next post tomorrow: How to rename columns in Derby within NetBeans.

Goold night and I hope this tutorial can help you to design your database tables.

Cheers