Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, 28 May 2011

Yesss!!!!!!! Java FX Runtime is Distributable! The future is bright!

Wow after all the Licensing issues raised here by worried observers, Oracle has listened and now, you can happily write desktop applications with javafx 2.0 and distribute it under exactly the same License as Java itself.

You can read the mini statement here.

Let the java desktop revolution begin!Link

Saturday, 18 September 2010

Hibernate in OSGi is a definite NO NO!

Recently I had the honor of trying to switch the persistence provider of our application so we can debug some performance issues and to my horrible suprise, there is no standard OSGi bundles for hibernate. Wow, with eclipselink, it was just a single jar! easy to find on eclipselink website, drop it in your auto start folder and bang! you are on your way.

After spending all day googling, I found some out of date bundles in SpringSource's repository. Wow, how difficult is it to produce an OSGi bundle if you have managed to write the code. I was thinking its just a packaging thing. Maybe am mistaken.

Anyway, after spending all that time, downloading all the gazillion dependencies manually and copying them to the felix auto start folder and also adding them to my pom file, the application finally started with all dependencies resolved.

As if that was not enough , I got an exception on startup
No Persistence provider for EntityManager named ...blah blah
What??
That was not enough? the persistence.xml file was there. The provider class specified in that file was there. I could clearly see it in Netbeans by just expanding the libraries tree and navigating the packages and the jar file that contained that class was also in the felix auto deploy folder.

I then started another googling session. It turns out hibernate has problems with classpath in OSGi. Ypu have to use some thread hacking to make it see your META-INF/persistence.xml and when you finish reset the classpath to what iwas before. At that point I just gave up. Its not worth the effort. As much as I love hibernate and hibernate-Search, its just not ready for OSGi. Will reinvent my search wheel with eclipselink

Friday, 13 August 2010

Is Oracle sinking the Java Boat? Please think of us too

A lot of people were wary with the Oracle Acquisition of Sun. For me, I was disappointed Sun was not acquired by a much more open source company. Oracle doesn't do open source with the heart and commitment Sun did. That is a fact!

The problem started becoming apparent when the big java people started leaving or walking away. That meant these guys were not comfortable in their new home.

Then it was followed by Oracle dropping some Sun products including the Sun Webspace server , project wonderland etc.

Then came Netbeans scaling down. In the new Netbeans 6.10 document, the only thing you read is performance and support for Oracle specific products. Nothing substantial to increase adoption or popularity.

Then finally Oracle is sending Google, a prominent Java shop, to the courts. Imagine all those frameworks and technologies Google has developed. What does oracle intend to acheive? More Money? Scare away big companies from Java? Or just Kill Java?

Who knows whats next?? Time for some Consipracy Theories.

My Message to Oracle
When making these decisions, think of the Millions of people who make a daily bread because they are able to write in Java and think of all those companies who employ them. If these companies fear to use Java, a lot of people will not be able to feed their families.

Please think of the Java Community! Please DO!

Tuesday, 3 August 2010

Top 10 Netbeans IDE Java Editor Shortcuts. Required for Daily Editor Usage.

These are my top 10 basic Netbeans Java Editor shortcuts that I use all the time everyday.
Hope it helps you increase your productivity.

1. Commenting. (This works in all Standard IDE editors, not just the Java editor). The commenting works regardless of the language, it will comment it appropriately. You can try it in the css editor or the XML editor


If no text is selected, the current line is commented appropriately.

2.Duplicate Current line.


3.Find implementation of an interface
With the cursor on the name of the interface,

When the list turns up, you can just click to open that class or use the keyboard to select and press enter

4. Fix Imports


5. Open class by name

Supports Camel case search and wildcards
To open any Resource ie css, html, text file use


6.Formatting

if no code is selected, the whole class file is formatted.
The formatting is controlled from that specified in Tools -> Options -> Editor -> Formatting

7.Rename a variable, class or method


8. Insert Some code.
This is one of the most used shortcut. Loads of options just appear when pressed.
The best way to utilise them is to generate getters and setters. declare all those properties,
and then press ALT+INSERT(Insert Key on the keyboard)
It works in a lot of editors, for example, in the html editor, you can easily generate Lorem Ipsum place holder.



9. Toggle Bookmark.
This helps when your file is very large and you keep scrolling up and down.

If the line is bookmarked already, the bookmark is removed and vice versa

10. Navigate bookmarks.
You can easily jump between bookmarks by pressing


Coming up next, Letting the IDE do the unnecessary typing. Stay tuned

Friday, 5 March 2010

In the age of DRYness, how dry are you?

