Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Showing posts with label tips. Show all posts
Showing posts with label tips. Show all posts

Sunday, 28 July 2013

Java EE best practices

A recent article in IBM developerworks discusses best practices in Java EE development. This is an update of the 2004 article on J2EE best practices. Here's the complete list:
  1. Always use MVC.
  2. Don't reinvent the wheel.
  3. Apply automated unit tests and test harnesses at every layer.
  4. Develop to the specifications, not the application server.
  5. Plan for using Java EE security from Day One.
  6. Build what you know.
  7. Always use session facades whenever you use EJB components.
  8. Use stateless session beans instead of stateful session beans.
  9. Use container-managed transactions.
  10. Prefer JSPs as your first choice of presentation technology.
  11. When using HttpSessions, store only as much state as you need for the current business transaction and no more.
  12. Take advantage of application server features that do not require your code to be modified.
  13. Play nice within existing environments.
  14. Embrace the qualities of service provided by the application server environment.
  15. Embrace Java EE, don't fake it.
  16. Plan for version updates.
  17. At all points of interest in your code, log your program state using a standard logging framework.
  18. Always clean up after yourself.
  19. Follow rigorous procedures for development and testing.
Links
  1. Top Java EE Best Practices
  2. The top 10 (more or less) J2EE best practices

Wednesday, 24 July 2013

Invoking Web Services through a proxy using JAX-RPC and JAX-WS

Not very often, we face the possibility of invoking Web Services provided by external entities that are outside our network. Some companies solve this by configuring their network to allow some application servers to bypass proxy servers. Whatever be the case, when in development, developers have to to be able to invoke web services through proxies. This post will be describe how to
  • Invoking Web Services through a proxy using JAX-RPC
  • Invoking Web Services through a proxy using JAX-WS
The solutions provided here are specific to Oracle Weblogic Server 10.3. I would suggest that you try the solutions provided on "Java Networking and Proxies", and only if they don't work (which happened to me), try the following.


There's More ...
Invoking Web Services through a proxy using JAX-RPC

  1. Generate the Web Service Proxy classes using the following ant task.
    <taskdef name="clientgen" classname="weblogic.wsee.tools.anttasks.ClientGenTask" />
    <target name="build-client">
    <clientgen
    wsdl="[path_to_WSDL]"
    destDir="./src"
    packageName="com.my.client"
    type="JAXRPC"/>
    </target>
  2. When the client classes are generated the type as JAXRPC, the generated classes will consist of Service, ServiceImpl, PortType and ProtTypeImpl etc files. To invoke the service you have to create the PortType from the Service. When working behind a proxy, you have to instantiate the ServiceImpl by using a constructor that takes in a weblogic.wsee.connection.transport.http.HttpTransportInfo.HttpTransportInfo object as a parameter as shown below.
      private HttpTransportInfo getHttpInfo() {
    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyServer", 9090));
    HttpTransportInfo httpInfo = new HttpTransportInfo();
    httpInfo.setProxy(proxy);

    httpInfo.setProxyUsername("proxyuser".getBytes());
    httpInfo.setProxyPassword("proxypassword".getBytes());
    return httpInfo;
    }
    When using SSL, you can use the weblogic.wsee.connection.transport.https.HttpsTransportInfo class which can be created in the same way as above.
Invoking Web Services through a proxy using JAX-WS
  1. When using JAX-WS, you have to change the clientgen task's "type" attribute to JAXWS, as shown below
    <taskdef name="clientgen" classname="weblogic.wsee.tools.anttasks.ClientGenTask" />
    <target name="build-client">
    <clientgen
    wsdl="[path_to_WSDL]"
    destDir="./src"
    packageName="com.my.client"
    type="JAXWS"/>
    </target>
    Make sure that the "path_to_WSDL" is to a local copy of the WSDL, as the properties which we set in the following steps are after the initialization of the service.
  2. Running clientgen with JAXWS will create classes of the type *Service and *ServiceSoap
  3. Setting up the client for proxy server involves setting a couple of request paramters: Username and password as shown below.
        MyService service = null;
    service = new MyService();

    MyServiceSoap port = service.getMyServiceSoap();
    BindingProvider bp = (BindingProvider) port;
    Binding binding = bp.getBinding();

    Map<String, Object> ctx = bp.getRequestContext();
    ctx.put(BindingProvider.USERNAME_PROPERTY, "proxyuser");
    ctx.put(BindingProvider.PASSWORD_PROPERTY, "proxypassword");
    Note that we don't specify the Proxy Server here. JAX-WS sends authentication information for the proxy in request headers.

