Wednesday, October 20, 2010

Web Server, Web Container & Application Server

A Web Server is a server capable of receiving HTTP requests, interpreting them, processing the corresponding HTTP Responses and sending them to the appropriate clients (Web Browsers).
Example: Apache Web Server

A Web Container, also called Servlet container or Servlet engine, is a J2EE compliant implementation which provides an environment for the Servlets and JSPs to run. Putting it differently we can say that a Web Container is combination of a Servlet Engine and a JSP Engine. If an HTTP Request refers to a Web Component (typically a Servlet or a JSP) then the request is forwarded to the Web Container and the result of the request is sent back to Web Server, which uses that result to prepare the HTTP Response for the particular HTTP Request.
Example: Tomcat is a typical Web Container. A typical setup would be to have Apache HTTP Server as the Web Server and Tomcat as the Web Container.
Illustration: Servlet Container = Web Server + Servlets/JSPs (dynamic response generation)

An Application Server is a complete server, which provides an environment for running the business components (EJBs, ADF BCs, etc.) in addition to providing the capabilities of a Web Container as well as of a Web Server.
Example: Bea WebLogic, IBM WebSphere, Oracle Application Server, etc.
Illustration: Application Server = Web Server + Servlets/JSPs + Business component (EJB)

Source:
- copied from http://geekexplains.blogspot.com/2008/06/web-server-web-container-application.html
http://www.ecomputercoach.com/index.php/component/content/article/68-servers/72-web-server-vs-servlet-container-vs-application-server.html

Sunday, September 12, 2010

JSP / JSTL / EL

JSP
JavaServer Pages (JSP) - is the standard presentation-layer technology for the J2EE platform.

JSP scripting elements:
  • expressions
    - form: <%= javaExpression %>
    - ex: date = <%= new java.util.Date() %>
    - xml syntax: <jsp:expression>javaExpression</jsp:expression>
  • scriptlets
    - form: <% code %>
    - xml syntax: <jsp:scriplet>code</jsp:scriplet>
  • declarations
    - form: <!% code %>
    - xml syntax: <jsp:declaration>code</jsp:declaration>
Comments
  • JSP Comment - <%-- JSP Comment --%>
  • HTML Comment - <!-- HTML Comment -->
Predefined vars: request, response, session, out, application, config, pageContext and page

JSTL

JSP Standard Tag Library (JSTL) - is a collection of standard custom tag libraries that implement basic functionality common to a wide range of server-side Java applications.

EL
Expression Language (EL) - is a simplified form for JSP expression
- syntax: ${elExpression}

Source:
http://www.ibm.com/developerworks/java/library/j-jstl0211.html
http://download.oracle.com/docs/cd/E17802_01/j2ee/j2ee/1.4/docs/tutorial-update2/doc/index.html

Thursday, September 9, 2010

Line Wrap for excel cells

DO:
In report manager,
exporter.setParameter(JExcelApiExporterParameter.IS_COLLAPSE_ROW_SPAN, Boolean.TRUE);

In xml,
textField isStretchWithOverflow="true" // on long data input cells
reportElement stretchType="RelativeToTallestObject"

API: http://jasperreports.sourceforge.net/api/net/sf/jasperreports/engine/export/JRXlsAbstractExporterParameter.html

Wednesday, June 9, 2010

Initialization of list/map in one line