In the age of DRYness, how dry are you. Here are 7 things to measure your DRY level.

  1. If you are using Code generators to generate CRUD functions for each of your entity controllers
    a.k.a DAOs or Entity facades each of which defines the same CRUD code with the Entity bean
    names changed, you are the Least DRY. Consider Generics and Delegation

  2. If you are using EJB 2.1 on Java 1.4, you can NEVER be DRY as there is just too much artifacts
    that are completely not reusable, ejb-jar.xml, CMP mappings, remote and local interfaces that
    don’t do anything etc. Another reason is because that platform promotes tight-coupling more
    than Channel4 promotes Big Brother!

  3. If you use Strings and scriptlets to generate your HTML ouput, your chances of being unDRY are
    above 80%

  4. If you are using the Command Controller pattern for your EJBs Session Bean or Front Contrliler
    Filter for your Views and using if clauses to select your handlers, you are 90% unDRY

  5. If all your JSP’s have the same top and bottom or if you use scriptlets to pull in the top and
    bottom such that for every JSP, there is an ‘include’ with a filename in String at the top, you are
    unDRY. Consider Templating

  6. If there is a lot of casting going on in your code, you are probably not DRY. Too much generic
    stuff that are not type safe!

  7. If you use Strings to construct your SQL statements, no matter what you do, you are unDRY even
    if you define them as global static final String!

Tuesday, 2 March 2010

Beginning Java EE 6. JSF 2.0 Tutorial. Part 3. Implementing Security. Access Control Logic via Annotations

OK. Its time for security. In the previous tutorials Part 1 and Part 2
we laid some foundational work. Now we are going to move into the real application development.

I did an extensive search on the internet looking for best practise with regards to implementing
security in a Java EE 6/JSF 2.0 Application. The reference samples from Sun..(Ooops Oracle..lol)
only provide example of how to use the Authentication functions of the Container. However, in
a real world, user access credentials and roles are mostly stored in the database and can therefore not
be hardcoded in the web.xml file.

Alternative solutions seem to use ACEGI Security for implementing Access Control Logic(ACL). However, I'm not keen on
learning Spring at this time just to implement Security. That solution also exponentially increase the number of
jars I have to worry about during deployment.

Another alternative is to use frameworks like JBoss Seam that provide in-built ACLs but at the time of this writing,
Seam is not compliant with the JSF2.0 Specification. Also , IMHO, this is not enough reason to adopt a full framework for this project,
So we will implemet it ourselves.

Lets get started.

I assume you have read Part 1 and Part 2. If you haven't please do as I will
make a lot of assumptions to tasks such as your simplea folder location, having run setenv.bat etc.
However, the main concept should be easy to follow without reading those previous sessions.

Also we are using the JSF 2.0 reference implementation (Mojarra). If you are using a different implementation such
as Apache myFaces, you will have to find the corresponding class names in your distribution and make the changes accordingly.
whiles we go along, I will mention it whenever we use anything Mojarra Specific

STEP 1

NB. Since we are not using an IDE yet, I want to say that if I say we create a
Java Class com.simplea.here.Foobar, I mean you should create the folder structure

com\simplea\here in the folder src\main\java and
in that folder create a file with name Foobar.java

Task 1.
Add the following to your pom.xml file


So your complete pom.xml looks like this


Task 1.
create Java Class com.simplea.jsf.extensions.CustomApplicationFactory

Enter the following in the file


NB: In this class, we are overiding a sun specific class. You must replace it with the corresponding
classname in your JSF 2.0 Implementation

Task 2.
create Java Class com.simplea.jsf.extensions.CustomActionListener
Enter the following in the file



Task 3.
create Java Class com.simplea.jsf.extensions.CustomApplication

Enter the following in the file


Task 4.
create Java Class com.simplea.security.SecurityManager

Enter the following in the file


The authenticate method is overloaded to accept different Security credentials depending on the client environment
At the moment it will only take UsernamePasswordCredentials so lets go ahead and create it

Task 5.
create Java Class com.simplea.security.UsernamePasswordCredentials

Enter the following in the file


Task 5.
create Java Class com.simplea.annotations.SecuredClass

Enter the following in the file


Task 6.
create Java Class com.simplea.annotations.SecuredMethod

Enter the following in the file


Task 7.
create Java Class com.simplea.handler.DashboardHandler

Enter the following in the file

This Handler has the SecuredClass Annotation on it. That means no method on it should
be called without being logged in. At the moment that is what we will use to test our SecuredClass Annotation

Task 8.
create Java Class com.simplea.handler.LoginHandler

Enter the following in the file

The Login Handler does not have any of our security annotations so you can click the login button.

Now lets test our classes to make sure they compile.

All these instructions are on the Command Prompt

Run setenv.bat. I assume you know how to do that.

Then cd to your simplea folder.

From now on, when I say type an mvn command, I will assume you have run setenv.bat in your current command prompt, and changed directory to the root of the simplea application folder.

type command

If that does not produce any errors, then you are good to proceed to the next Step. Make sure your code
compiles before proceeding to Step 2.

STEP 2


This is the site security story at the moment. To be built on.
Any user can access the index.xhtml and login.xhtml pages without having to log in.

To access the dashboard.xhtml page, the user must be logged in. At the moment, since only the LoginHandler
calls the securityManager.authenticate(), we will assume the user has logged in. In the next session when
we integrate a database, we will finish that up.


We accomplish the security requirements for the dashboard.xhtml by just annotating the DashboardHandler
with @SecuredClass



1.a) Create a file in the src\main\webapp\WEB-INF folder called faces-config.xml

1.b) Enter the following into that file



2.a) Create a file in the src\main\webapp folder called login.xhtml

2.b) Enter the following into that file



3.a) Create a file in the src\main\webapp folder called dashboard.xhtml

3.b) Enter the following into that file



We need to update the index.xhtml to include links to those pages

4. Delete the content of the index.xhtml and insert the following



NB
I am sure you have noticed the repetition in those pages and are wondering why dont we templatize them.Yes, we will do that
when we start actually designing the site. At this stage, its important we don't deviate.


Step 3


Undeploy Deploy.
Our undeploy deploy sequence is becoming repetitive so i have created a batch file to do that for us

In the folder C:\home\training\simplea, create a file called undeploy_deploy.bat

Enter the following into that file


Also, I have updated C:\home\setenv.bat so the default path is in the application folder
So open it and replace the content with this



Make sure Glassfish is running Instructions on doing that is available in the previous sessions

Open comand prompt, change directory to C:\home\training\simplea and type



and press enter

Now browse to



You will observe that clicking the dashboard take you to the login screen. Just enter anything
to login. Then you will be taken to the dashboard. Also see that once logged in, clicking the dashboard link
doesn't require you to login again.

In the next installation of this series,

We will integrate a Database,(Mysql 5) and JPA. Then we will complete this security by doing a proper check
from the database and acting according. Stay Tuned


Sunday, 28 February 2010

Beginning Java EE 6. Hand Holding Learning Trail Part 2. (JSF 2.0, Maven, Glassfish, Primefaces)

In the previous session we setup the skeleton of our simplea application.
In this installation, we will add a bit of Layout to the user interface before the next major atticle which
wil takle centralising Access control and security.

NB
This is only to beautify the look and feel. We will look at 'componentising' and taking advantage of
facelets in a future session. I actually dont feel easy just leaving it as this but in order not to be distracted
we will stay with this for now.

Lets get Rolling.


This is a continuation of a series. Please read the previous post to get a feel of what we are up to from here


TASK 1


Integrating 960 CSS framework.

As you may know, programmers are normally very bad at design and I am no exception. The 960 css framework is a grid framework that
allows you to position containers(divs) and other objects on your page very easily without having to worry about advanced CSS

It is a production ready open source CSS framework. Read More about it from here
So we will use that for our simplea application. I am hoping to create composite components for the 960 framework
later in this series.
OK, here we go.

1. In the src\main\webapp folder (this is a relative to the simplea folder), create

another folder called css.

2. Download the Zip version of 960 grid framework from here

3. Extract the ziped file into a folder.

4. In the code\css folder, copy the file 960.css and reset.css to the css folder created in step 1.

5. In the same folder ie code\css, create a file called styles.css

Enter the following in that file


6. Open the index.xhtml file created in the previous session and enter this



7. Create a package:

First cd into C:\home directory

Run setenv.bat

type setenv.bat and hit the enter key

Then cd into

then type


Now Start Glasfish by typing

then type


make sure previous version is uninstalled by typing

then type

then browse to

to see the application

You can now shutdown glassfish by typing

That brings us of the end of today's seesion.

Coming Up

Login and security in JSF 2.0. Stay tuned

Friday, 19 February 2010

Beginning Java EE 6. Hand Holding Learning Trail (JSF 2.0, Maven, Glassfish, Primefaces)

In this series and few more to follow, I will be posting on how to get started
with Java EE 6, JSF 2.0, Maven, Glasfish V3, Primefaces 2.0 and related frameworks.
This is just part of my effort to know it more. As I try to teach you,
I will be teaching myself even more. Lets get started.

I will try as much as possible not to use any IDE for now. Just plain text editor
so we can understand the basics.