Monday, 22 July 2013

Java 5 Concurrency: Selecting Locks

As with synchronizers, there is a choice of a few implementations of Locks in Java 5. In the previous post (selecting synchronizers), I gathered a few usage scenarios where the different synchronizers may be used. In this post, I will put together a few usage scenarios where the different Lock implementations may be used.
  • Lock: Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. The standard lock implementation may be used anywhere there is a need to restrict access to a shared resource so that only one thread of execution may access the resource. Spceifically,
    • When acquiring and releasing a lock may happen in different lexical scopes.
    • Chain locking: you acquire the lock of node A, then node B, then release A and acquire C, then release B and acquire D and so on ...
  • Read/Write Lock: maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.Usage Scenarios:
    • In scenarios where where is high frequency of reads and the duration of each is sufficiently long. User registries have such a data access pattern.
It should be noted that the standard lock may be used in any place a ReadWriteLock is used, but the performance gains by using a ReadWriteLock will be high when used in the proper application. Only profiling and measurement will establish whether the use of a read-write lock is suitable for your application.

Java 5 Concurrency: Selecting Synchronizers

Few of the recent posts described the use of the various constructs provided by Java 5, through the java.util.concurrent package. The next set describes which scenarios can be solved by the use of each of these constructs. I tried to gather the usage scenarios for the various synchronizers available in Java 5 in this post.
  • Semaphores: A semaphore is the classic method for restricting access to shared resources in a multi-processing environment. While a synchronized block allows only one thread to access a resource, a semaphore allows multiple threads to access a shared resource. Semaphores are often used to restrict the number of threads than can access some resource.
    • Maintaining multiple connections to a database: Define a semaphore, which has same number of permits as there are connections to the database. If all the permits are used, then a thread requesting a connection will be blocked until another thread releases a permit, when this thread may acquire a permit.
    • Binary semaphore can be used in place of any Lock implementation. Such a implementation has an advantage when recovering from deadlocks, since the lock can be unlocked by another thread.
    • When throughput advantages of non-fair ordering often outweigh fairness considerations. Semphores allow barging behaviour. The tryAcquire() method can be used for barging ahead of other threads, irrespective of fairness settings. The tryAcquire(0, TimeUnit.SECONDS) respects fairness setting.
  • Barriers: A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. Scenrarios:
    • Joins: When you join a set of threads and start a new set, there may be a need for each thread to save state at the join point. A cyclic barrier may be used for such a scenario.
  • Latches: A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. Usage Scenarios:
    • Divide a problem into N parts, describe each part with a Runnable that executes that portion and counts down on the latch, and queue all the Runnables to an Executor. When all sub-parts are complete, the coordinating thread will be able to pass through await.
    • Latching works well with initialization tasks, where you want no process to run until everything needed is initialized.
  • Exchangers: A synchronization point at which two threads can exchange objects, the condition being that the exchanging threads have to be paired up, and a specific data type must be exchanged. Usage Scenarios:
    • An Exchanger is often used when you have two threads, one consuming a resource, and the other producing it. Similar to the producer/consumer problem, but where the buffer can be in one of only two states - empty or full.

Friday, 19 July 2013

Java 5 Static Imports

Java 5 introduces the static import feature for allowing better access to the static members of a class. According to sun, this feature helps programmers avoid the "constant interface antipattern".

The problem:
It is a general practice to declare all your constants as public static final members of an interface and access them throughout the application. For ex.

