Search
Calendar
September 2017
S M T W T F S
« Sep    
 12
3456789
10111213141516
17181920212223
24252627282930
Your widget title
Archives

Posts Tagged ‘Java’

PostHeaderIcon How to access non-visible fields in Java?

How to access a non-acccessible field (either protected, package-protected or private) of an object in Java?

For instance, you would like to access the field threads of ThreadGroup:

ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
final Field privateThreadsField;
privateThreadsField = ThreadGroup.class.getDeclaredField("threads");
privateThreadsField.setAccessible(true);
threads = (Thread[]) privateThreadsField.get(threadGroup);

PostHeaderIcon How to include a dependency to tools.jar in Maven?

Case

You need include tools.jar as a dependency in a pom.xml, for instance in order to use Java 5’s annotations and APT. From a “Maven’s view point”, tools.jar is not a regular JAR defined by a groupId and artefactId.

Solution

Add this block in your pom.xml:

<dependency>
    <groupId>com.sun</groupId>
    <artifactId>tools</artifactId>
    <version>1.6.0_24</version>
    <scope>system</scope>
    <systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>

(You can also add it in your settings.xml)

You can do the same for any other “non-regular” JAR, available in your file system.

PostHeaderIcon javac: invalid flag: -s

Case

After updating my project and launching a build with Maven, I got this error:

[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Compilation failure
Failure executing javac, but could not parse the error:
javac: invalid flag: -s
Usage: javac <options> <source files>

Fix

Indeed the version of Java in the pom.xml had been upgraded. To get rid of the error, update your $JAVA_HOME to use a JDK 6 and no more a JDK5.

PostHeaderIcon WebLogic: use a startup and/or a shutdown class in a WAR

Abstract

WebLogic offers you to specify a startup and/or a shutdown class for an application. Anyway, this feature is restrained to EARs, and is not available for applications deployed as WARs. For EARs, Oracle WebLogic Server’s documentation is complete and gives basic examples: Programming Application Life Cycle Events

Yet, sometimes you need such a class even for a WebApp. You have two ways to handle this case.

Solutions

Full Weblogic!

Base

The first solution is not elegant. Open WebLogic console, go to Startup And Shutdown Classes, then add the classes names of which main() methods will be run on startup and shutdown, let’s say JonathanWeblogicStartup. These classes must be available in WebLogic classpath, which is surely different from your application classpath, eg in a library $DOMAIN_HOME/lib/customized-weblogic.jar.
Advantage of this means: if your startup/shutdown class does not evoluate often, then write it once and forget, it will be OK. Unlike, you will have to manage different versions of the JAR on each release… I assume your exploitation team may get angry at playing with classpaths and lib folders 😀

Suggestion

To improve the basic solution (and avoid your exploitation guy burst in your office), I had the following idea, that I did not experiment, but that should work:

  • Keep JonathanWeblogicStartup
  • Create another class JonathanConcreteStartup, locate as a source in your application code.
  • In JonathanStartup.main(), call JonathanConcreteStartup

This way,

  1. You keep a unique JAR in classpath that you do not need to update and you can forget.
  2. You can add, update or remove features in your very source code.
  3. The exploitation teams does not become hateful at you.

Add a Listener

The second one requires a bit more work.

  • Create a class implementing javax.servlet.ServletContextListener interface, let’s say MyLifecycleListener.
  • Implement methods contextInitialized() and contextDestroyed().
  • Edit your web.xml, add the following block:
      <listener>
            <listener-class>lalou.jonathan.MyLifecycleListener</listener-class>
        </listener>
  • Rebuild and deploy. It should be OK

PostHeaderIcon Tutorial: an Event Bus Handler for GWT / GXT

Overview

Introduction

Let’s consider a application, JonathanGwtApplication, divided in three main panels

  • a panel to select animal name name
  • a panel to display, expand and collapse trees of the animal ancestors
  • a panel of information to display many indicators (colors, ages, etc.).

An issue we encounter is: how to make the different panels communicate? In more technical terms, how to fire events from a panel to another one?

A first solution would be to declare each panel as listener to the other panels. Indeed, this principle may go further, and declare each component as listener to a list of other components…
Main drawbacks:

  • the code becomes hard to read
  • adding or removing a component requires to modify many parts of the code
  • we don’t follow GWT 2’s “philosophy”, which is to use Handlers rather than Listeners.

Hence, these reasons incited us to provide a global EventBusHandler.

The EventBusHandler concept

The EventBusHandler is a global bus which is aware of all events that should be shared between different panels, and fires them to the right components.
The EventBusHandler is a field of JonathanGwtApplicationContext.

Intrastructure

  • lalou.jonathan.application.web.gwt.animal.events.HandledEvent: generic interface for a event. Abstract method:
    EventTypeEnum getEventEnum();
  • lalou.jonathan.application.web.gwt.animal.handler.EventHandler: generic interface for a component able to handle an event. Abstract method:
    void handleEvent(HandledEvent handledEvent);
  • lalou.jonathan.application.web.gwt.animal.handler.EventHandlerBus: the actual bus. As a concrete class, it has two methods:
    /**
    	 * Fires an event to all components declared as listening to this event
    	 * event type.
    	 *
    	 * @param baseEvent
    	 */
    	public void fireEvent(HandledEvent baseEvent) {
                   // ...
    	}
    
    	/**
    	 * Adds an listener/handler for the event type given as parameter
    	 *
    	 * @param eventTypeEnum
    	 * @param eventHandler
    	 * @return The List of handlers for the key given as parameter. This list
    	 *         contains the eventHandler that was given as second parameter
    	 */
    	public List<EventHandler> put(EventTypeEnum eventTypeEnum,
    			EventHandler eventHandler) {
                  // ...
            }

How to use the bus?

  1. Define an event: in JonathanGwtApplication, an event is decribed by two elements:
    • a functionnal entity: eg: “animal”, “food”, “tree node”. The functionnal entity must be isomorph to a technical DTO, eg: AnimalDTO for an entity Animal.(in the scope of this turoriel we assume to have DTOs, even though the entities may ne sufficient)
    • a technical description of the event: “selection changed”, “is expanded”
  2. Add an entry in the enum EventTypeEnum. Eg: “ANIMAL_SELECTION_CHANGED
  3. in lalou.jonathan.application.web.gwt.animal.events, create an event, implementing HandledEvent and its method getEventEnum(). The match between EventTypeEnum and DTO is achieved here. Eg:
    public class AnimalSelectionChangedEvent extends
    		SelectionChangedEvent<AnimalDTO> implements HandledEvent {
    
    	public AnimalSelectionChangedEvent(
    			SelectionProvider<AnimalDTO> provider,
    			List<AnimalDTO> selection) {
    		super(provider, selection);
    	}
    
    	public EventTypeEnum getEventEnum() {
    		return EventTypeEnum.ANIMAL_SELECTION_CHANGED;
    	}
    
    }
  • When an event that should interest other component is fired, simply call the bus. The bus will identify the event type and dispatch it to the relevant handlers. eg:
    animalComboBox.addSelectionChangedListener(new SelectionChangedListener<AnimalDTO>() {
    
    			@Override
    			public void selectionChanged(SelectionChangedEvent<AnimalDTO> se) {
    				final AnimalDTO selectedAnimalVersion;
    				selectedAnimalVersion= se.getSelectedItem();
    				JonathanGwtApplicationContext.setSelectedAnimal(selectedAnimal);
    
    						final AnimalSelectionChangedEvent baseEvent = new AnimalSelectionChangedEvent(
    								se.getSelectionProvider(), se.getSelection());
    						JonathanGwtApplicationContext.getEventHandlerBus()
    								.fireEvent(baseEvent);
    
    			}
    		});
  • Handlers:
    • easy case: the component handles only one type of event: this handler must implement the right interface (eg: AnimalSelectionChangedEventHandler) and its method, eg:
      protected void handleAnimalSelectionChangedEvent(HandledEvent handledEvent) {
          return;
      }
    • frequent case: the component handles two or more event types. No matter, make the component implement all the needed interfaces (eg: AnimalSelectionChangedEventHandler, FoodSelectionChangedEventHandler). Provide a unique entry point for the method to implement, which is common to both interfaces. Retrieve the event type, and handle it with ad hoc methods. Eg:
      public void handleEvent(HandledEvent handledEvent) {
      		final EventTypeEnum eventTypeEnum;
      
      		eventTypeEnum = handledEvent.getEventEnum();
      
      		switch (eventTypeEnum) {
      		case ANIMAL_SELECTION_CHANGED:
      			handleAnimalSelectionChangedEvent(handledEvent);
      			return;
      		case FOOD_SELECTION_CHANGED:
      			handleFoodSelectionChangedEvent(handledEvent);
      			return;
      		default:
      			break;
      		}
      	}
      
      	protected void handleAnimalSelectionChangedEvent(HandledEvent handledEvent) {
      		// do something
              }
      	protected void handleFoodSelectionChangedEvent(HandledEvent handledEvent) {
      		// do something else
              }