List
ArrayList places = new ArrayList(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

ArrayList list = new ArrayList() {{
add("A");
add("B");
add("C");
}}

link

Map
Map m = new HashMap() {
{
put(".jpg", "image/jpeg");
put(".jpeg", "image/jpeg");
}
};

Sunday, April 11, 2010

Java Concurrency/Threads

Process vs Thread
Process - is a running program that runs independently from other processes. It has its own address space and cannot directly access resources of other processes. Each process can have one or more threads.

Thread - is sometimes called lightweight process. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process. Threads share the process's resources, including memory and open files.

2 ways to define a Thread:
  1. implement Runnable interface
    - more general, can have many superclass
    - starting: (new Thread(new HelloRunnable())).start();
  2. extend Thread class (Thread class itself implements Runnable)
    - simpler but limited
    - starting: (new HelloThread()).start();

Thread methods:
  • public void run() - the only method coming from Runnable
  • public void start() - calls the run() method, can only be called once
  • public static void sleep(long millis)/(long millis, int nanos) throws InterruptedException - suspend execution for a specified period
    - time is not guaranteed
    - can be interrupted
  • public void interrupt() - indicates that thread should stop
  • public static boolean interrupted() - interrupted status is cleared
  • public boolean isInterrupted() - has no effect on interrupted status
  • public final void stop()/suspend()/resume() - deprecated

ObjectThread
notify
notifyAll
wait
sleep
yield


Source: http://java.sun.com/docs/books/tutorial/essential/index.html
http://www.vogella.de/articles/JavaConcurrency/article.html

Thursday, April 1, 2010

Using Resource Bundle

ResourceBundle is a class used for containing locale-specific data. A Locale defines the user's environment particularly its language and region. A certain number in one locale may be written differently in another. Likewise, a label of a "Cancel" button may differ in different locales. Using ResourceBundle will allow you to handle these different locales without having to hard-code the locale-specific data.

Sample of retrieving locale-specific data
list of resource bundles:
ButtonLabel
ButtonLabel_de
ButtonLabel_en_GB
ButtonLabel_fr_CA_UNIX


selecting the locale-specific ButtonLabel resource bundle:
Locale currentLocale = new Locale("fr", "CA", "UNIX");
ResourceBundle introLabels =
ResourceBundle.getBundle("ButtonLabel", currentLocale);


2 Types of ResourceBundle
  1. PropertyResourceBundle - uses a properties file to contain the key-value pairs. The value can only be a String.

    properties files for 3 resource bundles:
    LabelsBundle.properties
    LabelsBundle_de.properties
    LabelsBundle_fr.properties

    resource bundle sample content:
    # This is the LabelsBundle_de.properties file
    s1 = Computer
    s2 = Platte
    s3 = Monitor
    s4 = Tastatur

    use of resource bundle sample:
    Locale[] supportedLocales = {
    Locale.FRENCH,
    Locale.GERMAN,
    Locale.ENGLISH
    };

    for (int i = 0; i < supportedLocales.length; i ++) {
    ResourceBundle labels =
    ResourceBundle.getBundle("LabelsBundle",currentLocale);

    String value = labels.getString(key);
    Enumeration bundleKeys = labels.getKeys();
    while (bundleKeys.hasMoreElements()) {
    String key = (String)bundleKeys.nextElement();
    String value = labels.getString(key);
    }
    }

  2. ListResourceBundle - uses a list to contain the key-value pairs. The value can be any object.

    3 resource bundles:
    StatsBundle_en_CA.class
    StatsBundle_fr_FR.class
    StatsBundle_ja_JP.class

    resource bundle sample:
    import java.util.*;
    public class StatsBundle_ja_JP extends ListResourceBundle {
    public Object[][] getContents() {
    return contents;
    }
    private Object[][] contents = {
    { "GDP", new Integer(21300) },
    { "Population", new Integer(125449703) },
    { "Literacy", new Double(0.99) },
    };
    }

    use of resource bundle sample:
    Locale[] supportedLocales = {
    new Locale("en","CA"),
    new Locale("ja","JP"),
    new Locale("fr","FR")
    };

    for (int i = 0; i < supportedLocales.length; i ++) {
    ResourceBundle stats =
    ResourceBundle.getBundle("StatsBundle",currentLocale);

    Integer gdp = (Integer)stats.getObject("GDP");
    }

Notes:
- things to check/consider when internationalizing: http://java.sun.com/docs/books/tutorial/i18n/intro/checklist.html
- numbers, dates, times, or currencies need not be isolated in a ResourceBundle because only the display format of these objects varies with Locale, the objects themselves do not
- it is better to have multiple ResourceBundle by determining related objects and grouping them together
- ResourceBundle.Control class provides a way to control the instantiation and location of resource bundles. You can override its methods to behave differently.
- list of language codes (ISO-639): http://ftp.ics.uci.edu/pub/ietf/http/related/iso639.txt
- list of country codes (ISO-3166): http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html

Source: http://java.sun.com/docs/books/tutorial/i18n/resbundle/index.html

Tuesday, March 23, 2010

Java Exceptions

Exception Objects
Throwable
'-> Error
'-> AnnotationFormatError
'-> AssertionError
'-> IOError
'-> ThreadDeath
'-> ...
'-> Exception
'-> RuntimeException
'-> ArithmeticException
'-> ArrayStoreException
'-> ClassCastException
'-> ConcurrentModificationException
'-> IndexOutOfBoundsException
'-> NullPointerException
'-> ...
'-> ClassNotFoundException
'-> CloneNotSupportedException
'-> InterruptedException
'-> IOException
'-> NoSuchMethodException
'-> ...

Kinds of Exceptions
  1. checked - all exceptions that are not RuntimeException
  2. unchecked
    - Error
    - RuntimeException


Notes
- finally is always executed even if there is a change of control flow like when there is a return statement in try
- can you catch runtime exception? yes, you can catch any Throwable type but since the cost of checking for runtime exceptions exceeds the benefit of catching or specifying them, the compiler does not require that you catch them
- for readable code, it's good practice to append the string Exception to the names of all classes that inherit (directly or indirectly) from the Exception class
- what to use when creating your own exception: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

Ref: http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html