GlassFish 3.1 to JBoss AS 7.1.1 EJB Invocation


This post demonstrates how to call a remote EJB deployed to JBoss AS 7.1.1 standalone server from an application deployed to GlassFish 3.1.x. It is similar to the standalone Java client connecting to JBoss AS 7.1.1, except that the remote client is running inside another application server product (GlassFish). The complete project is available in github: glassfish-calling-jboss.

The following is some steps and noteworthy points.

1, configure and start JBoss 7.1.1 standalone server (in a new terminal):
cd $JBOSS_HOME/bin
./standalone.sh
# in a new terminal/tab, or split it
# username: test
# password: 1234
./add-user.sh
2, configure and start GlassFish 3.1.x:
cd $$GLASSFISH_HOME/bin
./asadmin start-domain
./asadmin create-jvm-options -Dcom.sun.enterprise.naming.allowJndiLookupFromOSGi=false

cp $JBOSS_HOME/bin/client/jboss-client.jar $GLASSFISH_HOME/domains/domain1/lib/ext/
cp project-root/client-on-glassfish/src/main/resources/jboss-ejb-client.properties $GLASSFISH_HOME/domains/domain1/lib/classes/
./asadmin restart-domain
The com.sun.enterprise.naming.allowJndiLookupFromOSGi option is needed to disable the use of javax.naming.spi.InitialContextFactoryBuilder in GlassFish, which customizes its jndi bootstrapping. Since this configuration is jvm wide, we need to disable it to avoid any interference with JBoss jndi initialization inside GlassFish.

jboss-client.jar is copied to GlassFish domain lib/ext to provide the JBoss client-side ejb and naming funcionality. jboss-ejb-client.properties is also copied to GlassFish domain lib/classes dir so that it share the same classloader as jboss-client.jar.

jboss-ejb-client.properties inside the application should be sufficient. It is also copied in the above step to ensure it is always available to jboss client inside GlassFish. jboss-ejb-client.properties packaged inside the client ejb jar will be loaded by GlassFish application classloader, while jboss client-side runtime classes are loaded by GlassFish common classloader. So jboss client-side may not be able to load jboss-ejb-client.properties, especially if it uses its current classloader for resource loading.

If you see the following error, it means jboss-ejb-client.properties is not loaded:
Tests in error:
invokeClientBean(com.blogspot.javahowto.ClientBeanTestIT):
javax.naming.NameNotFoundException:
ejb:/service-on-jboss/ServiceBean!com.blogspot.javahowto.ServiceIF -- service jboss.naming.context.java.jboss.exported.ejb:.service-on-jboss."ServiceBean!com.blogspot.javahowto.ServiceIF"
3, build and run the project:
cd project-root
mvn clean install

...

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.blogspot.javahowto.ClientBeanTestIT
May 18, 2012 2:00:37 PM com.sun.enterprise.v3.server.CommonClassLoaderServiceImpl findDerbyClient
INFO: Cannot find javadb client jar file, derby jdbc driver will not be available by default.
Look up ClientBean by name java:global/client-on-glassfish/ClientBean, got com.blogspot.javahowto._ClientIF_Wrapper@3735f04a
Result from clientBean.clientHello(): In serviceHello of com.blogspot.javahowto.ServiceBean@3e9c66de

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 14.354 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

There is no transaction context or security context propagation during the remote invocation. If you need them, another approach is to use IIOP protocol and the interoperable naming service. But that requires EJB on both sides to expose 2.x-style remote home interface even for EJB 3 beans. Topic for another day.

Standalone Java Client for JBoss AS 7.1.1: Maven and JUnit Edition

In previous post, Standalone Java Client for JBoss AS 7.1.1, I showed a hand-written project of standalone client in JBoss AS 7. In this post, I will rewrite it as a maven project with JUnit and jboss-as-maven-plugin. The result is project jboss-as-7-client at github.

The steps are slightly different than the handwritten edition:

1, start JBoss AS and add users:
cd $JBOSS_HOME
./standalone.sh
./add-user.sh (user name: test, password: 1234)


2, "mvn clean install" will build the project, package and deploy the ejb jar to JBoss AS 7, and run the standalone client test.

3, if the ejb jar is already deployed in JBoss AS, step 2 will forcefully overwrite it. If you want to undeploy the ejb jar, run
mvn jboss-as:undeploy

Standalone Java Client for JBoss AS 7.1.1

In this previous post, I created a sample Java standalone client connecting to JBoss AS 5 & 6. Now let's look at how to do it in JBoss AS 7.1.1.

This sample application consists of a stateless EJB, its remote business interface and a standalone java client that looks up the EJB and invokes its business method.
ClientIF.java
package test;

public interface ClientIF {
public String clientHello();
}
ClientBean.java
package test;
import javax.ejb.*;

@Stateless
@Remote
public class ClientBean implements ClientIF {
public String clientHello() {
return "In clientHello of " + this;
}
}
Client.java
package test;

import javax.naming.*;

public class Client {
public static void main(String args[]) throws Exception {
ClientIF clientBean = InitialContext.doLookup(args[0]);
System.out.printf("Result from clientBean.clientHello(): %s%n%n",
clientBean.clientHello());
}
}
In addition, you also need to prepare a jndi.properties file, and a jboss-ejb-client.properties file, both should be in the client classpath:
# jndi.properties
#
java.naming.factory.initial=org.jboss.naming.remote.client.InitialContextFactory
java.naming.factory.url.pkgs=org.jboss.ejb.client.naming
java.naming.provider.url=remote://localhost:4447
java.naming.security.principal=test
java.naming.security.credentials=1234
# jboss-ejb-client.properties
#
endpoint.name=client-endpoint
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false

remote.connections=default

remote.connection.default.host=localhost
remote.connection.default.port = 4447
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false

remote.connection.default.username=appuser
remote.connection.default.password=apppassword

With the above 5 source and config files in place, the project structure looks like this:
jboss-ejb/
.........jndi.properties
.........jboss-ejb-client.properties
.........test/
.............ClientIF.java
.............ClientBean.java
.............Client.java
While in project root directory, compile and package the ejb jar:
javac -cp $JBOSS_HOME/bin/client/jboss-client.jar test/*java
jar cvf client-ejb.jar test/ClientIF.class test/ClientBean.class
If JBoss AS is not already running, start it in a new terminal, and add the application user referenced in the above jndi.properties (add-user.sh is an interactive script). When prompted, enter user name test and password 1234.
cd $JBOSS_HOME/bin
./standalone.sh

./add-user.sh
To deploy the ejb jar, simply copy it to JBoss AS deploy directory:
cp client-ejb.jar $JBOSS_HOME/standalone/deployments/
Finally, run our standalone Java client that looks up and invokes the remote EJB:
java -cp $JBOSS_HOME/bin/client/jboss-client.jar:. test.Client ejb:/client-ejb//ClientBean\!test.ClientIF

May 11, 2012 10:21:16 PM org.xnio.Xnio <clinit>
INFO: XNIO Version 3.0.3.GA
May 11, 2012 10:21:16 PM org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.0.3.GA
May 11, 2012 10:21:16 PM org.jboss.remoting3.EndpointImpl <clinit>
INFO: JBoss Remoting version 3.2.3.GA
May 11, 2012 10:21:17 PM org.jboss.ejb.client.EJBClient <clinit>
INFO: JBoss EJB Client version 1.0.5.Final
May 11, 2012 10:21:17 PM org.jboss.ejb.client.remoting.VersionReceiver handleMessage
INFO: Received server version 1 and marshalling strategies [river]
May 11, 2012 10:21:17 PM org.jboss.ejb.client.remoting.RemotingConnectionEJBReceiver associate
INFO: Successful version handshake completed for receiver context EJBReceiverContext{clientContext=org.jboss.ejb.client.EJBClientContext@53f64158, receiver=Remoting connection EJB receiver [connection=Remoting connection <a995a79>,channel=jboss.ejb,nodename=m-2]} on channel Channel ID bc3ed9ca (outbound) of Remoting connection 2e00e753 to localhost/127.0.0.1:4447
May 11, 2012 10:21:17 PM org.jboss.ejb.client.remoting.ChannelAssociation$ResponseReceiver handleMessage
WARN: Unsupported message received with header 0xffffffff
Result from clientBean.clientHello(): In clientHello of test.ClientBean@4783165b
The client class does a generic lookup, taking lookup jndi name from application arg. In the above java command line, ejb:/client-ejb//ClientBean!test.ClientIF is the jndi name for our remote EJB. This jndi name is constructed from the ejb module name, bean name, bean distinct name, and its remote business interface. More details are in this JBoss docs page.

Nature Wall Decals-Nature Wall Stickers

Nature Wall Decals And Nature Wall Stickers. The tendency of many people today are more like something that nature and fresh. Similarly, wall hangings, many in the living room decorated with natural ornaments. It is also a great choice for your room and your kitchen, child's room is also decorated with this ideal because as they grow older and their tastes change, you can easily give the room a new look.

Nature Wall Decals,Nature Wall Stickers

Nature Wall Decals,Nature Wall Stickers

Nature Wall Decals,Nature Wall Stickers

It decl wall nature allows you to bring the views of the forest into your living room, pictures of forest to your indoor patio area. And if you have a gym, you can bring the game up close and personal with the beach picture. Try it, you will feel the beauty of this world up close.

Nature Wall Decals,Nature Wall Stickers

Nature Wall Decals,Nature Wall Stickers

This decoration is not very easy to install. in price depending on size wall mural you want, but I'm sure you do not need to sell your valuables to get a natural wall murals.

Tree Wall Murals For Teenage Bedroom

Tree Wall Murals For Teenage Bedroom. Do you know the teenage is the most memorable in my life. Everything was beautiful and all-round challenge. Teen have fulfilled all his wishes. You never feel it's ...
As a parent you should know what is most preferred for his special teenage bedroom wall.


Coconut Wall Murals For Teenage Bedroom

Flower Wall Murals For Teenage Bedroom

Rose Wall Murals For Teenage Bedroom

Tree Wall Murals For Teenage Bedroom

Trees are a favorite among teens in decorating the walls. it is true, the bedroom feels cool and comfortable with tree wall mural. When your child home from campus and the rest in the room, they will feel very comfortable with the atmosphere of the room whose walls are decorated with wall murals trees.

Many types of plants you can install to decorate the walls. Girl usually prefer pictures of flowers such as roses or jasmine. whereas for a boy you could put a picture of palm trees or the other according to your teen craze.

Thoughts on ThreadLocal

2 main usages of java.lang.ThreadLocal variables:
  1. Vertical sharing: sharing and propagation of contextual data through the entire processing cycle. This is similar to http request attributes binding, except for the different scopes. A ThreadLocal variable (e.g., security context, transaction context) can be propagated across different tiers, e.g., from web to local EJB. After the processing is done, care must be taken to clear ThreadLocal variables to avoid context leaking.

  2. Horizontal sharing: sharing of objects across repeated and concurrent processing tasks. It offers a third approach for achieving thread safety, besides object locking and unshared instances. No need to clear TheadLocal variables after the current processing is done, since they are intended to be shared throughout the life of the thread.
However, when different class loaders are used among those tasks, the ThreadLocal object previously stored is not visible to the new class loader, and a new binding will be created. So over time, stales entries (instances of ThreadLocal data, and possibly anonymous inner subclass of ThreadLocal) will continue to consume memory. On the bright side, ThreadLocalMap keys use WeakReference and will eventually be cleared when the map approaches its capacity.

Think of ThreadLocal as a container that holds thread-sensitive application data. Therefore, a ThreadLocal variable can be associated with multiple threads. A thread can be associated with multiple ThreadLocal variables.

Thread class maintains a threadLocals Map (ThreadLocal.ThreadLocalMap) to hold all ThreadLocal variables for the current thread. The map key is the ThreadLocal instance, and the value is the actual object for this thread. When you call aThreadLocal.get() to retrieve the current binding, the get() method just asks the current thread to look up in its threadLocals map, using itself (aThreadLocal) as the key.

So the per-thread data is internally stored inside Thread class. Why did they create this ThreadLocal mediator class sitting in the middle? If I were to implement it, my first thought would be to introduce new methods to Thread class, such as setContextData(key, val), getContextData(key) & removeContextData(key).

Here are some reasons I can think of why ThreadLocal was designed this way:

1, Division of labor. Thread as a low-level construct should not be directly manipulated by applications. Application state is better managed by applcation classes.

2, Type safety. ThreadLocal<T> as a generic type is type-safe, and you can declare it to be ThreadLocal<Integer>, ThreadLocal<String>, or ThreadLocal<MyType>.

3, Encapsulation. The recommended practice is to declare a ThreadLocal<T> variable to be

private static final ThreadLocal<MyType> xxx = new ThreadLocal<MyType>();

The applicaton class can choose to completely hide the use of ThreadLocal as an implementation detail, or selectively allow certain operations, e.g., getXXX, setXXX, or removeXXX.

Disney Wall Murals for Kids Bedrooms

Journey to Disneyland during the holidays so much fun and create unforgettable memories. Each time to Disney with the kids to make them not want to go home.

Disney wall murals are very unique and interesting to see, this wall mural makes them remember the sweet memories when sightseeing. With wall murals of life seemed to go to Disney every day.

wall mural is unique and suited to your child decorate the walls. Disney wall murals in figure added with a picture or a butterfly in the surroundings really make life more beautiful in the lead.

Disney Wall Murals for Kids Bedrooms
Disney Princess Wall Murals

Disney Wall Murals for Kids Bedrooms
Disney Mickey Wall Murals

Disney Wall Murals for Kids Bedrooms
Disney Wall Murals Colouring

Disney Wall Murals for Kids Bedrooms
Girl Disney Wall Murals
Hopefully this article and the picture can inspire you

Different Strategies for Acquiring Dependency inside a Method

When we create or refactor a method, we find some input data is needed for the method to do its job. What are the various options to acquire these dependency? I just went through a major code refactoring and module restructuring, and would like to share some thoughts:
  1. Pass it in as method parameters. This seems to be most common approach, and some considerations are:
    • First forget about implementation details and needs, does it make sense to require the additional data in order to do the work? Think in terms of raw materials for completing the task, as opposed to method parameters.

    • The client code will need to acquire the new data, if not already available, or the target method declares a parameter injection.

    • All subtypes (e.g., subclasses overriding this method) and callers need to be updated to the new method signature. That may not be a problem if we are changing internal interfaces or implementation classes. But for public interfaces, it presents a backward compatibility problem.

    • To what granularity do we want to add the new parameter? Is it a coarse-grained or fine-grained parameter? For example, do we pass in (String name), or (UserInfo userInfo)? Some guidelines:

      • Conceptually, what input is needed for the method to perform its task? Try to reduce the granularity to what's really necessary, to make it usable in more contexts. Some calling code may only have the fine-grained data (e.g., zipCode), but not the coarse-grained data (e.g., userInfo)

      • Be consistent with other methods in the same interface or class. If many peer methods take UserInfo, it makes sense to have UserInfo in the new method even if only part of UserInfo is needed.

      • Unless it's remote invocation, the overhead of parameter passing is the same between a fine-grained and a coarse-grained parameter.

      • Avoid exporting information that is specific to a design tier or implementation layer. If the coarse-grained data fall into this category, then choose to export the fine-grained data that are not tied to the current tier or layer. For example,

        • HttpServletRequest or HttpServletResponse are tied to web tier, and may be passed around during the current request processing inside web tier, but should never be exported to business tier.

        • Security realm instances should not be passed outside security layer.

      • The above point is more evident and enforced by a module system like OSGi. A public class that is not exported by its host module will not be visible to other modules, and so may not be passed outwards. In this case, a fine-grained data type or even a string literal is more appropriate.


  2. Derive from existing method parameters, when the required data is indirectly reachable from existing parameters. For example,

    • String zip = person.getAddress().getZip();

  3. Is it already available as static or instance fields, or inherited from super classes?

    If some data are intrinsic attributes and relationship fields of a class, they should be initialized in constructors or injected via IoC framework and available to be shared by all methods. They consistute the class and instance state. It's possible that a method takes a type of parameter that is already available in class or instance state. They are intended to be distinct objects. For example,
    /**
    * @param userInfo a different UserInfo instance than represented by this person.
    * @return true if userInfo is a potential friend of this person; false otherwise.
    */
    public boolean maybeFriends(UserInfo userInfo) {
    return this.userInfo.similarTo(userInfo);
    }

  4. Derive it from existing static or instance fields, for example,

    • String zipCode = this.userInfo.getZipCode();

  5. Is it available from a global registry, or naming service? Typically, the global namespace is initialized and populated upon program start. If subsequent concurrent and write operations are supported, the global namespace needs to be thread-safe. For example,

    • User user = GlobalPlace.getCurrent(User.class);

    • String m = InitialContext.<String>doLookup("config/mode");

  6. Create my own instances, using direct instantiation or some sort of factory method. Use this option if the current method has adequate information and knows how to create. For example,

    • Config config = new Config(mapping);

    • Handler handler = HandlerFactory.createHandler();

    • Logger logger = Logger.getLogger("abc"); //find or create the named logger

How to Instantiate Annotation Type and Qualifier

Java annotations are usually used to annotate a language element, to inject dependency, or to provide metadata. They are interface types and cannot be directly instantiated. But sometimes we find it necessary to have instances of annotation types. This post demonstrates how to instantiate annotation types and use qualifier in simple search.

In short, you will need to write an abstract class that implements your annotation type T, and extends javax.enterprise.util.AnnotationLiteral<T> (see ContainsQualifier class below). The client code then can instantiate this abstract class by using anonymous inner class that supplies appropriate values to T (see AnnotationLiteralTest#findBy below).

A somewhat contrived use case: there are bags and baskets that contain items like gold or fruit. So bag and basket are annotated with what they contain. In a warehouse, the staff needs to find all packgages containing gold, all packages containing fruit, etc, based on one or more qualifiers.

This is implemented in the following maven project (project source in github):


pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.blogspot.javahowto</groupId>
<artifactId>annotation-literal</artifactId>
<version>1.0</version>

<build>
<defaultGoal>install</defaultGoal>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>

<dependencies>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.0-SP4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
The annotation type qualifier: Contains

package com.blogspot.javahowto;

import javax.inject.Qualifier;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Qualifier
@Documented
@Retention(value= RetentionPolicy.RUNTIME)
public @interface Contains {
String value() default "";
}
Bag type containing gold:

package com.blogspot.javahowto;

@Contains("Gold")
public class Bag {
}
Basket type containing fruit:

package com.blogspot.javahowto;

@Contains("Fruit")
public class Basket {
}
Abstract class that implements the qualifier Contains:

package com.blogspot.javahowto;

import javax.enterprise.util.AnnotationLiteral;

public abstract class ContainsQualifier extends AnnotationLiteral<Contains>
implements Contains {}
The qualifier-based search is implemented in CollectionManager:

package com.blogspot.javahowto;

import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.LinkedList;

public class CollectionManager {
private Collection collection;

public CollectionManager(Collection collection) {
this.collection = collection;
}

/**
* Finds all objects matching all criteria represented by annotations
* @param annotationsToMatch one or multiple search qualifiers
* @return a collection of objects that match all the search qualifiers
*/
public Collection findBy(Annotation... annotationsToMatch) {
Collection result = new LinkedList();
for(Object obj : collection) {
boolean matched = false;
Annotation[] classAnnotations = obj.getClass().getAnnotations();
for(Annotation an : annotationsToMatch) {
if(contains(classAnnotations, an)) {
matched = true;
} else {
matched = false;
break;
}
}
if(matched)
result.add(obj);
}
return result;
}

/**
* Checks if an array of Annotations contains an individual Annotation
* @param annotations an array of annotations
* @param ann an individual annotation
* @return true if ann is equal to at least one of the element in
* annotations array; false otherwise
*/
private boolean contains(Annotation[] annotations, Annotation ann) {
for(Annotation a : annotations) {
if(a.equals(ann)) {
return true;
}
}
return false;
}
}
The JUnit test class:

package com.blogspot.javahowto.test;

import com.blogspot.javahowto.*;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

public class AnnotationLiteralTest {
private static List mixed = new LinkedList();
private static CollectionManager collectionManager;

@BeforeClass
public static void setUp() throws Exception {
for (int i = 0; i < 2; i++) {
mixed.add(new Bag());
mixed.add(new Basket());
}
collectionManager = new CollectionManager(mixed);
}

@Test
public void testContainsGold() throws Exception {
System.out.printf("contains Gold: %s%n%n", findBy("Gold"));
}

@Test
public void testContainsFruit() throws Exception {
System.out.printf("contains Fruit: %s%n%n", findBy("Fruit"));
}

@Test
public void testContainsFruitGold() throws Exception {
System.out.printf("contains Gold and Fruit: %s%n%n", findBy("Gold", "Fruit"));
}

/**
* Finds all objects matching all criteria
* @param criteria one or multiple search qualifiers
* @return a collection of objects that match all the search qualifiers
*/
private Collection findBy(final String... criteria) {
Contains[] qualifiers = new Contains[criteria.length];
for (int i = 0; i < criteria.length; i++) {
final String s = criteria[i];
Contains containsQualifier = new ContainsQualifier() {
@Override
public String value() {
return s;
}
};
qualifiers[i] = containsQualifier;
}
return collectionManager.findBy(qualifiers);
}
}
To build the project and run the JUnit tests:

$ mvn install

Running com.blogspot.javahowto.test.AnnotationLiteralTest
contains Gold: [com.blogspot.javahowto.Bag@7b112783, com.blogspot.javahowto.Bag@23394894]

contains Fruit: [com.blogspot.javahowto.Basket@69198891, com.blogspot.javahowto.Basket@b551d7f]

contains Gold and Fruit: []

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.047 sec
Some points for discussion:

The subclass of ContainsQualifier (the anonymous inner class) represents a strategy in strategy pattern. Traditionally the strategy is an implementation of a common interface. Now this seems another area that annotation can replace the traditional interface.

In this project the search criteria are based on string values, and wrap them as annotation may be overkill. But in more complex cases, annotation offers a very flexible and generic interface for specifying conditions and qualifiers.

Wall Decals for Cosy Kitchen Design

Wall Decals for Cosy Kitchen Design. This wall decoration is very unique and attractive, ideal for decorating your Cosy Kitchen Design. wall decal is also easy to create and delete them.



To create a cozy atmosphere of the kitchen and the comfort you are not wrong when choosing vinyl wall decal wall decal or japanese or something. I love these wall hangings, so eat more savory and delicious and convenient kitchen Cosy Kitchen


Add some accesories like exotic flowers will add to your kitchen cozy, unique wall art decor or classic wall decor will also make-your mood more cheerful and energetic.

ConcurrentHashMap Examples

4 steps when accessing a cache implemented with java.util.ConcurrentHashMap (javadoc):
  1. get the value from the ConcurrentMap;
  2. if null, assume it's the first access, and create the value;
  3. call putIfAbsent on the concurrentMap to store the new value;
  4. if return value is not null (it's rare but happens), use the return value as the golden copy, and discard the newly-created object.
The following test class, SqrtTest, displays the square root of numbers, and each square root value is accessed multiple times concurrently. The intent is to calculate it only on the first access and return the cached value for subsequent requests.
import java.util.*;
import java.util.concurrent.*;

public class SqrtTest {
private static final String CONCURRENCY_LEVEL_DEFAULT = "50";
private static final String CONCURRENCY_KEY = "concurrency";
private ConcurrentMap<Double, Double> sqrtCache = new ConcurrentHashMap<Double, Double>();

public static void main(String args[]) {
final SqrtTest test = new SqrtTest();
final int concurrencyLevel = Integer.parseInt(System.getProperty(CONCURRENCY_KEY, CONCURRENCY_LEVEL_DEFAULT));
final ExecutorService executor = Executors.newCachedThreadPool();

try {
for(int i = 0; i < concurrencyLevel; i++) {
for(String s : args) {
final Double d = Double.valueOf(s);
executor.submit(new Runnable() {
@Override public void run() {
System.out.printf("sqrt of %s = %s in thread %s%n",
d, test.getSqrt(d), Thread.currentThread().getName());
}
});
}
}
} finally {
executor.shutdown();
}
}

// 4 steps as outlined above
public double getSqrt(Double d) {
Double sqrt = sqrtCache.get(d);
if(sqrt == null) {
sqrt = Math.sqrt(d);
System.out.printf("calculated sqrt of %s = %s%n", d, sqrt);
Double existing = sqrtCache.putIfAbsent(d, sqrt);
if(existing != null) {
System.out.printf("discard calculated sqrt %s and use the cached sqrt %s", sqrt, existing);
sqrt = existing;
}
}
return sqrt;
}
}
To compile and run the SqrtTest (-Dconcurrency=123 can be used to adjust the concurrency level):
$ javac SqrtTest.java
$ java SqrtTest 0.5 11 999 0.1

calculated sqrt of 0.5 = 0.7071067811865476
sqrt of 0.5 = 0.7071067811865476 in thread pool-1-thread-1
calculated sqrt of 11.0 = 3.3166247903554
sqrt of 11.0 = 3.3166247903554 in thread pool-1-thread-2
calculated sqrt of 999.0 = 31.606961258558215
sqrt of 999.0 = 31.606961258558215 in thread pool-1-thread-1
sqrt of 11.0 = 3.3166247903554 in thread pool-1-thread-2
calculated sqrt of 0.1 = 0.31622776601683794
calculated sqrt of 0.1 = 0.31622776601683794
sqrt of 999.0 = 31.606961258558215 in thread pool-1-thread-1
sqrt of 11.0 = 3.3166247903554 in thread pool-1-thread-8
sqrt of 0.5 = 0.7071067811865476 in thread pool-1-thread-4
sqrt of 0.5 = 0.7071067811865476 in thread pool-1-thread-7 calculated sqrt of 0.1 = 0.31622776601683794
discard calculated sqrt 0.31622776601683794 and use the cached sqrt 0.31622776601683794sqrt of 0.1 = 0.31622776601683794 in thread pool-1-thread-6
...
From the above output, we can see at least one calculation is discarded since the value already exists in the cache. It had been added to the cache by another thread between step 1 and step 3.

Multiple input double numbers are used to increase thread contention. When testing with one single input number, I couldn't trigger the race condition as evidenced by the "discard calculated sqrt" log message. It is probably because it takes time for the thread pool to create the second thread, and by the time it kicks in, the result is already calculated by the first thread and well established in the cache.

How to Create POJO JavaBean Custom Resource in GlassFish

In addition to simple value custom resources, GlassFish also provides decent support for POJO JavaBean custom resources. The steps are very similar to String and primitive custom resources, except that you will need to provide your resource impl class and use a different GlassFish factory class. For example, suppose we need to implement a Person class:

public class Person implements java.io.Serializable {
private String firstName;
private String lastName;
private int age;

public String getFirstName() {
return firstName;
}

public void setFirstName(String s) {
firstName = s;
}

public String getLastName() {
return lastName;
}

public void setLastName(String s) {
lastName = s;
}

public int getAge() {
return age;
}

public void setAge(int i) {
age = i;
}

@Override
public String toString() {
return String.format("Person firstName:%s, lastName:%s, age:%s",
firstName, lastName, age);
}
//TODO override equals and hashCode
}
Compile it and copy Person.class to GlassFish domain lib directory, restart the domain, and create a custom resource of type Person:

$ javac Person.java
$ cp Person.class $GLASSFISH_HOME/domains/domain1/lib/classes/
$ asadmin restart-domain
$ asadmin create-custom-resource --restype=Person --factoryclass=org.glassfish.resources.custom.factory.JavaBeanFactory --property firstName\="Jon":lastName\="Smith":age\=20 resource/person
To list the attributes and properties of the newly-created resource with GlassFish asadmin get command:

$ asadmin get 'resources.custom-resource.resource/person.*'

resources.custom-resource.resource/person.property.age=15
resources.custom-resource.resource/person.property.lastName=Smith
resources.custom-resource.resource/person.property.firstName=Jon
resources.custom-resource.resource/person.enabled=true
resources.custom-resource.resource/person.factory-class=org.glassfish.resources.custom.factory.JavaBeanFactory
resources.custom-resource.resource/person.jndi-name=resource/person
resources.custom-resource.resource/person.object-type=user
resources.custom-resource.resource/person.res-type=Person
Command get executed successfully.
To update the age property of the resource with asadmin set command:

$ asadmin set 'resources.custom-resource.resource/person.property.age'=15

resources.custom-resource.resource/person.property.age=15
Command set executed successfully.
To look up the custom resource, resource/person, from a webapp, or Java EE application:

try {
InitialContext ic = new InitialContext();
Person person = (Person) ic.lookup("resource/person");
} catch (NamingException e) {
throw new RuntimeException(e);
}
You can inject it into Java EE web component or EJB component class such as servlet, filter, web listener, interceptor, or EJB bean class:

@Resource(lookup="resource/person")
private Person person;
A Java SE remote client can also look up the resource:

import javax.naming.*;
/**
* A generic remote client for testing JNDI lookup.
*/
public class TestLookup {
public static void main(String args[]) throws Exception {
InitialContext ic = new InitialContext();
for(String name : args) {
System.out.printf("Looked up jndi name %s, got %s%n",
name, ic.lookup(name));
}
}
}
The following shows how to build and run the remote JNDI client, and the output:

$ javac TestLookup.java
$ java -cp "$GLASSFISH_HOME/modules/*:." TestLookup resource/person

Feb 18, 2012 11:42:12 AM com.sun.enterprise.v3.server.CommonClassLoaderServiceImpl findDerbyClient
INFO: Cannot find javadb client jar file, derby jdbc driver will not be available by default.
Looked up jndi name resource/person, got Person firstName:Jon, lastName:Smith, age:15
Note that both TestLookup.class and Person.class are in current directory and therefore are in the client classpath. Person class also implements java.io.Serializable to make remote access possible.

For more advanced example of GlassFish custom resources, see How to create and look up thread pool resource in GlassFish

Wayang Or Puppet Wall Decor


Wayang is indonesian traditional art, have unique characteristics perfect for decorate your room wall. Wayang is one of Indonesian traditional arts that go international and spread to various countries. even in Indonesia Wayang in use for a name of a well known group bands. In dutch Wayang used for the education of children to learn the background and philosophy in order to build the character of children.

Wayang Wall Decor, Puppet Art Decor
Wayang or Java's Puppet known since prehistoric times of about 1500 years before Christ. Java's Puppet is the Indonesian traditional art developed primarily in Java and Bali. UNESCO has Recognized puppet show on November 7, 2003, as a work of amazing cultural stories in narrative and beautiful heritage and valuable (Masterpiece of the Oral and Intangible Heritage of Humanity). When the Hindu religion in Indonesia it art show to be an effective medium to spread the Hindu religion, where puppet shows using the story of Ramayana and Mahabharata.
The next puppet arts thrive in the spread of Islam, Muslim humanists Sunan Kalijaga (one of nine guardian) admired by all adherents of Islam in Indonesia.
Java's Puppet is Suitable Art Decor for Kid Bedroom Wall or Living Room
Wayang Wall Decor, Puppet Art Decor


puppets are very unique and perfect for the bedroom wall decoration or your living room, this is very very interesting, funny and elegant. in addition, Java's Puppet story also unique art to see and can give us a lesson. in Indonesia, a large market for interior design began a new trend to use puppets as an accent wall decor for home owners to express an interest in art and history. It is decorating ideas perfect for those who appreciate the beauty of the beautiful culture.

puppet decorations such as stickers and drawings are also ideal for temporary use. in Indonesia and the Netherlands, this accessory is often used at birthdays, weddings and party. They are the perfect accessory for a classic motif or concept inspired to make this event even more exciting for the guests and all those present. puppet art wall decor accessories are also very good for teen bedroom decoration or nursery. kids will love this design because it can make them remembered the story that appears in the story of the puppet and their idol.
Home accents and wall decor puppet is fully customizable and can be perfectly placed anywhere around the house. you can choose a wayang golek, wayang kulit, Ramayana and Mahabharata, or other types of puppets fit your taste for further decorating ideas you can find on the Internet or you can seek advice from expert interior design. Have fun!

How to Create Simple String and Primitive Resources in GlassFish

Sometimes you need to create simple resources in application server so that all deployed applications can look them up. Their types can be string, boolean, number, or any custom java bean types. In GlassFish CLI, they are created and managed with a set of generic commands,

asadmin create-custom-resource ...
asadmin list-custom-resources ...
asadmin delete-custom-resource ...
asadmin get 'resources.custom-resource.*'
asadmin set ...
GlassFish admin console provides GUI way of doing things but I found using CLI is a lot faster.

For example:
$ asadmin create-custom-resource --restype=java.lang.String --factoryclass=org.glassfish.resources.custom.factory.PrimitivesAndStringFactory --property value="http\://javahowto.blogspot.com" resource/javahowto

$ asadmin create-custom-resource --restype=java.lang.Double --factoryclass=org.glassfish.resources.custom.factory.PrimitivesAndStringFactory --property value=0.5 resource/rate

$ asadmin create-custom-resource --restype=java.lang.Boolean --factoryclass=org.glassfish.resources.custom.factory.PrimitivesAndStringFactory --property value=true resource/flag
To look up the custom resource created above, just perform the following in any web or EJB component classes, e.g., servlet, filter, interceptor, web listener, EJB bean class:
try {
InitialContext ic = new InitialContext();
String javahowto = (String) ic.lookup("resource/javahowto");
double rate = (Double) ic.lookup("resource/rate");
boolean flag = (Boolean) ic.lookup("resource/flag");
System.out.printf(
"custom resources from lookup: javahowto=%s, rate=%s, flag=%s%n",
javahowto, rate, flag);
} catch (NamingException e) {
throw new RuntimeException(e);
}
An easier way to obtain these resources is through @Resource injection in any web or EJB component class:
  @Resource(lookup="resource/javahowto")
private String withLookup;

@Resource(lookup="resource/rate")
private double rate;

@Resource(lookup="resource/flag")
private boolean flag;
These custom resources can also be accessed from a remote Java SE client:

import javax.naming.*;

/**
* A generic remote client for testing JNDI lookup.
*/
public class TestLookup {
public static void main(String args[]) throws Exception {
InitialContext ic = new InitialContext();
for(String name : args) {
System.out.printf("Looked up jndi name %s, got %s%n",
name, ic.lookup(name));
}
}
}
To compile and run the remote client:

javac TestLookup.java
java -cp "$GLASSFISH_HOME/modules/*:." TestLookup resource/javahowto resource/rate resource/flag

Feb 16, 2012 8:21:21 PM com.sun.enterprise.v3.server.CommonClassLoaderServiceImpl findDerbyClient
INFO: Cannot find javadb client jar file, derby jdbc driver will not be available by default.
Looked up jndi name resource/javahowto, got http://javahowto.blogspot.com
Looked up jndi name resource/rate, got 0.5
Looked up jndi name resource/flag, got true
The warning message "Cannot find javadb client jar file" can be safely ignored. To avoid this annoying message, just add command line system property AS_DERBY_INSTALL, pointing to a valid derby installation:

java -cp "$GLASSFISH_HOME/modules/*:." -DAS_DERBY_INSTALL=$GLASSFISH_HOME/../javadb TestLookup resource/javahowto resource/rate resource/flag
You can view all attributes and properties of a custom resource with asadmin get command:

asadmin get 'resources.custom-resource.resource/rate.*'

resources.custom-resource.resource/rate.property.value=0.6
resources.custom-resource.resource/rate.enabled=true
resources.custom-resource.resource/rate.factory-class=org.glassfish.resources.custom.factory.PrimitivesAndStringFactory
resources.custom-resource.resource/rate.jndi-name=resource/rate
resources.custom-resource.resource/rate.object-type=user
resources.custom-resource.resource/rate.res-type=java.lang.Double
Command get executed successfully.
To update the value of a custom resource with asadmin set command:

asadmin set 'resources.custom-resource.resource/rate.property.value'=0.6
resources.custom-resource.resource/rate.property.value=0.6
Command set executed successfully.

Some Idea To Make Fantastic Art Wall Stencil

Some Idea To Make Fantastic Art Wall Stencil


Make your room Look fantastic with wall stencil, Any walls may be a perfect place for hanging framed stencil art prints.

Some Idea To Make Fantastic Art Wall Stencil
1. One of the best parts of creating your own stencil art is that you can choose whatever colors you want. You can use colors from the current décor or you can just reach right into your imagination and pull out whatever pleases you. Decorating with stencils is a great way to truly add personalized art to your room. By creatively adding different colors we add excitement. And we add a little of our own personalities.  We all have our favorites and by putting the colors that appeal most to us in our art, we oake it personal.


Some Idea To Make Fantastic Art Wall Stencil
2. Other second Best Tools for Sketching and Lettering on Walls is costum stencils. Stencils are one of the finest accessories to get your wall decorated in the best possible way. The best place to search for designs for your custom is through the internet. There are a lot of templates which you can look at for generating ideas. You can also give a visit to the local libraries available in your residing city.

Some Idea To Make Fantastic Art Wall Stencil
3. The Third Option for stencil is tuscan wall stencil, The Tuscan style is popular with home decorators and professional designers alike. Tuscan motifs, used as borders and accents, add the finishing touches to a Tuscan style. Tuscan wall motifs are versatile. They can look good in the kitchen, dining room, living room or patio and the effect is just as attractive in bedrooms and even bathrooms.

Followers

Pageviews Last 7 Days