Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, July 09, 2009

Scaling Java Applications

The latest episode from the guys at Java Posse provided an interesting insight into scaling large Java web applications.

Here are just a few of the technologies and concepts discussed which I should find the time to explore...

Terracotta

  • Open source JVM-level clustering software for Java which clusters the JVM underneath the application rather than clustering the application itself

memcached

  • Distributed memory object caching system with a second level cache available for Hibernate (hibernate-memcached)

Database Sharding

  • A "shared-nothing" partitioning scheme for large databases across a number of servers

Tuesday, June 23, 2009

RESTful Web Services

Enjoyed reading the first of Bruce Sun’s developerWorks series on A multi-tier architecture for building RESTful Web Services today…looking forward to future episodes which promise to include a tutorial bringing together REST Web Services, Spring Web Flow and Jersey, all of which have been on my learning list for a few years now and may finally make it to the top.

Tuesday, June 16, 2009

Programming Principles

After catching up on more of the insightful Neal Ford's evolutionary architecture and emergent design series, it got me thinking about the principles that an intermediate to advanced level programmer should be aware of. These thoughts have led this attempt to compose a (WIP) list of the terminology and generic patterns a competent developer should be able to explain:

Composed Method / Single Level of Abstraction Principle (SLAP) / Refactoring
  • An understanding of the need to divide your programs into methods that perform one identifiable task resulting in programs with many small methods each a few lines long and responsible for one and only one thing. Operations in a method should be kept at the same level of abstraction. For example avoiding the introduction of methods which deal with both low-level technical details e.g. database infrastructure and high-level domain logic. As a rule of thumb any Java method longer than about 10 lines of code is a candidate for refactoring because it probably does more than one thing.

Single Responsibility Principle / Separation of Concerns (SoC) / Encapsulation / Information Hiding / Principle of Least Privilege / Law of Demeter (LoD)

  • Classes and methods should have a single responsibility or reason for change, as you move up the design layers responsibilities become increasingly abstract. In Java concerns should overlap in functionality as little as possible through use of MVC or AOP. Also each layer should only be able to access the other layers necessary to fulfill its responsibilities.

Don't Repeat Yourself (DRY) / Copy-and-Paste Programming / Once And Only Once (OAOO)

  • Code should not be duplicated with each and every declaration of behavior appearing OAOO as it increases the difficulty of change, decreases clarity and leads to opportunities for inconsistency.

Coupling / Composition vs. Inheritance / Inversion of Control (IoC)

  • Avoiding tight coupling through the use of composition rather than introducing dependencies via inheritance which you will need to decouple later and usage of IoC to decouple execution from implementation. An explanation of expected understanding of dependencies is available here.

Design Patterns

  • It is unrealistic to expect someone to hold detailed knowledge of all Design Patterns (I hope!) whether they be the original GoF, J2EE, Enterprise or SOA patterns. However, an understanding of the architectural concepts behind design patterns and the ability to explain a handful of examples such as Singleton, Lazy Initialisation, Factory, Decorator etc. is desirable.

Big Requirements/Design Up Front (BRUF/BDUF) / Analysis Paralysis / You Aren't Gonna Need It (YAGNI) / Technical Debt

  • The trade-off of attempting to complete and perfect a design before the implementation has begun through up front planning against remaining adaptable to changing requirements.

Monday, February 09, 2009

Java Web Application Testing

My toolkit:
Some advice on a strategy: Performance Testing Guidance for Web Applications

Wednesday, October 29, 2008

Apache Qpid / AMQP

Qpid provides a multiple language implementation of the Advanced Message Queuing Protocol (AMQP) specification and related technologies. Client APIs include C++, Java, Ruby, Python and C# for .NET. In addition a JMS API is provided for Java making typical JMS use cases easy.
Qpid provides transaction management, queuing, distribution, security, management and heterogeneous multi-platform support.

Thursday, July 10, 2008

Java Final Arguments

When should I declare method parameters as final?
  • This prevents the parameter from being reassigned but does not make it immutable
  • It is mandatory to make the parameter available to anonymous inner classes
 UnaryOperator bind ( final BinaryOperator binOp, final Object boundLeftArg) {
return new UnaryOperator() {
public Object apply(Object arg) {
return binOp.apply(boundleftArg, arg);
}
};
}
See: http://c2.com/cgi/wiki?JavaFinalArguments

Tuesday, July 08, 2008

EJB3 vs Hibernate vs TopLink vs JDO

What should be the preferred choice for O/R mapping...?

See: The EJB 3.0 Hibernate Fallacy

These frameworks provide similarly common features:

EntityManager - A transaction-level artifact that references, maintains identity and manages the objects in a given transaction. JDO calls this a PersistenceManager, Hibernate calls this a Session. TopLink calls this a UnitOfWork. These are all very close in scope, purpose and API.

Named queries - Queries must be able to be pre-defined and bound to a name for later retrieval and execution. These are called named queries in all of TopLink, Hibernate and JDO.

Native queries - Native SQL queries that allow the application to specify the query criteria in SQL. These are called SQL queries in all of TopLink, Hibernate and JDO.

Callback Listeners - The ability to define a class or method that will get invoked when a given event occurs. TopLink calls these event listeners, Hibernate and JDO call them life cycle callbacks.

Detaching/Reattaching objects - Objects can leave the scope of the EntityManager that controls them. They can also be reattached to the same or a different EntityManager through the use of the merge API call on the EntityManager. TopLink offers a series of merge calls, the most basic one being mergeClone. Hibernate has saveOrUpdateCopy and JDO has a couple of flavours of attachCopy call on the PersistenceManager.

O/R Mapping Types - All of the direct and relationship mapping types that are fundamental to mapping object state to relational database tables. These are all supported by Hibernate, TopLink and JDO. I won't go through all of the names (one-to-one, etc.. they are all pretty standard), but although some of the names differ a little bit from one to the other the functionality is pretty much the same and what you would expect.

Embedded Objects - Objects that have no persistent identity of their own but depend upon their parent object for identity. JDO calls them embedded objects, TopLink calls them aggregates and Hibernate calls them components.

Sunday, July 06, 2008

XML Best Practices

  • Always provide an XSD for validation, code-completion and auto-generation of XML
  • Do not use elements that only contain attributes as they are difficult to parse and extend
  • Always declare the character encoding and use UTF-8 unless there is a good reason why not
  • Use structures instead of delimiting fields within elements
  • Wrap repeated elements in parents to make them more human-readable
  • Do not repeat element names in different contexts
  • Do not unnecessarily abbreviate element and attribute names
See: http://java.dzone.com/articles/crimes-against-xml

Friday, July 04, 2008

Generics Wildcards

Wildcards are useful with generics because they are not covariant unlike arrays. For example an array of Integer is also an array of Number, but a generic List of Integer is not a generic List of Number.

Upper-bound wildcards place an upper bound on the type: ? extends T
Lower-bound wildcards place a lower bound on the type: ? super T

The get-put principle acts as a reminder of which wildcard to use:
"Use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don't use a wildcard when you do both."

An example using both upper and lower-bound wildcards:
public static<T> void copy(
Box<? extends T> from,
Box<? super T> to) {
to.put(from.get());
}
See: Java theory and practice: Going wild with generics

Thursday, July 03, 2008

Typical JEE Project & Package Structure

Here is a typical structure for the Project and Packages of a JEE Web App:


Presentation Layer (Web project)
  • contains the UI e.g JSF pages and beans etc
  • only able to access the implementation of the project via the Control project
  • actions ('do' methods) are used to trigger use cases
  • does not contain any logic or calculations to remain swappable with an alternative UI
Business Layer (Control)

  • contains the transactional business logic operations whose pre-conditions are validated
    encapsulates any 'finder' methods required by the Web project
  • communicates with the Service project for CRUD operations
Persistence Layer (Service)
  • services all operations on persisted data using ORM mapping
    contains no business logic
Domain Layer (Common)
  • does not contain any methods other than those provided by the utils package
  • domain objects simply represent state and are passed through the layers of the system
  • the project is likely exported as a JAR file in a UML-Java transaformation to force any updates to change the domain model

Throw an Exception if Not Found

    /**
* Typical DAO/Service layer finder method.
* If unable to find the Object from the ID,
* throw an Exception instead of returning null.
*/
public Object findById(BigDecimal id)
throws NotFoundException, FindException {
try {
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
Object obj = new Object();
// populate the object...
return obj;
}
// throw a runtime exception instead of returning a null object
throw new NoSuchElementException("Object not found for ID: " + id);
} catch (SQLException e) {
throw new FindException(e);
}
}

See: Diagnosing Java Code: The Null Flag bug pattern

Thursday, June 26, 2008

Private Constructors

Prevent your generic 'Utils' classes from being instantiated:
/**
* Template for a Utils class full of Static methods.
* Declare the class as Final so it cannot be subclassed.
*/
public final class MyUtils {

/**
* Provide a Private constructor to prevent instantiation.
*
* Use Assertions (if enabled) or throw an Error in case of
* an attempt is made to instantiate within the class itself.
*/
private MyUtils() {
assert false;
// OR
throw new AssertionError();
}

}

Apache Logging - log4j Configuration

Add the log4j.xml file to the classpath:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "http://logging.apache.org/log4j/docs/api/org/apache/log4j/xml/log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

<!-- an appender is an output destination, such as e.g. the console or a file;
names of appenders are arbitrarily chosen -->
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
<!-- layouts are used by appenders to format layout -->
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"

value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />
</layout>

</appender>
<appender name="debug" class="org.apache.log4j.FileAppender">
<param name="File" value="logs/debug.log" />
<param name="Threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{ISO8601} %-5p %c - %m%n"/>
</layout>
</appender>


<!-- the root category -->

<root>
<!-- all|debug|info|warn|error|fatal|off|null -->
<!-- all log messages of level debug or more serious will be logged, unless defined otherwise -->
<priority value="debug" />
<appender-ref ref="stdout" />
<appender-ref ref="debug"/>
</root>

</log4j:configuration>

Lazy load the logger:
    /**
* @return the log.
*/
protected Log getLog() {
if (this.log == null) {
this.log = LogFactory.getLog(this.getClass());
}
return this.log;
}

Use the logger:
        if (getLog().isInfoEnabled())
getLog().info("Hello World!");

http://logging.apache.org/

Monday, March 03, 2008

Service Component Architecture (SCA)


"A set of specifications which describe a model for building applications and systems using a Service-Oriented Architecture. SCA extends and complements prior approaches to implementing services, and SCA builds on open standards such as Web services."

Concepts:

  • Component - general term for a configured implementation of an SCA application
  • Composite - larger structure composed of several components
  • SCDL - Service Component Definition Language used for composite configuration files
  • Domain - container for components and composites
  • Service - exposes a components business logic
  • Reference - used by a component to indicate the services it relies on
  • Property - an instantiated component value which can be read from the SCDL configuration
  • Binding - specifies how components communicate with other software

Supported by BEA, IBM, Oracle, SAP AG, Red Hat, Sun, TIBCO and others.

Implementations:

See: OSOA Service Component Architecture Project

Tuesday, February 19, 2008

JAX-RPC Compliance

The following types are supported by JAX-RPC:
  • Primitives - boolean, byte, short, int, long, float, and double
  • Classes - String, Date, Calendar, BigInteger, BigDecimal, QName, and URI
  • Arrays of the above
  • Exceptions extending java.lang.Exception

Also a class which complies with the following:

  • Has a public default constructor
  • Does not implement java.rmi.Remote (directly or indirectly)
  • Its fields are also compliant and have getter and setter methods

Part 2: Validate Java classes for compliance to JAX-RPC

Monday, February 18, 2008

JAX-RS (JSR 311)

JAX-RS:
  • Standard API for RESTful Web Services in Java
  • Annotations are applied to POJO's to provide RESTful services
  • Planned for inclusion in Java EE 6
REpresentational State Transfer:
  • global resources are identified by URI's
  • clients & servers communicate using standard communications protocol e.g. HTTP
  • provides lightweight alternative to SOAP by transmitting directly over HTTP (no XML)

Key Concepts:

  • Resource - provide access to an individual resource
  • Representation - the state of a Resource
  • Addressability - each Resource has one address, its URI
  • Connectedness - web apps contain many URI's connected to each other
  • Uniform Interface - the interface is the same for any URI
  • Statelessness - web app does not maintain the state of clients (no HTTP sessions)

JSR 311: JAX-RS: The JavaTM API for RESTful Web Services
Implementing RESTful Web Services in Java

Friday, January 18, 2008

Cookies in JSF

  // create cookies
HttpServletResponse httpServletResponse =
(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
Cookie cookie = new Cookie("cookieKey", "cookieValue");
cookie.setMaxAge(365);
cookie.setComment("A Comment");
httpServletResponse.addCookie(cookie);

// get cookies
HttpServletRequest httpServletRequest =
(HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
Cookie[] cookies = httpServletRequest.getCookies();
if (cookies != null) {
for(int i=0; i<cookies.length; i++){
if (cookies[i].getName().equalsIgnoreCase("cookieKey")){
String cookieValue = cookies[i].getValue();
}
}
}

Homemade WebSphere LDAP Authentication

import java.util.HashSet;
import java.util.Set;

import javax.faces.context.FacesContext;
import javax.security.auth.login.AccountExpiredException;
import javax.security.auth.login.CredentialExpiredException;
import javax.security.auth.login.FailedLoginException ;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;

import com.ibm.websphere.security.auth.callback.WSCallbackHandlerImpl;
import uk.org.gth.exceptions.LoginException;

public class LoginUtils {

public static void doLogin(String username, String password, FacesContext facesContext)
throws LoginException {
LoginContext loginContext = null;

try {
loginContext = new LoginContext("WSLogin", new WSCallbackHandlerImpl(username, password));
loginContext.login();
} catch (AccountExpiredException e) {
throw new LoginException("Account has Expired.");
} catch (CredentialExpiredException e) {
throw new LoginException("Credentials have Expired.");
} catch (FailedLoginException e) {
throw new LoginException("Login Failure.");
} catch (LoginException e) {
if (e.getMessage().indexOf("52e") > 0) {
throw new LoginException("Invalid Password.");
} else if (e.getMessage().indexOf("532") > 0) {
throw new LoginException("Password Has Expired.");
} else if (e.getMessage().indexOf("533") > 0) {
throw new LoginException("Your account has been disabled.");
} else if (e.getMessage().indexOf("701") > 0) {
throw new LoginException("Your account has expired.");
} else if (e.getMessage().indexOf("773") > 0) {
throw new LoginException("Your password must be reset.");
} else {
throw new LoginException(e.getMessage());
}
} catch (SecurityException e) {
throw new LoginException("Cannot create LoginContext.");
}
}

}

Saturday, January 05, 2008

Project Woodstock

Project Woodstock participants are developing the next generation of User Interface Components for the web, based on Java Server Faces and AJAX. This open source collaboration enables a community of developers to create powerful and intuitive web applications that are accessible and localizable, and which are based on a uniform set of guidelines and components, to help ensure ease of development and ease of use.

Vision: Project Woodstock is devoted to providing the best possible web application experience for our customers and communities. That experience will certainly be greatly enriched by the interaction of ideas, information, and techniques that emerge from the cooperation of individuals in the web community, and the rapid introduction of new technologies by members of that community.

Project Woodstock
JSFTemplating and Woodstock: Component Authoring Made Easy