This is to help us understand the structure of the whole web application.
Once we are done and we start using an IDE (Netbeans 4 Me), you will realise you have much control
you have over what you are doing because you understand how it all comes together.

Ok. Lets Run

ONE GOTCHA
Windows Notepad has the habit of adding .txt to my xml files which caused me a lot of trouble
untill I realised the files were being named wrongly. eg web.xml.txt.

Make sure your files are actually .xml and .xhtml files as windows will still tell
you they are even when they are not. (I used notepad++)

PART 1


Setting up our environment
I will not be jack of all trades. I will only use Windows. If you are using linux
or some other platform you must look for the equivalent commands.

Create the folder

This will be our Workspace will be
(Just make sure you understand what you are doing if you have to choose settings
to suit your environment)
I will generally work from c:\
Change the drive letters to suit your environment

Task 1. Install Java


Get Java from our old(rebranded) site. Make sure your version is >= 1.6 update 17
Get 1.6 update 18(the latest at the time of writing) from here
http://java.sun.com/javase/downloads/widget/jdk6.jsp
Install it to so your JAVA_HOME becomes

I will not install it because I already have it installed but it should be very easy.

Task 2. Install Glassfish V3 (Zip Version)


Download Glassfish V3(Zip Version). The zip version will help us to understand how things work
even more. Also we can easily clean up our environment easily if we dont need it.
Get the full zip (Not the Web profile) from
http://download.java.net/glassfish/v3/release/glassfish-v3.zip
NB: the web profile will do but as I'm new to this, I will stay out of trouble for now
Save it to

Right-click and extract it so that, after its done, your glassfish home will be

Open notepad or any editor and type the following

and save it as setenv.bat in the folder C:\home

Task 3. Install Maven


Download Maven from one of the mirrors here
http://www.apache.org/dyn/closer.cgi/maven/binaries/apache-maven-2.2.1-bin.zip
and save it.
Then extract it such that your maven home folder will be

Open your setenv.bat in the folder C:\home
and add the following

So your whole setenv.bat file will look like

