java.net member

Rechercher dans ce site

Hello World, Barcode in Java, using ZXing

>> 29 September 2010

I have posted an article about using "Barbecue" for generating bar codes in Java, a few days ago.

 Yesterday I read this excellent post : about using "ZXing" Java Library (Open Source), to generate bar code in Java programs.

This library looks very interesting and powerful. Here is a Hello World.

ZXing ("Zebra Crossing")

The description is from the library's site
"ZXing (pronounced "zebra crossing") is an open-source, multi-format 1D/2D barcode image processing library implemented in Java. Our focus is on using the built-in camera on mobile phones to photograph and decode barcodes on the device, without communicating with a server."

Project's Site :
http://code.google.com/p/zxing/

Installing
  • Download the current version (Zxing-1.6.zip)
  • Unzip in a folder of your choice, this will give "zxing-1.6" folder
  • For normal Java programs, two .jar files must be built
  • One of the possibilities is to use "ant"
  • cd zxing-1.6/core
  • Type "ant" you'll get in the same folder "core.jar"
  • cd zxing-1.6/javase
  • Type "ant" you'll get here "javase.jar"
  • In your Java project, create a folder (give it any name), for instance "lib"
  • Copy "core.jar" and "javase.jar" to YourProject/lib
  • Add these two .jar files to YourProject/properties/Java Build Path



Hello World

package com.java_javafx.ka;

import java.io.File;
import java.io.FileOutputStream;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;

/**
 *
 * @author Kaesar ALNIJRES
 *
 */