package mypackage;
public interface Constants {
public static final double PI = 3.14;
public static final double PHI = 1.61803399;
public static final int RAD = 50;
}

These constants may be accessed from another class thus

package mypackage;
import mypackage.Constants;
public class StaticImportTest {
public static void main(String args[]) {
double area = Constants.PI * Constants.RAD * Constants.RAD;

System.out.println(area);
}

}

(you can always use the constants and methods of java.lang.Math for such operations)

While this is an correct implementation, most programmers would prefer a cleaner approach to this where you can write:

double area = PI * RAD * RAD;

To achieve this, programmers tend to implement the interface, so that they can avoid typing the interface name and also have readable code. The problem with this approach is that:
  1. You are making the constants in the interface a part of the contract of your class, so any client using your class can access the constants. If they do, then any change in the constants will mean that the all the clients have to be recompiled.
  2. More importantly, you are making the constants a part of your class' API, which exposes your implementation details.

The solution:
Java 5.0 provides a solution for this problem in the form of static imports. Now you can import all the constants in the interface using a single "import static" statement thus:

import static mypackage.Constants.*;
package mypackage;
import static mypackage.Constants.PI;
import static mypackage.Constants.RAD;
public class StaticImportTest {
public static void main(String args[]) {
double area = PI * RAD * RAD;

System.out.println("2 " + area);
}

}

Although this avoids the "Constant Interface Antipattern" it also comes with some problems which can be avoided by a little careful programming:
  1. If you have multiple static imports, it becomes difficult for the reader to understand where the constant is coming from.
  2. You may end up having naming conflicts in your program.

So, here are a couple of things to remember while using static imports

  1. Always import the full path of the constant, without the wildcards. For ex:

    import static mypackage.Constants.PI;
  2. Use static imports to improve readability not to avoid typing too much.
** The code was tested on Windows XP with JDK1.5.0_06**

Wednesday, 17 July 2013

Java 5 Executors: ThreadPool

The following is a sample of a daemon that accepts requests and processes them concurrently. The daemon accepts requests and creates one thread to handle one request.
while (true) {
request = acceptRequest();
Runnable requestHandler = new Runnable() {
public void run() {
handleRequest(request);
}
};
new Thread(requestHandler).start();
}
While this is a correct implementation, it has some performance drawbacks.
  • Thread lifecycle overhead: If the requests are frequent and lightweight, the thread creation and teardown may become an overhead.
  • Resource consumption:
    • Active threads consume system resources.
    • Idle threads may occupy a lot of memory.
    • Having too many threads competing for CPU time may add an overhead to processing time.
  • Stability: Unbounded thread creation may end in an OutOfMemoryError. This is because of the limits (imposed by the native platform, JVM invocation parameters etc.) on the number of threads that can be created.
This is where the Java 5 executor framework comes in handy. Executor is the primay abstraction for task execution in Java 5.
public interface Executor {
void execute(Runnable command);
}
The executor provides a standard means of decoupling task submission from task execution. The Executors also provide thread lifecycle support and hooks for adding statistics gathering, application management, and monitoring. Executor is based on the producer-consumer pattern, where activities that submit tasks are producers and the threads that execute tasks are consumers. The following sample code shows how to use a ThreadPool (an implementation of Executor).
int NTHREADS = 100;
Executor exec = Executors.newFixedThreadPool(NTHREADS);
while (true) {
request = acceptRequest();
Runnable requestHandler = new Runnable() {
public void run() {
handleRequest(request);
}
};
exec.execute(requestHandler);
}
In this case, the main thread is the producer and requestHandler is the consumer.
Execution Policies
The various Executor implementations provide different execution policies to be set while executing the tasks. For example, the ThreadPool supports the following policies:
  • newFixedThreadPool: Creates threads as tasks are submitted, up to the maximum pool size, and then attempts to keep the pool size constant.
  • newCachedThreadPool: Can add new threads when demand increases, no bounds on the size of the pool.
  • newSingleThreadExecutor: Single worker thread to process tasks, Guarantees order of execution based on the queue policy (FIFO, LIFO, priority order).
  • newScheduledThreadPool: Fixed-size, supports delayed and periodic task execution.
Executor Lifecycle
An application can be shut down either gracefully or abruptly, or somewhere in-between. Executors provide the ability to be shutdown as abruptly or gracefully. This is addressed by the ExecutorService, which implements Executor and adds a number of methods for lifecycle management (and some utility methods).
public interface ExecutorService extends Executor {

void shutdown();

List<Runnable> shutdownNow();

boolean isShutdown();

boolean isTerminated();

boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;

<T> Future<T> submit(Callable<T> task);

<T> Future<T> submit(Runnable task, T result);

Future<?> submit(Runnable task);

<T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks)
throws InterruptedException;

<T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;

<T> T invokeAny(Collection<Callable<T>> tasks)
throws InterruptedException, ExecutionException;

<T> T invokeAny(Collection<Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;

}
The first five methods are for lifecycle management. The following code sample shows how the above methods for lifecycle management may be used
doWork() {
ExecutorService exec = ...;
while (!exec.isShutdown()) {
try {
Request request = acceptRequest();
exec.execute(new Runnable() {
public void run() { handleRequest(conn); }
});
} catch (RejectedExecutionException e) {
e.printStackTrace();
}
}
}

public void stop() { exec.shutdown(); }

void handleRequest(Request request) {
if (isShutdownRequest(req))
stop();
else
handle(req);
}

This post presented a brief overview of the Executor framework. The next post will provide more details into the usage of the executor framework, introducing more classes from the java.util.concurrent package.

Tuesday, 16 July 2013

Java 5: New features in Concurrency

Most of the new features in concurrency are implemented in the java.util.concurrent packages. There are also new concurrent data structures in the Java Collections Framework:
  • Lock objects support locking idioms that simplify many concurrent applications.
  • Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.
  • Concurrent collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.
  • Atomic variables have features that minimize synchronization and help avoid memory consistency errors.
LOCK OBJECTS
Lock objects work very much like the implicit locks (monitors) used by synchronized code. As with implicit locks, only one thread can own a Lock object at a time. Lock objects also support a wait/notify mechanism, through their associated Condition objects. All the lock objects are defined in the java.util.concurrent.lock package. The biggest advantage of Lock objects over implicit locks is their ability to back out of an attempt to acquire a lock. The tryLock method backs out if the lock is not available immediately or before a timeout expires (if specified). The lockInterruptibly method backs out if another thread sends an interrupt before the lock is acquired.

EXECUTORS
The java.util.concurrent package defines three executor interfaces:
  • Executor: A simple interface that supports launching new tasks.
  • ExecutorService: A sub-interface of Executor, which adds features that help manage the lifecycle, both of the individual tasks and of the executor itself.
  • ScheduledExecutorService: A sub-interface of ExecutorService, supports future and/or periodic execution of tasks.
CONCURRENT COLLECTIONS
The java.util.concurrent package includes a number of additions to the Java Collections Framework.
  • BlockingQueue defines a first-in-first-out data structure that blocks or times out when you attempt to add to a full queue, or retrieve from an empty queue.
  • ConcurrentMap is a subinterface of java.util.Map that defines useful atomic operations. These operations remove or replace a key-value pair only if the key is present, or add a key-value pair only if the key is absent. The standard general-purpose implementation of ConcurrentMap is ConcurrentHashMap, which is a concurrent analog of HashMap.
  • ConcurrentNavigableMap is a subinterface of ConcurrentMap that supports approximate matches. The standard general-purpose implementation of ConcurrentNavigableMap is ConcurrentSkipListMap, which is a concurrent analog of TreeMap.
ATOMIC VARIABLES
The java.util.concurrent.atomic package defines classes that support atomic operations on single variables (ex. AtomicInteger). All classes have get and set methods that work like reads and writes on volatile variables. The atomic compareAndSet method also has these memory consistency features, as do the simple atomic arithmetic methods that apply to integer atomic variables.

References

Java: Handling Interrupts

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate. A thread can be interrupted by calling the threadObject.interrupt() on the thread object.
threadObject.interrupt();
In order for the interrupt to work, the thread object has to support interruption, i.e. The thread object should check for interruptions periodically, as shown below:
while(!interrupted()) {
doWork();
}
An interrupt does not force the thread to halt (except when the thread is in sleep or wait mode). As shown in the above piece of code, the thread has to check if it is interrupted and take appropriate action (most likely, cleanup and stop execution). There are two ways in which a thread can check if it is interrupted.
  • isInterrupted(): This is a non-static method that simply checks whether a thread is interrupted, and returns true or false.
  • interrupted(): This method (used in the above example) is a static method of the Thread class, which checks if the current thread is interrupted and clears the interrupted state of the thread.

Note: The interrupted state of a thread can be cleaned only by the that thread, no thread can clear the interrupted state of another thread.
While interrupting a thread does not affect it's normal execution (unless the thread is programmed to do so), a thread can also be interrupted by an InterruptedException thrown by the sleep or wait methods. This has to be handled in a proper way, since a thrown exception clears the interrupted state of the thread. InterruptedException is best handled in the following way:
try {
// do some work.
Thread.sleep(sleepTime);
}catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
The question arises, is when and how should interruptions be handled. Here are some general tips handling interruptions:
  • If the thread invokes methods that throw InterruptedException frequently, then it is better to catch the interrupted exception and set the interrupted state of the thread as shown above.
  • If your method blocks, it should respond to interruption, otherwise you must decide what interruption/cancellation means for your method, and make such behavior a part of your method's contract. In general, any method that performs a blocking operation (directly or indirectly), should allow that blocking operation to be cancelled with interrupt and should throw an appropriate exception (as sleep and wait do). If you're using channels, available with the new I/O API introduced in Java 1.4, the blocked thread will get a ClosedByInterruptException exception.
  • Never hide an interrupt by clearing it explicitly or by catching an InterruptedException and continuing normally as it prevents any thread from being cancellable when executing your code.
References

Sunday, 14 July 2013

Detecting Code Smells With Eclipse and CheckStyle

In a new article "Automation for the people: Continual refactoring" as a part of the "Automation for the people" series, Paul Duvall discusses the use of static code analysis tools to identify code smells and suggested refactorings. The article shows how to
  • Reduce conditional complexity code smells by measuring cyclomatic complexity using CheckStyle and providing refactorings such as Replace Conditional with Polymorphism
  • Remove duplicated code code smells by assessing code duplication using CheckStyle and providing refactorings such as Pull Up Method
  • Thin large class code smells by counting source lines of code using PMD (or JavaNCSS) and providing refactorings such as Extract Method
  • Wipe out too many imports code smells by determining a class's efferent coupling using CheckStyle (or JDepend) and providing refactorings such as Move Method
There's MoreThe following is a short list of static code analysis tools available for JavaThis post describes how to identify common code smells using CheckStyle and Eclipse. Checkstyle has a useful eclipse plugin. Installing the plugin is simple. In Eclipse Ganymede,
  1. Go to Help->Software Updates->Software Updates->Available Software
  2. Click on Add Site, and add http://eclipse-cs.sourceforge.net/update to the sites list
  3. Select the new site and click Install
Once CheckStyle plugin is install, running the tool is quite simple. Usage is well documented in the plugin site. The following are some Code smells which can be detected using Checkstyle, along with the suggested refactorings (from the "Smells to Refactorings Quick Reference Guide"). The description of the refactorings can be found at refactoring.com and refactoring to patterns catalog. The center column shows the CheckStyle configuration option in the plugin GUI.


Conditional complexityMetrics->Cyclomatic Complexity
  • Introduce Null Object
  • Move Embellishment to Decorator
  • Replace Condidtional Logic with Strategy
  • Replace State-Altering Conditionals with State
Duplicated codeDuplicates->Strict Duplicate Code
  • Chain Constructors
  • Extract Composite
  • Extract Method
  • Extract Class
  • Form Template Method
  • Introduce Null Object
  • Introduce Polymorphic Creation with Factory Method
  • Pull Up Method
  • Pull Up Field
  • Replace One/Many Distinctions with Composite
  • Substitue Algorithm
  • Unify Interfaces with Adapter
Long methodSize Violations->Maximum Method Length
  • Extract Method
  • Compose Method
  • Introduce Parameter Object
  • Move Accumulation to Collecting Parameter
  • Move Accumulation to Visitor
  • Decompose Conditional
  • Preserve Whole Object
  • Replace Conditional Dispatcher with Command
  • Replace Conditional Logic with Strategy
  • Replace Method with Method Object
  • Replace Temp with Query

Saturday, 13 July 2013

java.text.Collator for String Comparison

The String class doesn't have the ability to compare text from a natural language perspective. Its equals and compareTo methods compare the individual char values in the string. If the char value at index n in name1 is the same as the char value at index n in name2 for all n in both strings, the equals method returns true. The java.text.Collator class provides natural language comparisons. Natural language comparisons depend upon locale-specific rules that determine the equality and ordering of characters in a particular writing system.A Collator object understands that people expect "cat" to come before "Hat" in a dictionary. Using a collator comparison, the following code prints cat < Hat.
Collator collator = Collator.getInstance(new Locale("en", "US"));
int comparison = collator.compare("cat", "Hat");
if (comparison < 0) {
System.out.printf("%s < %s\n", "cat", "Hat");
} else {
System.out.printf("%s < %s\n", "Hat", "cat" );
}
For a detailed description and extra information refer to Strings - Core Java Technologies Technical Tips.

Thursday, 11 July 2013

The Strategy Pattern

The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. It is useful for situations where it is necessary to dynamically swap the algorithms used in an application. In Design Patterns, the authors define the Command pattern as:
Define a family of algorithms, encapsulate each one, and make them interchangeable.
Strategy lets the algorithm vary independently from clients that use it.
The Strategy pattern consists of a family of related algorithms behind a driver class called the Context. Either the client or the context select the which one of the algorithms to use for the given situation. The strategy pattern may be used in the following scenarios:
  • When you have many related classes that differ only in behavior. Strategy pattern provides a way to configure a class with one of many behaviors.
  • Strategy pattern can be used when you have different variants of an algorithm. Each variant can be encapsulated within a strategy.
  • An algorithm uses internal data structures that need not be exposed to the client.
  • A class defines many behaviors, which are selected by multiple conditional statements. Eliminate conditional statements by encapsulating each behaviour in a strategy.
Advantages of Strategy Pattern
  • Hierarchies of Strategy classes can be used to define a family of algorithms or behaviors for contexts to reuse.
  • Encapsulating the algorithm in separate Strategy classes lets you vary the algorithm independently of its context.
  • The Strategy pattern offers an alternative to conditional statements for selecting desired behavior. When different behaviors are Encapsulating different behaviours in different Strategy classes eliminates the need for conditional statements.
Drawbacks of Strategy pattern
  • A client must understand how Strategies differ to be able to select the right strategy. If possible, the context may be albe to this for you.
  • Strategy pattern increases the number of objects in an application.

Monday, 8 July 2013

Web Service Best Practices

Bobby Woolf at IBM has a list of articles with best practices for working with Web Services. Most of these links are IBM resources.
To these I'd just like to add Implementing REST Web Services: Best Practices and Guidelines, which I find useful for implementing REST based web services.

Sunday, 7 July 2013

The Java 5 for each loop