Now open Command Prompt(I guess you know how to do that..lol)
and type each of the following, press enter after each command(Don't copy and paste)



You should get something like this after your last command

Our environment is almost set.
Lets test our glassfish.
With our command prompt still opened(If you closed it, make sure you run setenv.bat to set your environment and cd to the training folder before you proceed.)

type


then type

then browse to http://localhost:4848/
You should see glassfish loading.
For now, If we get a modal box asking us to register we will not register,so just do remind me later.
Hopefully, you will see a very nice man in a boat with a paddle.
That is the test. If you see that, you have completed part 1.

PART 2 Creating the Skeleton of the Application


On the command prompt

type

the type

then press Enter
This is a wrapped version so you can understand it. Use the one above to stay out of trouble


Maven will go off to do some stuff. You will get some messages on the console and the you will see
Build Successful. Yes. The Skeleton is now created.

Maven will generate standard maven project into our training folder.

The folder structure of the maven generated project is as shown below
Skeleton of a maven application

Open the pom.xml with your favourite editor . Delete the whole content and just paste this there.
(You can also just copy the parts you just need but to make sure we all make
the same mistakes, just change it all)

I have put a lot of comments in the pom.xml to explain each part so you can adapt it to suit your needs



Inside the main folder create another two subfolders


In the webapp folder, create another sub folder called WEB-INF

In the WEB-INF folder, create a new file called web.xml


For servlet 3.0, web.xml is not required. However, you need a way to specify your welcome file and also, the custom tags were not getting processed if i used .xhtml files instead of jsp
When we understand it more, we will know why it didn't work

So your entire directory structure will look like this:
The folder structure of the maven generated project is as shown below
Maven Web Application Directory Structure

Open the web.xml in your favourite editor and enter the following

In the webapp folder, create a new file called index.xhtml
Open it in your editor and enter the following

Now our basic application is almost complete.
Now cd into simplea folder by typing


make sure you run cd c:\home\setenv.bat if you closed you Command Prompt

then type

I all goes well, You will see the build successfull message on the screen.
That will create our war file:

Task 4. Installing the war file in glassfish


NOTE

If you shut it down, restart it using the instructions above . If you are doing that
make sure you run c:\home\setenv.bat before.

Now whiles Glassfish is running
Now go to

On the left sidebar, click on Applications
Click on the deploy button
On the next page, leave the selected radio button and click browse
Browse to C:\home\training\simplea\target and select simplea.war and click open.
When you return, leave all the defaults, scroll to the bottom and click ok.
That should take you back to the applications list page

Task 5. Enable and Run


On the applications list just tick checkbox for simplea and click enable.
When the notification comes that the application is snabled,
Just click launch to see the application

Task 5. Shut down Glassfish


type

then type

Coming up next. Designing the homepage and the Login.
Stay tuned

Thursday, 10 September 2009

IzPack Installation Script Example, with Lunch4j, Ant integration, Java Service Wrapper and Windows Service

My IzPack installation script that I use for my installer has changed tremendously to integrate easily with our production system which needed installation environment properties defined in a properties file instead of being supplied by the customer. With this system, the client defines all the variables in the properties file and supply the packed zip file at installation time. The Zip file is created by us from a Technical questionnaire(TQ) given to the client at the project initiation phase. This way, we control all the parameters and customer does not make any input during the installation. We also have a Java Service wrapper file to install it automatically as a service. The file is parsed by the IzPack script to insert all the variables. We currently use this to integrate into more than ten different LLPG and NLPG systems.

CHANGE THE PATHS TO SUIT YOUR ENVIRONMENT

So here I will post my scripts: build.xml

Ant Integration Task

The IzPack Script: nizpack.zml


The Packing Time Ant Integration Script which invokes the ant script: AntActionsSpec.xml

The actual Ant script that is executed: installer_scripts.xml

Lastly, the Lauch4j script

The Lunch4jt script that is executed: launch4jConfig.xml

Sunday, 14 June 2009

Sending Email with Java Mail with attachments Example

Here I am sharing my EmailManager class that handles Email. Hope you find it useful.
package com.console.app.service;

import com.console.app.mtgapi.ApiRequest;
import com.console.app.mtgapi.ApiResponse;
import com.console.core.biz.MtEmailAuthenticator;
import com.sun.mail.smtp.SMTPSSLTransport;
import java.util.Properties;
import javax.ejb.Stateless;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

/**
 *
 * @author Farouk Alhassan
 */
@Stateless
public class EmailManagerImpl implements EmailManager {
  
  private static String SMTP_HOST_SERVER = "plus.smtp.mail.yahoo.com";
  
  private static String POP3_SERVER = " plus.pop.mail.yahoo.com";
  
  private static String SMTP_PORT = "465";
  
  private static String POP3_PORT = "995";
  
  private static String ACCOUNT_NAME ="MY_ACCOUNT_NAME";
  
  private static String EMAIL_ADDRESS = "MY_ACCOUNT_NAME@yahoo.com";
  
  private static String ACCOUNT_PASSWORD = "MY_PASSWORD";
  
  private static String USE_AUTHENTICATION = "true";
  
  private static String SMTP_USE_SSL = "true";
  
  private static String POP3_USE_SSL = "true";

  public void sendEmail(String to,
          String subject, String messageBody ) throws
          MessagingException, AddressException {

    // Setup mail server
    Properties props = System.getProperties();
    props.put("mail.smtps.host", SMTP_HOST_SERVER);
    props.put("mail.smtps.port", SMTP_PORT);
    props.put("mail.smtps.auth", USE_AUTHENTICATION);
    props.put("mail.smtps.user", ACCOUNT_NAME);

    // Get a mail session
    Session session = Session.getDefaultInstance(props,null);
      //new MtEmailAuthenticator());
    session.setDebug(true);

    // Define a new mail message 
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(EMAIL_ADDRESS));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);

    // Create a message part to represent the body text
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(messageBody,"text/html");

    //use a MimeMultipart as we need to handle the file attachments 
    Multipart multipart = new MimeMultipart();

    //add the message body to the mime message
    multipart.addBodyPart(messageBodyPart);

    // Put all message parts in the message 
    message.setContent(multipart);

    // Send the message
    SMTPSSLTransport tr = (SMTPSSLTransport) session.getTransport("smtps");
    tr.connect(SMTP_HOST_SERVER, ACCOUNT_NAME, ACCOUNT_PASSWORD);
    message.saveChanges();
    tr.sendMessage(message, message.getAllRecipients());
    tr.close();
  }

  protected void addAtachments(String[] attachments, Multipart multipart)
          throws MessagingException, AddressException {
    for (int i = 0; i <= attachments.length - 1; i++) {
      String filename = attachments[i];
      MimeBodyPart attachmentBodyPart = new MimeBodyPart();

      //use a JAF FileDataSource as it does MIME type detection
      DataSource source = new FileDataSource(filename);
      attachmentBodyPart.setDataHandler(new DataHandler(source));

      //assume that the filename you want to send is the same as the
      //actual file name - could alter this to remove the file path
      attachmentBodyPart.setFileName(filename);

      //add the attachment
      multipart.addBodyPart(attachmentBodyPart);
    }
  }
}


Feel free to comment and let me know how I could have done this better