public class HelloWorld {

  
    public static void main(String[] args) {
      
           int width = 440;
           int height = 48;
           
             
           BitMatrix bitMatrix;
        try {
            bitMatrix = new Code128Writer().encode("Hello World !!!",BarcodeFormat.CODE_128,width,height,null);
            MatrixToImageWriter.writeToStream(bitMatrix, "png", new FileOutputStream(new File("/home/kas/zxing_barcode.png")));
        } catch (WriterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}


Read more...

PrimeFaces with JSF2 Fist Step

>> 27 September 2010


JSF2 is a very cool technology. With PrimeFaces, you can add lots of components, themes and goodies, with almost no efforts at all.

Welcome to PrimeFaces
"PrimeFaces is a lightweight open source component suite for Java Server Faces 2.0 featuring 100+ rich set of JSF components."

Getting started
1.Download the .jar (current is primefaces-2.2.M1.jar). Add it to  WEB-INF/lib

2.Add WEB-INF/lib/primefaces-2.2.M1.jar to YourProject/properties/Java Build Path

3.Import the namespace, by instruction in .xhtml page
"xmlns:p="http://primefaces.prime.com.tr/ui"

Web Site :
http://www.primefaces.org/

Will it play on GAEJ
Yes. Except for some special operations where other libraries are used. Some of these use dependencies that are not on the "The JRE Class White List" of Google, for instance Jcomponent when generating bar  code with "Barbecue".
Hello Calendar
To change a bit of the famous "Hello World", I'll try here a calendar (one of the components provided by PrimeFaces)

faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
 version="2.0">

 <navigation-rule>
 <from-view-id>/prime.xhtml</from-view-id>
 <navigation-case>
 <from-outcome>done</from-outcome>
 <to-view-id>/result.xhtml</to-view-id>

  </navigation-case>
 
  </navigation-rule>
 </faces-config>


PrimeTest.java (The bean)
package fr.iipt.ka.faces;


import java.util.Date;


import javax.faces.bean.*;

@ManagedBean(name="pTest")
@RequestScoped
public class PrimeTest {
  
    private Date date;
        /**
     * @return the date
     */
    public Date getDate() {
        return date;
    }

    /**
     * @param date the date to set
     */
    public void setDate(Date date) {
      
        this.date = date;
    }
  
    public String whatNext()
    {
        return "done";
    }
  

}

prime.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui"
>
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="2">
<p:calendar value="#{pTest.date}" mode="popup" showOn="button" pattern="dd/MM/yyyy"/>
<h:commandButton action="#{pTest.whatNext}" value="result"/>
</h:panelGrid>
</h:form>
</h:body>
</html>

result.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
>
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>result.xhtml</title>
</h:head>
<h:body>

result.xhtml<br/>
<h:outputText value="#{pTest.date}">
<f:convertDateTime pattern="dd/MM/yyyy"/>
</h:outputText>

</h:body>
</html>








 

Using a customized theme
There are many themes, ready to use. Each is a zip file to download on PrimeFaces site. When unzipped, it creates one folder "images" and a css file "skin.css"

How to install
1.Disable default skin
in web.xml
<!-- Disable original theme in primefaces -->
   <context-param>
      <param-name>primefaces.skin</param-name>
        <param-value>none</param-value>
    </context-param>
<!--END Disable original theme in primefaces  -->

2.Unzip the downloaded theme file (zip) into a folder in your application (I Used in the example "ui-lightness" the full path  to the unzipped folder is "war/primeFacesThemes/ui-lightness/")
3.In any .xhtml put a link to the css file
 <link type="text/css" rel="stylesheet" href="primeFacesThemes/ui-lightness/skin.css" />

web.xml
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  
  
    <context-param>
    <param-name>org.apache.myfaces.config.annotation.LifecycleProvider</param-name>
    <param-value>org.apache.myfaces.config.annotation.NoInjectionAnnotationLifecycleProvider</param-value>
  </context-param>
 
  <!-- for EL 2.2 -->
<context-param>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>

 <!-- end EL 2.2 -->
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
<!--  end add -->




<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</param-value>
</context-param>

<!-- Disable original theme in primefaces -->
   <context-param>
      <param-name>primefaces.skin</param-name>
        <param-value>none</param-value>
    </context-param>
<!-- END Disable original theme in primefaces  -->
  
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

prime.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui"
>
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Calendar in PrimeFaces</title>
<link type="text/css" rel="stylesheet" href="primeFacesThemes/ui-lightness/skin.css" />
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="2">
<p:calendar value="#{pTest.date}" mode="popup" showOn="button" pattern="dd/MM/yyyy"/>
<h:commandButton action="#{pTest.whatNext}" value="result"/>
</h:panelGrid>
</h:form>
</h:body>
</html>



Read more...

Hello World, in PDF, using iText and Java

>> 23 September 2010

Generating PDF from your Java programs is nowadays possible and easy, thanks to iText a free/Open Source project (you can also have a commercial license).

IText let you (between other things) generate PDF documents and save these as ordinary .pdf file from any Java program. It can also generate a PDF document on the fly, this one, for instance can be served from a servlet.

In this tiny tutorial, I'll generate a .pdf file from a Java program.

Note about GAEJ
In older versions of iText, some dependencies were not on the "The JRE Class White List" of Google. In this version (and maybe in other recent versions), this problem was likely solved and restricted class exception is now over, or at least in the code i've been testing for the last couple of days (simple PDF documents).

Official site of iText
http://itextpdf.com/

Download site
http://sourceforge.net/projects/itext/files/

Download iText
itext is available as .jar file (the current version is 5.0.4)

Installing
  • If you use a Java project (In Eclipse for instance), just create a folder of your choice in the project (in the example I called it "lib"), copy "iText-5.0.4.jar", to "lib" folder.
  • Add "iText-5.0.4.jar" (now in YourProject/lib) to YourProject/properties/Java Build Path


HelloWorld!!!

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

/**
*
* @author kaesar ALNIJRES
*
*/

public class HelloWorldFromIText {


public static void main(String[] args) {

Document document = new Document();

try {
PdfWriter.getInstance(document, new FileOutputStream("/home/kas/helloWorld.pdf"));


document.open();

document.add(new Paragraph("Hello World!!!"));

document.close();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}


Read more...

Barcode generating in Java, Barbecue, Hello World

>> 21 September 2010


If you are looking for an open source library for generating barcodes from your Java application, then this article is for you.


What is Barbecue :
"Barbecue Project" site's says
"Barbecue is a Java library that enables the creation of barcodes in a variety of standard formats that can be displayed as Swing/AWT components, included in printed output, generated as EPS and SVG and displayed in a web application."

Note:
Before going any further, please note that Barbecue will not play on GAEJ, some dependencies are not on the "The JRE Class White List" of Google, for instance JComponent.


Project's Site :
http://sourceforge.net/projects/barbecue/


Installing
  • Download the current version (In this moment it's 1.5Beta 1)
  • Unzip
  • In a Web App
    • copy barbecue-1.5-beta1.jar to war/WEB-INF/lib
    • copy jdom.jar (in the created folder/lib when unzipping ) to war/WEB-INF/lib
    • Add these two .jar files to YourProject/properties/Java Build Path
  • In a normal Java project
    • Create a folder (give it any name), for instance "lib"
    • copy barbecue-1.5-beta1.jar to YourProject/lib
    • copy jdom.jar (in the created folder/lib when unzipping ) to     YourProject/lib
    • Add these two .jar files to YourProject/properties/Java Build Path

Hello World
import java.io.File;

import net.sourceforge.barbecue.Barcode;
import net.sourceforge.barbecue.BarcodeException;
import net.sourceforge.barbecue.BarcodeFactory;
import net.sourceforge.barbecue.BarcodeImageHandler;
import net.sourceforge.barbecue.output.OutputException;

/**
 *
 * @author Kaesar ALNIJRES
 *
 */

public class BarCode {

    /**
     * @param args
     */
    public static void main(String[] args) {
      
        //1 get a File reference to save the bar code image
        File file=new File("/home/kas/barcode");
      
      
                          
        try {
            //2 create the bar code using a String (your data)
            Barcode barCode=BarcodeFactory.createCode128("Hello World !!!");
          
        //3 save the generated bar code to the above file as jpeg image
            BarcodeImageHandler.saveJPEG(barCode,file);
        } catch (OutputException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BarcodeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

}





Read more...

JSF2 and Internationalization (I18N)

>> 07 September 2010

JSF as many Java based products is designed for easy internationalization experience. One of the main feature used in localizing components is the Message Bundles.

Message Bundles are simply text files (properties files), and composed of key/value pairs. These are easy to use. The big picture is to have one properties file per language that you want to use, for instance one for English, another for French, Arabic, Russian or whatever else language, you load a MessageBundle with the current locale and get values from files. You can at any time add other files and merely other languages.

In this tutorial I'll take a sample example of an inscription form, and see how to internationalize it. I'll put only two components for the name and first name to have a compact, clear sources. I'll take two languages as example English and French

Message Bundles
We have two files, for English and French, you can give these files any name you want, with some restrictions : every file must have a suffix to identify the language and it must have ".properties" extension

I'll call my files localizedMessages_fr.properties for the French file and
localizedMessages_en.properties for the English. So the base name for every Message Bundle (or properties file) is localizedMessages. You have a suffix part to identify language : an underscore followed by the lowercase, two-letter ISO-639 language code (_fr and _en)

localizedMessages_en.properties
inscription_name=Name
inscription_firstName=First-Name

localizedMessages_fr.properties
inscription_name=Nom
inscription_firstName=Prénom

You need to note here that in the French version, "inscription_firstName" has "Prénom" as a value, this word has a special character "é". Message Bundle has to be in ASCII. To use Unicode for special characters you have two ways.

  1. Leave your properties file as is and use a program included with the JDK "native2ascii". To use it add JAVA_HOME/bin to your path and type
  2.        native2ascii file_with_special_char unicode_file
  3. Instead of using native2ascii you can replace the special character in the file with it's Unicode code for instance "é" is "\u00e9" and Prénom became  Pr\u00e9nom

Where to put Message Bundles
Save the files together with your classes, in Eclipse for example, in src/com/java_javafx/ka/ (Any way they must at the end be with the compiled classes. The properties file is loaded by the class loader)


Declare the files in your application
You can declare the Message Bundles in two ways.
1.The simplest way is to supply the declaration in WEB-INF/faces-config.xml

<faces-config>
...
<application>
<resource-bundle>
<base-name>com.java_javafx.ka.localizedMessages</base-name>
<var>msgs</var>
</resource-bundle>
</application>
...
</faces-config>

2.Instead of using a global resource bundle declaration, you can add the f:load-Bundle element to each JSF page that needs access to the bundle, like this:

<f:loadBundle basename="com.java_javafx.ka.localizedMessages" var="msgs"/>

In either cases, the messages in the bundle are accessible through a map variable with the name "msgs".

How to use these files
In any .jsf file use the variable defined in faces-config.xml or with <f:loadBundle. The variable is called here "msgs". This variable is to be used  with a key defined in a properties file

For instance to get the localized string for "name" use #{msgs.name}

How the locale is selected
  • As part of the internationalization support in Java, the bundle that matches the current locale is automatically loaded.
  • The current locale can be selected, for instance by selecting the preferred language in the browser.

Declare the accepted locales in the application
In WEB-INF/faces-config.xml
<faces-config>
...
<application>
...
<!-- set locales -->
<locale-config>
<default-locale>en</default-locale>
<supported-locale>fr</supported-locale>

</locale-config>
<!-- end locals -->
</application>
</faces-config>

Let's get an example

faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
 version="2.0">

<application>


<resource-bundle>
<base-name>com.java_javafx.ka.localizedMessages</base-name>
<var>msgs</var>
</resource-bundle>
<!-- set locales -->
<locale-config>
<default-locale>en</default-locale>
<supported-locale>fr</supported-locale>
</locale-config>
<!-- end locals -->
</application>

 <!-- navigation for inscription -->
 <navigation-rule>
 <from-view-id>/inscriptionForm.xhtml</from-view-id>
 <navigation-case>
 <from-outcome>true</from-outcome>
 <to-view-id>/result.xhtml</to-view-id>
  </navigation-case>
  </navigation-rule>
 <!-- end inscription -->
 </faces-config>


Person.java

package com.java_javafx.ka;

import java.io.Serializable;
import javax.faces.bean.*;




/**
 * @author Kaesar ALNIJRES
 *
 */
@ManagedBean(name="person")
@SessionScoped
public class Person implements Serializable {
    private String name="";
    private String firstName="";
  
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
      
        this.name = name;
    }

    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * @param firstName the firstName to set
     */
    public void setFirstName(String firstName) {
         this.firstName=firstName;
    }
public String validate()
{
    return "true";
}
}



InscriptionForm.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"

      xmlns:h="http://java.sun.com/jsf/html">


<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

</h:head>
<body>
<f:view>

<h:form prependId="false" id="form">

<h:panelGrid columns="1">

<h:panelGroup><h:outputText value="#{msgs.inscription_name}" />
<h:inputText value="#{person.name}" id="name"/>
</h:panelGroup>

<h:panelGroup>
<h:outputText value="#{msgs.inscription_firstName}" />
<h:inputText value="#{person.firstName}"  id="firstName"/>
</h:panelGroup>
</h:panelGrid>

<h:commandButton id="cmdBtn" value="OK" action="#{person.validate}" />

</h:form>

</f:view>
</body>
</html>

Display
When French is the preferred language in the browser. And English






What if we want to use localized Strings in the bean
  1. 1.Get the locale used by the browser :

    FacesContext context = FacesContext.getCurrentInstance();
    Locale locale=context.getViewRoot().getLocale();
  2. Load the ResourceBundle associated with this locale, using the full path and base name :

    rs=ResourceBundle.getBundle("com.java_javafx.ka.localizedMessages",locale);
  3. You can get any value using it's key in the properties file :

    rs.getString("inscription_name");



Person.java
With 2 added methods, one to load Resource Bundle (for instance in a method annotated with @PostConstruct, if you want a call once init method), the other to get a greeting message.


package com.java_javafx.ka;

import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.annotation.PostConstruct;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;




/**
 * @author Kaesar ALNIJRES
 *
 */
@ManagedBean(name="person")
@SessionScoped
public class Person implements Serializable {
    private String name="";
    private String firstName="";
    private ResourceBundle rs;
    private String greeting;
   
    @PostConstruct
    public  void init() {
   
       
       
        FacesContext context = FacesContext.getCurrentInstance();
        Locale locale=context.getViewRoot().getLocale();
        rs=ResourceBundle.getBundle("com.java_javafx.ka.localizedMessages",locale);
       
       
    }
   
   
    /**
     * @return the greeting
     */
    public String getGreeting() {
        greeting=rs.getString("inscription_thanks");
        return greeting;
    }


    /**
     * @param greeting the greeting to set
     */
    public void setGreeting(String greeting) {
        this.greeting = greeting;
    }


    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
       
        this.name = name;
    }

    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * @param firstName the firstName to set
     */
    public void setFirstName(String firstName) {
      this.firstName=firstName;
    }
public String validate()
{
    return "true";
}
}

Messages with Variable Parts
It's possible to add localized Strings in MessageBundles (properties files)and pass them some parameters from the calling page. They are Strings with placeholders like "hello {0}"

Placeholders are numbered {0}, {1}, {2}, and so on.

We'll get the greeting message from the bean in "result.xhtml" using <f:outputFormat, we pass a parameter to the value of "inscription_thanks" in properties files. In the example the parameter use the first name and name used in the inscription. To pass a parameter to <f:outputFormat. Use <f:param

Note:
The h:outputFormat tag uses the MessageFormat class from the standard library to
format the message string. That class has several features for locale-aware
formatting.

resultat.xhtml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>
<f:view>

<h:outputFormat value="#{person.greeting}">
<f:param value="#{person.firstName} #{person.name}"/>
</h:outputFormat>
</f:view>
</body>
</html>

localizedMessages_en.properties
inscription_name=Name
inscription_firstName=First-Name
inscription_thanks=Thank you for your inscription {0}

localizedMessages_fr.properites
inscription_name=Nom
inscription_firstName=Pr\u00e9nom
inscription_thanks=Merci {0} inscription termin\u00e9e



Read more...

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP