Java

Personal notes on Java
For other technologies like HTML, CSS, .NET, PHP, etc. check my other blog

BareTail

Baretail is a free Log File Monitoring tool.
Many features:
  • line highlighting;
  • you can create batch files to open related log files together, ex:
    SET SERVER=TEST
    SET DIR=\Logs\Applications\
     
    START baretail.exe \\%SERVER%%DIR%Application1.Console.log \\%SERVER%%DIR%Application2.Console.log \\%SERVER%%DIR%Application3.log
  • many more...
References:


Log4J

References:

Main concepts:

  • "Appender": takes care of sending the formatted output to its destination (ex. console; file; etc.).
  • "Layout" is associated, by the user, with an appender and is responsible for formatting the logging request according to the user's wishes; (ex. print the logging level; class and method line; timestamp; etc.)
    Ex. of a layout definition for an appender in a .properties file:
    log4j.appender.fileAppender.layout.ConversionPattern=[%d{ABSOLUTE}] %5p %c{1}:%L - %m%n
    This and other formating options can be found on the: PatternLayout class of the standard log4j distribution.
    Table of conversion characters:
    Conversion Character Effect
    c Used to output the category of the logging event. The category conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.
    If a precision specifier is given, then only the corresponding number of right most components of the category name will be printed. By default the category name is printed in full.
    For example, for the category name "a.b.c" the pattern %c{2} will output "b.c".
    C Used to output the fully qualified class name of the caller issuing the logging request. This conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.
    If a precision specifier is given, then only the corresponding number of right most components of the class name will be printed. By default the class name is output in fully qualified form.
    For example, for the class name "org.apache.xyz.SomeClass", the pattern %C{1} will output "SomeClass".
    WARNING Generating the caller class information is slow. Thus, use should be avoided unless execution speed is not an issue.

    d Used to output the date of the logging event. The date conversion specifier may be followed by a date format specifier enclosed between braces. For example, %d{HH:mm:ss,SSS} or %d{dd MMM yyyy HH:mm:ss,SSS}. If no date format specifier is given then ISO8601 format is assumed.
    The date format specifier admits the same syntax as the time pattern string of the SimpleDateFormat. Although part of the standard JDK, the performance of SimpleDateFormat is quite poor.
    For better results it is recommended to use the log4j date formatters. These can be specified using one of the strings "ABSOLUTE", "DATE" and "ISO8601" for specifying AbsoluteTimeDateFormat, DateTimeDateFormat and respectively ISO8601DateFormat. For example, %d{ISO8601} or %d{ABSOLUTE}.
    These dedicated date formatters perform significantly better than SimpleDateFormat.

    F Used to output the file name where the logging request was issued.
    WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.
    l Used to output location information of the caller which generated the logging event.
    The location information depends on the JVM implementation but usually consists of the fully qualified name of the calling method followed by the callers source the file name and line number between parentheses.
    The location information can be very useful. However, its generation is extremely slow and should be avoided unless execution speed is not an issue.
    L Used to output the line number from where the logging request was issued.
    WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.
    m Used to output the application supplied message associated with the logging event.
    M Used to output the method name where the logging request was issued.
    WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.
    n Outputs the platform dependent line separator character or characters.
    This conversion character offers practically the same performance as using non-portable line separator strings such as "\n", or "\r\n". Thus, it is the preferred way of specifying a line separator.
    p Used to output the priority of the logging event.
    r Used to output the number of milliseconds elapsed from the construction of the layout until the creation of the logging event.
    t Used to output the name of the thread that generated the logging event.
    x Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event.
    X Used to output the MDC (mapped diagnostic context) associated with the thread that generated the logging event. The X conversion character must be followed by the key for the map placed between braces, as in %X{clientNumber} where clientNumber is the key. The value in the MDC corresponding to the key will be output.
    See MDC class for more details.
    % The sequence %% outputs a single percent sign.

Logging levels:

Level Description
OFF The highest possible rank and is intended to turn off logging.
FATAL Severe errors that cause premature termination. Expect these to be immediately visible on a status console.
ERROR Other runtime errors or unexpected conditions. Expect these to be immediately visible on a status console.
WARN Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console.
INFO Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum.
DEBUG Detailed information on the flow through the system. Expect these to be written to logs only.
TRACE Most detailed information. Expect these to be written to logs only.

Sample .properties file

To configure log4j for your project you must add a file named "log4j.properties" (or alternatively a log4j.xml) into your project classpath (to do this I usually just paste the file in the projects "src" folder and then Eclipse will add it to the bin folder).
TIP: use this query on google to find many other sample files  log4j.properties filetype:properties.
#DEFINE A CONSOLE APPENDER:
log4j.appender.consoleAppender = org.apache.log4j.ConsoleAppender
#define the layout for the console appender:
log4j.appender.consoleAppender.layout = org.apache.log4j.PatternLayout
log4j.appender.consoleAppender.layout.ConversionPattern=[%d{HH:mm:ss.SSS}] %5p %l - %m%n

#DEFINE A FILE APPENDER (direct log messages to a log file)
log4j.appender.fileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.fileAppender.File=C:\\logs\\TesteLogger.log
log4j.appender.fileAppender.MaxFileSize=1MB
log4j.appender.fileAppender.MaxBackupIndex=1
log4j.appender.fileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.fileAppender.layout.ConversionPattern=[%d{ABSOLUTE}] %5p %c{1}:%L - %m%n

# DEFINE ROOT LOGGER OPTIONS
# the first attribute is the logging level (the level specified and above will be logged)
# the other attributes: map our console appender and file appender as a root logger (means all log messages will go to this appenders)
log4j.rootLogger = DEBUG, fileAppender, consoleAppender

# Print only messages of level WARN or above in the package novaPack
log4j.logger.novaPack=WARN

Logging Exceptions trick

Note that there is a subtle difference between the method override log#(String, Exception) and log#(Exception), ex:
try {
 Integer.parseInt("3d");
} catch (Exception ex) {
 log.error(ex); // only logs the Exception message
 log.error("Some text here", ex); // logs the full stack trace!
}

Configure log4j

Add log4j into your project

  • Web apps: (TODO)
  • Standalone apps: 

To use log4j in you project you just need to:
  • add the log4j jar into your projects classpath
    Ex. of its location: C:\apache-log4j-1.2.17\log4j-1.2.17.jar;
  • add a file named "log4j.properties" or log4j.xml into your project's classpath.
    I usually just paste it on the projects "src" folder (and then Eclipse will automatically copy it to the bin folder).
    see examples of the contents of this file further down on this page.
  • if you want you can add the log4j javadoc too
    my preferred way of doing this is to create an eclipse user library so that I can reuse it on the fly in multiple projects.

Preferred way: create a user defined library in eclipse

This way that you can reuse the configuration in multiple projects inside eclipse (then you just need to import this library to have the jar and its associated javadoc).
To do this:
  • Create a new user library and add the log4j jar:
    Project -> Properties -> Java Build Path -> Libraries -> Add Library -> User Library -> User Libraries -> New -> Add external jars -> Select the (ex) C:\apache-log4j-1.2.17\log4j-1.2.17.jar -> Open.
  • Associate the javadoc:
    Expand the just created library tree -> Select "Source Attachement" -> Edit... -> External location -> External folder -> C:\apache-log4j-1.2.17\src\main\java\ -> OK

Alternatively you can do it manually for each project:

  • Add the jar:
    Project -> Properties -> Java Build Path -> Libraries -> Add External Jars... -> Select the (ex) C:\apache-log4j-1.2.17\log4j-1.2.17.jar
  • Associate javadoc:
    For ex.: inside Eclipse type "Logger l;" Then Ctrl + click the "Logger"  class name -> on the new screen click the "Attach source..." button -> "Add external folder" -> browse to the log4j folder on your system and choose the "\src\main\java\" folder inside it.
    Sample location: C:\apache-log4j-1.2.17\src\main\java\ 




Specifying a classpath

References:


The class path is the path that the Java runtime environment searches for classes and other resource files. The class search path (more commonly known by the shorter name, "class path") can be set using either the:

  • -classpath option when calling a JDK tool like javac or java (the preferred method)
  • or by setting the CLASSPATH environment variable (not recommended). 
The -classpath option is preferred because you can set it individually for each application without affecting other applications and without other applications modifying its value.

Using the CLASSPATH environment variable (not recommended):

In windows you can operate with environment variables directly from a console (any modifications will only be valid for the current console):

  • List all environment variables:
    C:> set
  • check the contents of a variable (ex. the CLASSPATH var):
    C:> echo %CLASSPATH%
  • change the contents of a var:
    C:> set CLASSPATH=.;C:\axis2-1.6.2\lib\*
    You can also use the contents of other vars, ex:
    C:>set CLASSPATH=.;%AXIS2_HOME%\lib\* <--- the ".;" part especifies the root dir
    C:>set CLASSPATH=%CLASSPATH%;some\other\dir <-- this will append the new dir to the classpath
If you want to permanently change the contents of a var go to:
Righ-Click "My Computer" -> Properties -> Advanced -> Press "Environment Variables" button.
Edit/Create variable named CLASSPATH and add any required directories to it. You can use wildcards to specify multiple files, ex.:
  • .;C:\axis2-1.6.2\lib\*

Using the javac -cp (or -classpath):

  • Compiling the class MainFrame (that needs access to classes and jars specified in the classpath):
    C:\project> java -cp bin;C:\classes;E:\lib\junit.jar com.elharo.gui.MainFrame
  • Using classpath wildcards to specify multiple jars (NOTE: if you don't use the "" it wont work): C:\project> javac -cp "C:\axis2-1.6.2\lib\*" net\roseindia\*.java
    will compile all java classes in net.roseindia package and use required jars located in C:\axis2-1.6.2\lib\

References:

It is advised to add the AXIS2_HOME/bin to the PATH, so that you'll be able to run the following scripts from anywhere.

Axis2 wsdl2java and java2wsdl


Skeletons generation example (for the webservice):
%AXIS2_HOME%\bin\wsdl2java.bat -uri file:\\\C:\apps\axis2\samples\zSample\Axis2UserGuide.wsdl -p org.apache.axis2.axis2userguide -o target_directory_name -d adb -s -wv 1.6.2 -ss -sd

Stubs generation example (for the webservice client):
%AXIS2_HOME%\bin\WSDL2Java -uri Axis2UserGuide.wsdl -p org.apache.axis2.axis2userguide -d adb -s

7,5º obviamente... :o)

Porque:

  1. Em 360º temos 12h
  2. Portanto temos 360/12 = 30º/h
  3. Logo a cada 1/4h temos 30/4 = 7,5º
OU
a cada 90º temos 3 horas, portanto  90/3 = 30; 30/4=7,5º (c.q.d.)

OU
é matemática... podemos ir por vários caminhos mas o destino é sempre o mesmo.

No entanto, a questão de fundo mantem-se, como pergunta o jornalista: "Quanto é isso em dinheiro?"



EDIT: Fibonacci

Como tínhamos falado, não há grande valor nem em reinventar a roda nem em plagiar:
A página na wikipedia contém a função fibonacci, informa-nos das aplicações da sequência (como na análise de mercados financeiros) mas também da sua existência na natureza, como é o caso do "arranjo do cone da alcachofra"! o_O

Os algoritmos que falámos são bem conhecidos (este site contem implementações deles todos):
  • Recursivo;
  • Iterativo;
  • Memoization (fazer cache dos números já calculados para obtermos melhor performance);
A utilização de variáveis de tipo int não nos permite obter nem a primeira centena de números (a sequência tem um crescimento exponencial bastante acentuado e rapidamente ultrapassamos Integer.MAX_VALUE), mas a sua substituição por BigInteger já nos permite alcançar números de grandeza "ilegível".

Em suma, já tínhamos abordado todos estes aspectos, podia colocar aqui o código mas isso levava-nos ao inicio deste texto :)

NOTE: This page is a child of JPA page.


EntityManager

In the AffableBean project, all of the EJBs employ the EntityManager. Any of the session facade beans uses the @PersistenceContext annotation to express a dependency on a container-managed EntityManager and its associated persistence context (AffableBeanPU, as specified in the persistence.xml file).
For example, the ProductFacade bean looks as follows [1]:
@Stateless
public class ProductFacade extends AbstractFacade<Product> {
    @PersistenceContext(unitName = "AffableBeanPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    ...

    // manually created
    public List<Product> findForCategory(Category category) {
        return em.createQuery("SELECT p FROM Product p WHERE p.category = :category").
               setParameter("category", category).getResultList();
    }
}



Use the EntityManager to mark entity objects to be written to the database
em.persist(customer);

NOTE:
[1]The EntityManager's persist method does not immediately write the targeted object to the database. To describe this more accurately, the persist method places the object in the persistence context. This means that the EntityManager takes on the responsibility of ensuring that the entity object is synchronized with the database. Think of the persistence context as an intermediate state used by the EntityManager to pass entities between the object realm and the relational realm (hence the term 'object-relational mapping').

What is the scope of the persistence context? If you examine the Javadoc documentation for the @PersistenceContext annotation, you'll note that the type element is used to specify one of the above: 
  • A transaction-scoped persistence context (default behavior): is created at the start of a transaction, and terminated when the transaction ends. 
  • An extended persistence context: applies to stateful session beans only, and spans multiple transactions. 


References:
[1] - The NetBeans E-commerce Tutorial - Integrating Transactional Business Logic

You can use JPA in JavaSE almost the same way has you use it in JavaEE.
Some diferences are:

  • In JavaSE, you don't get an EntityManager instance from the Application Server (there isn't one!) so you have to create a new instance yourself, ex:
    EntityManagerFactory emf =
        Persistence.createEntityManagerFactory("EmployeeServicePU");
    EntityManager em = emf.createEntityManager();
  • In JavaSE you cant use the container managed transactions like JTA (there is no Application Server!) so you have to do it manually.
    You can use the EntityTransaction service for this, ex:
    em.getTransaction().begin();
    createEmployee(158, "John Doe", 45000);
    em.getTransaction().commit();
  • In JavaSE you need to specify every Entity class in the Persistence Unit definition (in persistence.xml);
    I.e. define XML <class> elements like the "myentities.Employee" class below:
      <persistence-unit name="JPAJavaSEPU" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>myentities.Employee</class>
        <properties>

Steps to take:
  1. Create a normal JavaSE project;
     
  2. Add the jar that contains the javax.persistence package into your project libraries.
    If you are using Glassfish you can find it on the installation folder.
    Ex.: C:\glassfish3\glassfish\modules\javax.persistence.jar
     
  3. Create a normal class and turn it into an entity:
     - Annotate your class with @Entity;
     - Annotate a class field with @Id;
     - Create get/set methods to the id field to turn in into a property;
     - The class must implement Serializable;
    Ex.:
    @Entity
    public class Employee implements Serializable {
    
        @Id 
     private int id;
        private String name;
        private long salary;  
     ...
    } 
    
      
  4. Create the database on your DBMS
    For example, if you are using MySQL you can use "MySQL Workbench" to create the database schema.
    In this example I've created a database with this attributes:
     - database name: "jpa_javase"
     - user/pass: "root" "1234";
     - MySQL is running on localhost and listening on port  3306 (the default port);
     
  5. Create a persistence unit (PU) and add the the JPA implementation jars into your project libraries:
    If you are using Netbeans you can click on the light bulb next to the class name and it will take you through the entire configuration of the PU and the connection that it uses for the database.


    This will:
    • Generate the necessary xml definitions for the PU in your projects persistence.xml file.
      Example of the persistence.xml file:
      <?xml version="1.0" encoding="UTF-8"?>
      <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
        <persistence-unit name="JPAJavaSEPU" transaction-type="RESOURCE_LOCAL">
          <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
          <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa_javase"/>
            <property name="javax.persistence.jdbc.password" value="1234"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
          </properties>
        </persistence-unit>
      </persistence>
    • Add the jars of your JPA implementation (ex. Hibernate; EclipseLink, etc.) into your project libraries.
      For the EclipseLink it would import these 2 jars:
      TODO

  6. Create a test method to run a JPA instruction and check if everything is ok
    Ex.:
    public static void main(String[] args) {
     try {
      EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAJavaSEPU");
      EntityManager em = emf.createEntityManager();
      Employee employee = new Employee();
      employee.setId(1);
      employee.setName("Antero");
      employee.setSalary(3000);
      
      em.getTransaction().begin();
      em.persist(employee);
      em.getTransaction().commit();
     } catch (Exception ex) {
      System.out.println("Error: " + ex.getMessage());
     }
    } 
    
     
    NOTE: you need to surround em.persist with the em.getTransaction().begin() and em.getTransaction().commit() to start and end a transaction otherwise nothing will get persisted on the database!
     
  7. Add your "DBMS JDBC driver" jar into your project libraries
    For MySQL this driver is called "Connector/J".
    The file name is something like "mysql-connector-java-5.1.21-bin.jar" depending on your version of the driver.
    I've mine in: C:\glassfish3\glassfish\domains\domain1\lib\mysql-connector-java-5.1.21-bin.jar
    If you don't have it yet check the JDBC page on this site to see where to find it and download it.

    If you skip this step and run the program you'll get and error like:
    ...
    Exception Description: Configuration error.  Class [com.mysql.jdbc.Driver] not found.
    ... 
    
     
  8. Add your entity classes into the Persistence Unit (PU) configuration (persistence.xml)
    • You can add them manually in the persistence.xml
      For example for the entity "Employee" you would add a line like:
      <class>entities.Employee</class>
      
      Where "entities" is the package name for the "Employee" class.
    • Or you can use "NetBeans XML editor" to edit the persistence.xml and add the entities through the GUI:
      Double click "persistence.xml" on the project tree to open the XML editor. Then click the "Add Class..." button to select and add the entities;

    If you skip this step you'll get an error like:
    Error: Object: entities.Employee@1aa8d4 is not a known entity type.
    


Code example

Employee entity class
@Entity
public class Employee {
@Id private int id;
private String name;
private long salary;
public Employee() {}
public Employee(int id) { this.id = id; }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public long getSalary() { return salary; }
public void setSalary (long salary) { this.salary = salary; }
}

Service Class for Operating on Employee Entities:
import javax.persistence.*;
import java.util.List;

public class EmployeeService {

    protected EntityManager em;

    public EmployeeService(EntityManager em) {
        this.em = em;
    }

    public Employee createEmployee(int id, String name, long salary) {
        Employee emp = new Employee(id);
        emp.setName(name);
        emp.setSalary(salary);
        em.persist(emp);
        return emp;
    }

    public void removeEmployee(int id) {
        Employee emp = findEmployee(id);
        if (emp != null) {
            em.remove(emp);
        }
    }

    public Employee raiseEmployeeSalary(int id, long raise) {
        Employee emp = em.find(Employee.class, id);
        if (emp != null) {
            emp.setSalary(emp.getSalary() + raise);
        }
        return emp;
    }

    public Employee findEmployee(int id) {
        return em.find(Employee.class, id);
    }

    public List<Employee> findAllEmployees() {
        TypedQuery<Employee> query = em.createQuery(
                "SELECT e FROM Employee e", Employee.class);
        return query.getResultList();
    }
}



Using EmployeeService
import javax.persistence.*;
import java.util.List;

public class EmployeeTest {

    public static void main(String[] args) {
        EntityManagerFactory emf =
                Persistence.createEntityManagerFactory("EmployeeService");
        EntityManager em = emf.createEntityManager();
        EmployeeService service = new EmployeeService(em);
// create and persist an employee
        em.getTransaction().begin();
        Employee emp = service.createEmployee(158, "John Doe", 45000);
        em.getTransaction().commit();
        System.out.println("Persisted " + emp);
// find a specific employee
        emp = service.findEmployee(158);
        System.out.println("Found " + emp);
// find all employees
        List<Employee> emps = service.findAllEmployees();
        for (Employee e : emps) {
            System.out.println("Found employee: " + e);
        }
// update the employee
        em.getTransaction().begin();
        emp = service.raiseEmployeeSalary(158, 1000);
        em.getTransaction().commit();
        System.out.println("Updated " + emp);
// remove an employee
        em.getTransaction().begin();
        service.removeEmployee(158);
        em.getTransaction().commit();
        System.out.println("Removed Employee 158");
// close the EM and EMF when done
        em.close();
        emf.close();
    }
}

What is Refactoring?

  • Refactoring is a disciplined technique for improving the structure of existing code without changing the observable behavior.
  • In short: change the structure of your code, without changing behavior. Using Refactoring, you can easily move fields, methods or classes around without breaking things. Refactorings come as simple as Rename or more complex like Tease Apart Inheritance.

Why should I Refactor?
  • Refactoring improves the design of software 
  • Refactoring makes software easier to understand 
  • Refactoring makes software easier to maintain 
  • Refactoring helps you find bugs 
  • Refactoring helps you program faster 
What are the various techniques in refactoring? Following are of some of the transformations that can be done in order to refactor your code:
  • Rename: You can change the name of a package, class, method or field to something more meaningful. Netbeans will update all source code in your project to reference the element by its new name.
  • Replace block of code with a method;
  • Encapsulate Fields: Many IDEs can automatically generates a getter method and and a setter method for a field and optionally update all referencing code to access the field using the getter and setter methods.
  • Move Class: Moves a class to another package or into another class. In addition, all source code in your project is updated to reference the class in its new location.
  • Safely Delete: Checks for references to a code element and then automatically deletes that element if no other code references it.
  • Change Method Parameters: Enables you to add parameters to a method and change the access modifier.
  • Extract Interface: Creates a new interface from the selected public non-static methods in a class or interface.
  • Extract Superclass: Creates a new abstract class, changes the current class to extend the new class, and moves the selected methods and fields to the new class.
  • Move Inner to Outer Level: Moves an inner class one level up in hierarchy. 

Refactoring with Netbeans

Check this article: Refactoring with Netbeans