This blog is mainly about Java...

Thursday, November 4, 2010

How to add RichFaces to your existing jQuery enabled site

As of Richfaces 3.0, jQuery has been inbuilt. If you don't know what jQuery is, you can watch a video about it here.

We have been using jQuery separately in our project, but wanted to add some Richfaces components. Now since Richfaces is using jQuery, there is a conflict that appears.

They both use $ as their main function name. That might brake the behaviour, and you might see error messages in your web browser, such as:

this.focusKeeper.observe is not a function

[Break on this error] Richfaces.ListBase.ASC="acs";Richfaces...ner('load',this.imagesOnLoad,true);}}
ListBase.js (line 4)

and
element.dispatchEvent is not a function

[Break on this error] event.eventName=eventName;event.memo=m...nt.fireEvent(event.eventType,event);}
3_3_1....eScript (line 265)

To resolve such cases jQuery introduces the .noConflict() function.

To use the jQuery that is bundled in RichFaces, you have to load the correct script.

<a:loadScript src="resource://jquery.js"/>

Then you can assign jQuery to $j for convenience. Add the following in your javascript code:
$j = jQuery.noConflict();
Then you have to replace all your former $() with $j() or the equivalents $. $[] and function($) with $j. $j[] and function($j)

Your new code now may look something like this:

function showMessages() {
  $j("div#messagetextPanel").fadeIn("fast");
}

And your Richfaces component will display and work without any problems! Thats it!

Thursday, October 7, 2010

Why you should NOT use the Seam Application Framework

NOT TO BE CONFUSED WITH SEAM, WHICH IS AWESOME!

I am a very experienced Seam user. I have used Seam daily now for almost 3 years.

In this blog post, I will try to convince you to avoid the Seam Application Framework, and truly understanding when it should be used, and when it shouldn't.

What is Seam Application Framework?
 Seam in Action says: "Seam is an application framework for Java EE. It provides a container that manages components and leverage's those components to tie the layers of an enterprise Java application together. Nestled within the Seam code base lies a handful of classes that comprise the Seam Application Framework. This "framework within a framework" is a specialized collection of component templates that effortlessly blanket the programming requirements of garden-variety web applications. Such tasks include performing create,read,update and delete (CRUD) operations on entity instances;querying for data; and developing JSF page controllers. You may be hesitant to give this spattering of classes much notice, but I assure you that they'll carry you a long way."

According to Dan Allen, he is encouraging you to check this "framework within a framework" out. However, though he is right, that there are benefits with this framework, I will prove that there are far more disadvantages than advantages and that he should have rewritten the last line to include that the framework is only really useful for small CRUD applications, and not something to leverage and build upon.

Way too many people are using this framework
If you have a look at the Seamframework.org forums, you will see tons of questions from people having problems and issues with the Seam Application Framework. Either a lot of people are developing small CRUD based applications, or there is a growing misconception about Seam and Seam Application Framework.

There are many people that are confused about this notion. They think that Seam == Seam Application Framework, and that they have to use it. And who can blame them? The seam-gen utility is a fantastic way of getting you quickly started. However, I have always encouraged people to only use the create-project and generate-entities part of the utility, and not the generate-ui part of it, this because most people I have talked with, are not developing small CRUD based applications, but rather medium sized enterprise apps, but since you get the Seam Application Framework for free, it is quite easy to extend and use it.

PROS
I did mention that there are a few pro's about using this framework, but it depends on people truly understanding the inner workings of the framework.
  • Quick to get started
  • Excellent for small models,presentation and proof of concept
  • Great in-built pagination of lists
  • Can @Override the methods and inherit classes to extend/tweak upon the framework
If you want to visualize for your customer, boss or client, an application as a proof of concept, then it is very easy to do this using the framework. In this case you don't care so much about performance and inherited abstraction layers, but rather how quickly you can get something visual and up and running.

I also want to note, before I get spammed with comments about how wrong I am, that you can if you know what you are doing, speed things up. Details can be found here. However, this again requires some knowledge about Seam.

CONS
  • Its a bit slower
  • More abstraction which might not suit your requirements
  • More difficult to use than the plain components. You need to "learn a new framework as well as Seam"

Consider this very very simple example. We have a SystemLog, and we want to display the log.


@Entity
public class SystemLog {

    @Getter @Setter
    @Id
    @GeneratedValue
    private Long id;

    @Getter @Setter
    @NotEmpty
    private String description;

    @Getter @Setter
    @Column
    private String category;

    @Getter @Setter
    @Temporal(TemporalType.TIMESTAMP)
    private Date date;

    @Getter @Setter
    @Column
    private String username;

    @Getter @Setter
    @Column
    private String organization;

    @Getter @Setter
    @Column(length = 1024)
    @Lob
    private String details;

    @Getter @Setter
    @Column
    private String severity;

    @Getter @Setter
    @Column
    private String ipAddress;

}

We have an action class that used the EntityQuery of the Seam Application Framework.


@Name("systemLogQuery")
@MeasureCalls
public class SystemLogQuery extends EntityQuery<SystemLog> {
  @Logger Log log;
  
  @Override
  public String getEjbql() {
    return "select sys from SystemLog sys";
  }
  
  @Override
  public List<SystemLog> getResultList() {
    log.warn("Inside systemlog query getResultList");
    return super.getResultList();
  }

}

And this normal (non tweaked) seam component.


@Name("systemLogNormal")
@MeasureCalls
public class SystemLogNormal {

  @Logger Log log;
  
  @In EntityManager entityManager;
  
  List<SystemLog> result;
  
  public List<SystemLog> getResultList() {
    log.warn("Inside systemLog normal resultList");
    if(result == null)
      this.result = entityManager.createQuery("FROM SystemLog").getResultList();
     
    return result;
  }
}


And a simple data table iterating over the elements

<h:dataTable value="#{systemLogNormal.resultList}" var="sys">
    <h:column>
      <f:facet name="header">
        description
      </f:facet>
      #{sys.description}
    </h:column>
</h:dataTable>

Now at first glance, I think the normal seam component is much cleaner and easier to read. Remember, this is a very simple example. In a normal real life example you would have extended the component to be much more complicated, and if you want to do this using the existing framework, you will need to find out what the framework already is doing, and correctly override those methods. Otherwise, you risk of doing the same thing twice.

If you ask your self what the @MeasureCalls annotation is doing, then have a look here, and scroll down to the second example. But a short description is that it measures the time of execution for a method.

When you run this example using the SystemLogNormal and the Query component, they are pretty much equal. However, you will see that the Query component is also calling the validate() method, which takes a few milliseconds to execute.
It is correct that a few milliseconds is hardly anything noteworthy, however this is a very very simple example, with very little data, and in a more realistic scenario, the number could possibly be different. Either way, the overall time difference is that the EntityQuery object is a few milliseconds slower.

13:58:24,224 WARN  [SystemLogQuery] Inside systemlog query getResultList
13:58:24,228 INFO  [STDOUT] Hibernate: 
    select
        systemlog0_.id as id0_,
        systemlog0_.category as category0_,
        systemlog0_.date as date0_,
        systemlog0_.description as descript4_0_,
        systemlog0_.details as details0_,
        systemlog0_.ipAddress as ipAddress0_,
        systemlog0_.organization as organiza7_0_,
        systemlog0_.severity as severity0_,
        systemlog0_.username as username0_ 
    from
        SystemLog systemlog0_
13:58:24,239 WARN  [SystemLogQuery] Inside systemlog query getResultList
13:58:24,257 WARN  [SystemLogQuery] Inside systemlog query getResultList
13:58:24,334 INFO  [TimingFilter] 2.201607 ms   1   EntityQuery.validate()
13:58:24,334 INFO  [TimingFilter] 15.967185 ms   3   SystemLogQuery.getResultList()



13:58:31,647 WARN  [SystemLogNormal] Inside systemLog normal resultList
13:58:31,648 INFO  [STDOUT] Hibernate: 
    select
        systemlog0_.id as id0_,
        systemlog0_.category as category0_,
        systemlog0_.date as date0_,
        systemlog0_.description as descript4_0_,
        systemlog0_.details as details0_,
        systemlog0_.ipAddress as ipAddress0_,
        systemlog0_.organization as organiza7_0_,
        systemlog0_.severity as severity0_,
        systemlog0_.username as username0_ 
    from
        SystemLog systemlog0_
13:58:31,662 WARN  [SystemLogNormal] Inside systemLog normal resultList
13:58:31,678 WARN  [SystemLogNormal] Inside systemLog normal resultList
13:58:31,712 INFO  [TimingFilter] 15.740409 ms   3   SystemLogNormal.getResultList()


As you can see, we get three outputs of "Inside systemlog". Really there should only be one. So adding a @Factory annotation on top of it will do the trick for both versions.

Then there are the Home and Query objects, with methods like isIdDefined(), clearDirty(), isManaged(), getEjbql(), RESTRICTIONS and more confusing methods which you need to read the documentation to understand.

Conclusion

In my opinion, for first time users who are learning Seam, it is more than enough to understand and learn the framework, instead of in addition learning "a framework inside a framework". The seam-gen utility is sort of a devil in disguise. Its great for a shortcut to get started, but its evil in disguise for new comers.

Newbies think Seam Application Framework is Seam, and all components they create must extends the Home, List or Query objects. Its confusing, and in my opinion they should avoid using it unless they know all the ins and out of both Seam and the application framework.

So if you are new to Seam, start by looking at the Seam examples that comes with the bundle. They are far better to use, than generating the UI with seam-gen and going from there.

Friday, September 17, 2010

Devoxx versus JavaOne

Devoxx or JavaOne?
Thats the question...

It's really not that difficult to choose.
If you are based in Europe (as our company is), then you will for sure get more value for your money attending Devoxx instead of JavaOne.

However, if you look at a technical perspective, then still Devoxx comes on top in my opinion. The opening talk is by Mark Reinhold and one of the last talks, "Java state of the Union" is by no other than James Gosling. (I don't even need to link to him, every Java developer should know who he is), and there are tons of fameous speakers: Brian Goetz, The JavaPosse, Heinz Kabutz, Richard Bair and Roberto Chinnici just to name a few. (No pun intented for the others I didn't mention).

So it shouldn't come as a big surprise that I am also attending Devoxx. If you are going, lemme know and we can hook up!

Sunday, September 12, 2010

Java 7, yet another delay

Mark Reinhold has published a blog stating what has been painfully obvious to everyone following the JDK 7 development: It will yet again be delayed until mid 2012(!)

Mark is further saying that there is an alternative which they are considering, and that "is to take everything we have now, test and stabilize it, and ship that as JDK 7. We could then finish Lambda, Jigsaw, the rest of Coin, and maybe a few additional key features in a JDK 8 release which would ship fairly soon thereafter."

I couldn't agree more. The community has waited too long for Java 7 to come out. There are so many problems in the current Java version, that makes people look around for alternatives in the Java Virtual Machine.
I am certain that if Java 7 will be delayed for yet two more years, then most people by that time will move to other languages such as Scala and Grails, which doesn't have the problems Java has today. 

So, to sum up. Oracle has my vote to ship whatever they have now, and then come with the rest of it with JDK 8.

Monday, August 2, 2010

Migrating from JODConverter 2 to JODConverter 3 and converting PDF to PDF/A

In the previous posting I showed you how you could automate conversions of documents to PDF & PDF/A using JODConverter 2.  

JODConverter 3.0.beta has been out for some time, and even though it is still beta, it is very stable. Maybe even more stable than JODConverter 2.

In this blog posting I will highlight the benefits of JODConverter 3 compared to its predecessor and show you how you can modify your code to create PDF/A documents with JODConverter 3.  
To be able to convert an existing PDF document to PDF/A in OpenOffice.org, you will need to install Sun PDF Import extension!

JODConverter 2 versus 3
JODConverter 3 still uses OpenOffice.org to perform its conversion. It is still a wrapper to the OOo API. It is only a complete rewrite of the JODConverter core library which is much cleaner and easier to use.

Whats new? 
  • No more init script(!) 
    • You don't have to manually start OpenOffice.org as a service anymore. This will be handled automatic.
    • You can even create multiple processes which is useful for multi-core CPU's. Best practise is one process for each CPU core.
  • Automatically restart an OOo instance if it crashes.
    • If for some reason your process crashes, JODConverter will detect this, and restart the process automatic. This was a hassle with JODConverter 2, as you needed to manually do this in Linux.
  • Abort conversions that take too long (according to a configurable timeout parameter)
  • Automatically restart an OOo instance after n conversions (workaround for OOo memory leaks)
Additionally the new architecture will make it easier to use the core JODConverter classes as a generic framework for working with OOo - not just limited to document conversions.
I am sure there will be more features when JODConverter 3 goes final.

Configuration

All you need to do do is point your OpenOffice.org installation to the OfficeManager, and you are good to go.

OfficeManager officeManager = new DefaultOfficeManagerConfiguration()
        .setOfficeHome("/usr/lib/openoffice")
        .buildOfficeManager().start();

This manager will use the default settings for Task Queue Timeout, Task Execution Timeout, Port Number etc but you can easily change them

OfficeManager officeManager = new DefaultOfficeManagerConfiguration()
        .setOfficeHome("/usr/lib/openoffice")
        .setTaskExecutionTimeout(240000L)
        .setTaskQueueTimeout(60000L)
        .buildOfficeManager().start();

If you want to utilize piping (Recommended is one process per CPU-core), you will need to set VM argument and point java.library.path to the location of $URE_LIB which on my Ubuntu machine is /usr/lib/ure/lib/
For instance:
-Djava.library.path="/usr/lib/ure/lib"

And then you can change your OfficeManager.

OfficeManager officeManager = new DefaultOfficeManagerConfiguration()
        .setOfficeHome("/usr/lib/openoffice")
        .setConnectionProtocol(OfficeConnectionProtocol.PIPE)
        .setPipeNames("office1","office2") //two pipes
        .setTaskExecutionTimeout(240000L) //4 minutes
        .setTaskQueueTimeout(60000L)  // 1 minute
        .buildOfficeManager().start();



ConverterService3Impl
The following codes performs all the converting. It supports a File or byte[] as input.

This is how you use it:
Lets say you have a PDF file as byte[], and you want to convert this byte to PDF/A as byte.
All you would have to do is call method:



byte[] pdfa = converterService.convertToPDFA(pdfFile);

Similarly, if you have a Document (say a OpenOffice.org writer document) and you want to convert this to PDF you would call the method:

File doc = new File("myDocument.odt");
File pdfDocument = converterService.convert(doc, ".pdf");

Note that you will always get a PDF/A compliant pdf. All you need to do is change the extension from ".pdf" to ".html" and the converter would do the magic.


Here is the source. Please read the comments in the source code if you want to understand it, or just ask in the comment section below.

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ejb.Local;
import javax.ejb.Stateless;

import lombok.Cleanup;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.document.DefaultDocumentFormatRegistry;
import org.artofsolving.jodconverter.document.DocumentFamily;
import org.artofsolving.jodconverter.document.DocumentFormat;
import org.artofsolving.jodconverter.document.DocumentFormatRegistry;

/**
 * This service converts files from one thing to another ie ODT to PDF, DOC to ODT etc
 * @author Shervin Asgari
 *
 */
@Stateless
@Local(ConverterService.class)
public class ConverterService3Impl implements ConverterService {

  private static final String PDF_EXTENSION = ".pdf";
  private static final String PDF = "pdf";  

  // Uncomment these when we want to use them

  // private final int PDFXNONE = 0;
  private final int PDFX1A2001 = 1;
  // private final int PDFX32002 = 2;
  // private final int PDFA1A = 3;
  // private final int PDFA1B = 4; 


  @Logger //Your favourite logger (ie Log4J) could be injected here 
  private Log log;

  public File convert(File inputFile, String extension) throws IOException, ConnectException {
    if (inputFile == null) {
      throw new IOException("The document to be converted is null");
    }

    Pattern p = Pattern.compile("^.?pdf$", Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(extension);
    OfficeDocumentConverter converter;
    
    //If inputfile is a PDF you will need to use another FormatRegistery, namely DRAWING
    if(FilenameUtils.isExtension(inputFile.getName(), PDF) && m.find()) {
      DocumentFormatRegistry formatRegistry = new DefaultDocumentFormatRegistry();
      formatRegistry.getFormatByExtension(PDF).setInputFamily(DocumentFamily.DRAWING);
      converter = new OfficeDocumentConverter(officeManager, formatRegistry);
    } else {
      converter = new OfficeDocumentConverter(officeManager);
    }
    
    String inputExtension = FilenameUtils.getExtension(inputFile.getName());
    File outputFile = File.createTempFile(FilenameUtils.getBaseName(inputFile.getName()), extension);

    try {
      long startTime = System.currentTimeMillis();
      //If both input and output file is PDF
      if (FilenameUtils.isExtension(inputFile.getName(), PDF) && m.matches()) {
        //We need to add the DocumentFormat with DRAW
        converter.convert(inputFile, outputFile, toFormatPDFA_DRAW());
      } else if(FilenameUtils.isExtension(outputFile.getName(), PDF)) {
        converter.convert(inputFile, outputFile, toFormatPDFA());
      } else {
        converter.convert(inputFile, outputFile);
      }
      long conversionTime = System.currentTimeMillis() - startTime;
      log.info(String.format("successful conversion: %s [%db] to %s in %dms", inputExtension, inputFile.length(), extension, conversionTime));

      return outputFile;
    } catch (Exception exception) {
      log.error(String.format("failed conversion: %s [%db] to %s; %s; input file: %s", inputExtension, inputFile.length(), extension, exception, inputFile.getName()));
      exception.printStackTrace();
      throw new IOException("Converting failed");
    } finally {
      //outputFile.deleteOnExit();
      //inputFile.deleteOnExit();
    }
  }
  
  /**
   * Convert pdf file to pdf/a
   * You will need to install OpenOffice extension (pdf viewer) to get it working
   * @param pdf
   * @return Byte array
   * @throws IOException
   */
  public byte[] convertToPDFA(byte[] pdfByte) throws IOException, ConnectException {
    @Cleanup InputStream is = new ByteArrayInputStream(pdfByte);
    File pdf = createFile(is, PDF_EXTENSION);
    log.debug("PDF is: #0 #1", pdf.getName(), pdf.isFile());
    return convert(pdf);
  }

  
  private byte[] convert(File pdf) throws IOException {
    if (pdf == null) {
      throw new IOException("The document to be converted is null");
    }

    File convertedPdfA = convert(pdf, PDF_EXTENSION);
    @Cleanup final InputStream inputStream = new BufferedInputStream(new FileInputStream(convertedPdfA));
    byte[] pdfa = IOUtils.toByteArray(inputStream);
    return pdfa;
  }

  /**
   * Creates a temp file and writes the content of InputStream to it. doesn't close input
   * 
   * @return File
   */
  private java.io.File createFile(InputStream in, String extension) throws IOException {
    java.io.File f = File.createTempFile("tmpFile", extension);
    @Cleanup BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
    IOUtils.copy(in, out);
    return f;
  }
  
  /**
   * This DocumentFormat must be used when converting from document (not pdf) to pdf/a
   * For some reason "PDF/A-1" is called "SelectPdfVersion" internally; maybe they plan to add other PdfVersions later.
   */
  private DocumentFormat toFormatPDFA() {
    DocumentFormat format = new DocumentFormat("PDF/A", PDF, "application/pdf");
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("FilterName", "writer_pdf_Export");

    Map<String, Object> filterData = new HashMap<String, Object>();
    filterData.put("SelectPdfVersion", this.PDFX1A2001);
    properties.put("FilterData", filterData);

    format.setStoreProperties(DocumentFamily.TEXT, properties);

    return format;
  }
  
  /**
   * This DocumentFormat must be used when converting from pdf to pdf/a
   * For some reason "PDF/A-1" is called "SelectPdfVersion" internally; maybe they plan to add other PdfVersions later.
   */
  private DocumentFormat toFormatPDFA_DRAW() {
    DocumentFormat format = new DocumentFormat("PDF/A", PDF, "application/pdf");
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("FilterName", "draw_pdf_Export");

    Map<String, Object> filterData = new HashMap<String, Object>();
    filterData.put("SelectPdfVersion", this.PDFX1A2001);
    properties.put("FilterData", filterData);

    format.setStoreProperties(DocumentFamily.DRAWING, properties);

    return format;
  }

}


Remember to close the connection when your application is quit/shutdown

Labels