A new article on java.net, Nuances of Java 5.0 for-each loop, discusses the Java 5 for-each loop, in great detail. The article covers common programming errors when using the for-each loop, how the enhanced for-loop compares with the equivalent implementation with the regular for-loop, how to write new classes that can be used as targets of a for-each loop compiler optimizations of the for-each loop, and a lot more. Here is a list of the talking points:
  1. The for-each loop can handle only one iteration variable.
  2. Nested iterations are allowed.
  3. Iterating over varargs. Java 5.0 now allows a variable number of arguments of a single type to be passed in as the last parameter to a method. The compiler collects these varargs parameters into an array of that type. The for-each loop can be used to iterated over the varargs.
  4. Do not modify the list during iteration
  5. When appropriate, implement java.util.RandomAccess to allow for compiler optimizations
  6. Consider returning an Iterable rather than a List
  7. Consider returning Iterable views rather than implementing Iterable
  8. Return zero length arrays or empty lists rather than nulls

Thursday, 4 July 2013

Implementing Command Pattern in Java

The previous post described the Command pattern in brief. I listed out where and why the command pattern may be used. This post describes how to implement command pattern in Java and also some implementation considerations. The following is the UML diagram for command patternCommand Pattern UMLThe following is a simple description of each of the elements of the above diagram, followed by a simple implementation.
  • Client: The client is responsible for creating the Command object and setting it's reciever.
    public class ClientApp {
    public static void main(String[] args) {
    Receiver rec = new Receiver();
    Command incCommand = new IncrementCommand(rec);
    Command decCommand = new DecrementCommand(rec);
    Invoker invoker = new Invoker();
    invoker.setDecCommand(decCommand);
    invoker.setIncCommand(incCommand);
    invoker.addRequest();
    invoker.addRequest();
    invoker.removeRequest();
    System.out.println(rec.getValue());
    }
    }
    ClientApp.java
  • Invoker: The Invoker acts as a placeholder for the Command object and invokes the execute method on the Command. In case of undoable commands, it stores the command in a stack (for multi-level undo, or just the command for single level undo), before executing the command.
    public class Invoker {
    Stack<Command> commands;

    Command incCommand;

    Command decCommand;

    public Invoker() {
    commands = new Stack<Command>();
    }

    public void setIncCommand(Command command) {
    incCommand = command;
    }

    public void setDecCommand(Command command) {
    decCommand = command;
    }

    public void undoAll() {
    Command cmd = null;
    while (!commands.empty()) {
    cmd = commands.pop();
    cmd.undo();
    }
    }

    public void addRequest() {
    incCommand.execute();
    commands.add(incCommand);
    }

    public void removeRequest() {
    decCommand.execute();
    commands.add(decCommand);

    }

    public void commit() {
    commands = new Stack<Command>();
    }
    }
    Invoker.java
  • Receiver: The object that performs the operations associated with carrying out a request. Any class may serve as a Receiver.
    public class Receiver {
    private int value;

    public Receiver() {
    value = 0;
    }

    public void increment() {
    ++value;

    }

    public void decrement() {
    --value;
    }

    public int getValue() {
    return value;
    }

    }
    Receiver.java
  • Command: The command object represents the request operation. The command implements execute() method, which invokes the corresponding operations on the Reciever. This defines a binding between a Receiver object and an action.
    public interface Command {
    public void execute();
    public void undo();
    }
    Command.java
    public class IncrementCommand implements Command {

    Receiver receiver;

    public IncrementCommand(Receiver rec) {
    receiver = rec;
    }

    public void execute() {
    receiver.increment();

    }

    public void undo() {
    receiver.decrement();
    }

    }
    IncrementCommand.java
    public class DecrementCommand implements Command {

    Receiver receiver;
    public DecrementCommand(Receiver receiver) {
    this.receiver = receiver;
    }

    public void execute() {
    receiver.decrement();
    }

    public void undo() {
    receiver.increment();
    }
    }
    DecrementCommand.java

Additional Notes
  • A command can have a wide range of abilities from a simple interface between the client and receiver to being a receiver itself.
  • When supporting multi-level undo, a command may store state information, which mean that, with each execute(), you have to copy the state of the command at that time. In such cases a copy of the command has to be added to the history stack.

The Command Pattern

The Command pattern is probably the most used design pattern. In command pattern, objects are used to represent actions. This allows you to issue requests to objects without knowing anything about the operation being
requested or the receiver of the request. The command object can act as an interface between the client and the reciever. In Design Patterns, the authors define the Command pattern as:
Encapsulate a request as an object,
thereby letting you parameterize clients with different requests,queue or log requests, and support undoable operations.
Note that, the undoable is actually undo-able and not un-doable. Using the command pattern helps you to :
  • Decouple the object that invokes the operation from the one that performs the action.
    described earlier.
  • Assemble commands into a composite command. An example is the MacroCommand class. Composite commands are an instance of the Composite pattern.
  • Add new Commands, without having to change existing classes.
The following is a list of scenarios where the command pattern may be put to use.
  • Improve API design: In some cases, code that uses a command object is shorter, clearer, and more declarative than code that uses a procedure with many parameters. This is particularly true if a caller typically uses only a handful of the parameters and is willing to accept sensible defaults for the rest.
  • A command object is a temporary storage for procedure parameters. It can be used while assembling the parameters for a function call and allows the command to be set aside for later use.
  • A class is a convenient place to collect code and data related to a command. A command object can hold information about the command, such as its name or which user launched it; and answer questions about it, such as how long it will likely take.
  • Treating commands as objects enables data structures containing multiple commands (Macro commands).
  • Multi-level undo: The Command's Execute operation can store state for reversing its effects in the command itself, there by allowing you implement the undo action. By storing the the list of commands executed seperately, multi-level undo can be achieved.
  • Transactional behaviorUndo is perhaps even more essential when it's called rollback and happens automatically when an operation fails partway through. Installers need this. So do databases. Command objects can also be used to implement two-phase commit.
  • Progress barsSuppose a program has a sequence of commands that it executes in order. If each command object has a getEstimatedDuration() method, the program can easily estimate the total duration. It can show a progress bar that meaningfully reflects how close the program is to completing all the tasks.
  • GUI buttons and menu items: In Swing programming, an Action is a command object. In addition to the ability to perform the desired command, an Action may have an associated icon, keyboard shortcut, tooltip text, and so on.
  • Queuing Requests: A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. The items in the queue are command objects.
  • Logging Requests: If all user actions are represented by command objects, a program can log a sequence of actions by keeping a list of the command objects that are executed. In case of a system failure, the program can execute the same sequence of events.
  • Wizards: Often a wizard presents several pages of configuration for a single action that happens only when the user clicks the "Finish" button on the last page. In these cases, a natural way to separate user interface code from application code is to implement the wizard using a command object. The command object is created when the wizard is first displayed. Each wizard page stores its GUI changes in the command object, so the object is populated as the user progresses. "Finish" simply triggers a call to execute(). This can be seen as a special case of Queuing requests.
  • Networking: It is possible to send whole command objects across the network to be executed on the other machines, for example player actions in computer games.

Monday, 1 July 2013

Using Displaytag with tiles

If you run the example in the previous post, with each click on the related table you will see that the URL has changed to reflect that of the JSP
http://localhost:8090/StrutsPaging/pages/search.jsp?d-3999332-p=2
This may cause problems when using Struts with tiles. In order to avoid the problem you have to change add a new attribute to the display:* tag
requestURI=""
In the JSP file in step 2 of "Struts: Paging and Sorting with Displaytag", change the display:table tag, change the tag to look as shown below:
<display:table name="sessionScope.empList" pagesize="4" id="empTable" sort="external" defaultsort="1" defaultorder="ascending" requestURI="">
Now, the URL appears as shown below
http://localhost:8090/StrutsPaging/search.do?d-3999332-o=2&d-3999332-s=empName&d-3999332-p=1&d-3999332-n=1
This solution in mentioned in the displaytag FAQ page(Had to dig a little to find it :) ). Once you have done this, you can safely use it with tiles too.

LinkWithin

Related Posts Plugin for WordPress, Blogger...