Feb
14
2011
Frank
This short tutorial gives you the needed steps to integrate SEAM into an existing WAR-project or to build such a WAR from the beginning.
1. Including Dependencies
First of all you need to add the SEAM dependencies and of course JSF, if not already present:
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>1.2_15</version>
</dependency>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>1.2_15</version>
</dependency>
<dependency>
<groupId>com.sun.facelets</groupId>
<artifactId>jsf-facelets</artifactId>
<version>1.1.15.B1</version>
</dependency>
<dependency>
<groupId>org.jboss.seam</groupId>
<artifactId>jboss-seam</artifactId>
<version>2.2.1.Final</version>
<exclusions>
<exclusion>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jboss.seam</groupId>
<artifactId>jboss-seam-ui</artifactId>
<version>2.2.1.Final</version>
</dependency>
2. Modify web.xml
Here you have to add the FacesServlet for JSF, the Seam-Filter for SEAM and a Listener for SEAM. Additionally you can define some CONTEXT-variables for JSF / SEAM.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!-- Context Variables -->
<context-param>
<param-name>facelets.SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<!-- Seam Listener -->
<listener>
<listener-class>org.jboss.seam.servlet.SeamListener</listener-class>
</listener>
<!-- Seam Filter -->
<filter>
<filter-name>Seam Filter</filter-name>
<filter-class>org.jboss.seam.servlet.SeamFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Seam Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- JSF Servlet -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<!-- Seam Resource Servlet -->
<servlet>
<servlet-name>Seam Resource Servlet</servlet-name>
<servlet-class>org.jboss.seam.servlet.SeamResourceServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Seam Resource Servlet</servlet-name>
<url-pattern>/seam/resource/*</url-pattern>
</servlet-mapping>
</web-app>
3. Configure JSF
Then you have to add an faces-config.xml to the WEB-INF directory.
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xi="http://www.w3.org/2001/XInclude"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
</faces-config>
4. Configure SEAM
Just add some empty configuration files to enable seam for your WAR.
<?xml version="1.0" encoding="UTF-8"?>
<components xmlns="http://jboss.com/products/seam/components"
xmlns:core="http://jboss.com/products/seam/core" xmlns:transaction="http://jboss.com/products/seam/transaction"
xmlns:web="http://jboss.com/products/seam/web" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<core:init debug="false" />
</components>
And also put an empty seam.properties to your classpath (in directory src/main/resources).
2 comments | tags: Java, JSF, Maven, SEAM | posted in Java, Maven, SEAM
Feb
7
2011
Frank
Yesterday I had the problem that I need to send a broadcast message in an application which should be processed by every running node. This message should be the initiator to clear a local cache on each node. So I had the idea to use JMS as API using a topic and every node will listen on that topic. I am using this on JBoss 5.1.0.GA.
First of all the need to define an Topic. This could be done in an own service.xml, which is located directly in the deploy directory or (my preferred way) in the ear.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| < ?xml version="1.0" encoding="UTF-8"?>
<server>
<mbean code="org.jboss.jms.server.destination.TopicService"
name="jboss.messaging.destination:service=Topic,name=MyEvents"
xmbean-dd="xmdesc/Topic-xmbean.xml">
<depends optional-attribute-name="ServerPeer">
jboss.messaging:service=ServerPeer
</depends>
<depends>
jboss.messaging:service=PostOffice</depends>
<attribute name="Clustered">true</attribute>
</mbean>
</server> |
Especially the attribute “Clustered” is important. Otherwise you would only have a local topic and not a cluster-wide.
Next we have to define our listener:
1
2
3
4
5
6
7
8
9
10
11
12
| @MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "topic/MyEvents") }, messageListenerInterface = MessageListener.class)
@Depends(value = { "jboss.messaging:service=PostOffice",
"jboss.messaging.destination:name=MyEvents,service=Topic" })
public class ClusterEventsListener implements MessageListener {
public void onMessage(Message message) {
//do some stuff
System.out.println("received an event");
}
} |
That’s all, now you can easily send some events using standard JMS commands, for example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
| @Stateless
public class SendEventImpl implements SendEvent {
@Resource(mappedName = "topic/MyEvents")
private Topic eventTopic;
@Resource(mappedName = "ConnectionFactory")
private TopicConnectionFactory eventQueueFactory;
public void sendEvent() {
try {
TopicConnection cnn = null;
TopicSession sess = null;
TopicPublisher publisher = null;
try {
cnn = eventQueueFactory.createTopicConnection();
sess = cnn.createTopicSession(false,
TopicSession.AUTO_ACKNOWLEDGE);
publisher = sess.createPublisher(eventTopic);
TextMessage message = sess.createTextMessage("hello world");
publisher.send(message);
} finally {
try {
if (publisher != null)
publisher.close();
} catch (Throwable e) {
log.error("closing sender", e);
}
try {
if (sess != null)
sess.close();
} catch (Throwable e) {
log.error("closing session", e);
}
try {
if (cnn != null)
cnn.close();
} catch (Throwable e) {
log.error("closing connection", e);
}
}
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
} |
no comments | tags: Cluster, Java, JBoss, JMS, MDB | posted in Java, JBoss
Jan
24
2011
Frank
Using JPA or especially Hibernate for mapping database tables to POJOs is quite comfortable. An essential feature here is lazy loading of constraints between objects. Unfortunately this didn’t work out of the box for reversed @OntToOne relations.
For example you have two classes:
1
2
3
4
5
6
7
8
9
10
11
12
13
| public class A {
@OneToOne(fetch=FetchType.LAZY)
private B foo;
}
public class B {
@OneToOne(mappedBy = "foo", fetch = FetchType.LAZY)
private A bar;
public A getBar() {
return bar;
}
} |
If you now load B from the database Hibernate needs to look if A also exists, because Hibernate needs to know if “bar” is null or not. In this case the parameter “fetch” has no effect. There are two known possible solutions to solve this problem:
- Implement the “bar” relation as @OneToMany with a collection and implement getBar as you needed. But if you need this relation in complex queries you could have problems to define the correct HQL.
- You use Bytecode instrumentation to realize a real lazy loading behaviour. In this case you have to add the following annotation to the property “bar”: @LazyToOne(LazyToOneOption.NO_PROXY)
no comments | tags: ejb, ejb3, hibernate, Java, jpa, lazy loading | posted in Hibernate, Java
Dez
7
2010
Frank
After a long break, I write again some tips and hints about Java programming.
Today I had again the problem that I need some configurable parameteres in an application. One way could be the usage of the Properties-API. But this only give us a very flat model.
In my eyes a better solution is to use XML. But this is very komplex to parse using DOM or SAX. So we can use some Binding-APIs to bind Java-Code to XML and vise versa.
One solution is XMLBeans, which I used in past. But from Java 6 on JAXB is included and so no extra library is needed.
So we start writing our Model in Java (I named it “Config”):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| @XmlRootElement(name = "config", namespace = Config.NAMESPACE)
public class Config {
public static final String NAMESPACE = "http://www.javahelp.info/test/config";
private String host;
@XmlElement(namespace = NAMESPACE)
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
} |
That’s all. From now an you can read the config from a file with the following code:
1
2
3
4
5
| JAXBContext context = JAXBContext.newInstance(Config.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
//skip validation
unmarshaller.setSchema(null);
Config config = (Config) unmarshaller.unmarshal(new File("config.xml")); |
And you also can write a in-memory-config:
1
2
3
4
5
6
| Config config = new Config();
config.setHost("localhost");
JAXBContext context = JAXBContext.newInstance(Config.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(config, new File("config.xml")); |
no comments | tags: binding, config, Java, jaxb, marshal, serialization, unmarshal, xml | posted in Java
Nov
30
2009
Frank
Sometimes it is necessary to handle a parameter of type object different for the real type. So you have to use instanceof to determine the type of an object. If you are need to check if it is an array, you can use the Reflection-API provided by the JRE. The Reflection API is a comfortable and rich functional API to inspect and manipulate Objects at runtime. One example could be to access private fields at runtime.
I had the problem to serialize some variables to JavaScript, so I wrote me a simple function:
1
| public void objectToJavaScript(Object object, StringBuffer buf); |
If the given object is primitive I would simple add it to the provided StringBuffer, but if it is an array I need to output ‘[' and ']‘ with the given parameters. So I have to check if the object is an array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| public void objectToJavaScript(Object object, StringBuffer buf) {
if (object == null) {
buf.append("null");
return;
}
... //other types
if (object.getClass().isArray()) {
buf.append('[');
//TODO output array content
buf.append(']');
return;
}
...
} |
But how to access each entry of the array? One way could be to cast the object to Object[]. Unfortunately
if the array is an array of primtive types this would throw a ClassCastException. So we have to use the functions, provided by java.lang.reflect.Array. The full code looks like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| public void objectToJavaScript(Object object, StringBuffer buf) {
if (object == null) {
buf.append("null");
return;
}
... //other types
if (object.getClass().isArray()) {
buf.append('[');
int len = java.lang.reflect.Array.getLength(object);
for(int i = 0; i < len; i++) {
if (i > 0) buf.append(',');
objectToJavaScript(java.lang.reflect.Array.get(object, i), buf);
}
buf.append(']');
return;
}
...
} |
no comments | tags: api, Java, reflection | posted in Java
Nov
12
2009
Frank
Today I had another time the problem to execute many short tasks in a thread pooled environment. One way could be to write the pooling itselfs (like the other times in history
). But I thought: Why to reinvent the wheel every time and not using standardized libraries like the java.util.concurrent.*?
What I want:
- A self enlarging and shrinking ThreadPool depending on the queued tasks. (Because sometimes it is nothing to do and sometimes it could be to get many hundreds of tasks in a short time)
- A definable Limit of maximum running Threads (Because we cannot create hundreds of threads just for this task. Keep in mind: the tasks have a short run time)
- Queuing the Tasks to run later, if the ThreadPool has reached the given limits
So I looked at the given Examples and the Executors-Class, which provides fast and simple methods:
- newCachedThreadPool : This looks good, but unfortunately you can’t define a maximum limit of threads.
- newFixedThreadPool : This handles the wanted limitation, but not the automatic enlarging and shrinking.
So we cannot use the predefined methods and need to instantiate ThreadPoolExecutor directly.
Continue reading
no comments | tags: Java, performance, thread concurrency | posted in Java
Nov
2
2009
Frank
The Standard Service Life of Java 5 expired on Friday, October 30th. This is not really tradic, because Sun provides a Java SE 6 since December 2006. But on the other side on Mac OS X (up to 10.5. Leopoard) the default JRE is Version 5.0. 
Apple only published a Version 6 for 64 bit Intel processors. So many desktop applications still uses Java 5 as basis. It would be interessting, what Apple will do, if critical bugs in Java 5 would be found.
An overview of the whole EOL-Policy for Java can be seen at http://java.sun.com/products/archive/eol.policy.html
no comments | tags: eosl, Java, sun | posted in Java
Nov
1
2009
Frank
The EJB3 Standard provides some annotations to handle general approaches, like transactions (@TransactionAttribute) and security (@RolesAllowed, etc.). To use these methods, you only have to add them to the concerning method.
1
2
3
4
5
6
7
8
| @Stateless
@Local(SampleStateless.class)
public class SampleStatelessBean implements SampleStateless {
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void sampleMethod() {
// do some stuff
}
} |
Sometimes you have to call methods of other business objects to handle the business logic. For example you have a batch update separated into many small update steps. Here you want to split the main transaction into several small transactions and the main part should have no transaction, because it only handles the reading of external data (The example code is not complete and should only demonstrate the usage of the annotations.).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| @Stateless
@Local(SampleStateless.class)
public class SampleStatelessBean implements SampleStateless {
@TransactionAttribute(TransactionAttributeType.NEVER)
public void import() {
//read some data
while (haveData) {
importData(subData);
}
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
private void importData(List data) {
// do some stuff
}
} |
This above code is unfortunately NOT CORRECT. The reason is that the @TransactionAttribute-annotations will only be honored, if you call the method via a business interface. So the first solutions is to inject the bean itself and call the submethod via the injected bean.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| @Stateless
@Local(SampleStateless.class)
public class SampleStatelessBean implements SampleStateless {
@EJB
private SampleStateless bp;
@TransactionAttribute(TransactionAttributeType.NEVER)
public void import() {
//read some data
while (haveData) {
bp.importData(subData);
}
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void importData(List data) {
// do some stuff
}
} |
Another solution, which is quite faster on JBoss in my tests, is to use the SessionContext to get a reference to the current business object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| @Stateless
@Local(SampleStateless.class)
public class SampleStatelessBean implements SampleStateless {
private SampleStateless bp;
@Resource
private SessionContext ctx;
@PostConstruct
public void init() {
bp = ctx.getBusinessObject(SampleStateless.class);
}
@TransactionAttribute(TransactionAttributeType.NEVER)
public void import() {
//read some data
while (haveData) {
bp.importData(subData);
}
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void importData(List data) {
// do some stuff
}
} |
no comments | tags: ejb, ejb3, Java, JBoss, transactions | posted in Java, JBoss
Okt
31
2009
Frank
Today I tried to read a JPEG with the ImageIO-Library, provided by the JRE. But instead of a wonderful image I only received the following exception:
1
2
3
4
5
6
7
8
| java.lang.IllegalArgumentException: bandOffsets.length is wrong!
at javax.imageio.ImageTypeSpecifier$Interleaved.< init >(ImageTypeSpecifier.java:382)
at javax.imageio.ImageTypeSpecifier.createInterleaved(ImageTypeSpecifier.java:495)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.getImageTypes(JPEGImageReader.java:743)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:935)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:912)
at javax.imageio.ImageIO.read(ImageIO.java:1400)
at javax.imageio.ImageIO.read(ImageIO.java:1322) |
With an EXIF-Reader (by the way a nice website) I tried to analyze the picture and saw the picture includes an embedded color profile “(unrecognized embedded color profile ‘SWOP (Coated), 20%’)”. A little bit more research showed the currently unresolved bugs in the JRE (especially ImageIO-Library; #4799903 and #5100094). So I’m not the only person, who had the problem. There are some code snippets and bug workarounds on the net trying to convert CMYK or YCCK to RGB. For my picture the CMYK-Solution doesn’t work, because the JRE means the embedded ICC profile doesn’t match the given raster (raster contains 3 bytes per pixel, but CMYK 4 bytes). But Werner Randelshofer wrote that it is important to use the given ICC, because of unexpectable color problems. So just to use a fix conversion method is not the wanted solution.
Then I tried first not to use the ImageIO library, but to give AWT-Toolkit a try. I was very surprised, that this function can correctly read the given image. So I didn’t need to handle the embedded ICC profiles directly. I modified my code to use this method, if ImageIO fails. The resulting code looks like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| private BufferedImage readImage(InputStream picture) throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
byte[] b = new byte[10240];
int l = 0;
while ((l = picture.read(b)) >= 0) {
buf.write(b, 0, l);
}
buf.close();
byte[] picturedata = buf.toByteArray();
buf = null;
try {
return ImageIO.read(new ByteArrayInputStream(picturedata));
} catch (IllegalArgumentException e) {
ImageInputStream input = ImageIO
.createImageInputStream(new ByteArrayInputStream(
picturedata));
Iterator< ImageReader > readers = ImageIO.getImageReaders(input);
ImageReader reader = null;
while (readers.hasNext()) {
reader = (ImageReader) readers.next();
if (reader.canReadRaster())
break;
}
if (reader == null)
throw new IOException("no reader found");
// Set the input.
reader.setInput(input);
int w = reader.getWidth(0);
int h = reader.getHeight(0);
BufferedImage image;
image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Image intImage = Toolkit.getDefaultToolkit().createImage(
picturedata);
new ImageIcon(intImage);
Graphics2D g = image.createGraphics();
g.drawImage(intImage, 0, 0, null);
g.dispose();
return image;
}
} |
The Toolkit-Method also has no problems on servers without an X11 server.
no comments | tags: awt, icc, images, Java, jpeg | posted in Java
Okt
28
2009
Frank
I recently updated my Eclipse from a beta of 3.4 to the latest Gallileo version using Yoxos OnDemand service.
After that I received always the following error, if I started a application or unit test case from eclipse:
1
| Exception in thread "main" java.lang.NoClassDefFoundError: info/javahelp/TestClass |
The solution for me was to reset the used JRE in the Build Path (Project Properties -> Java Build Path).

Here I changed from a System JRE from the underlying operation system Mac OS X to the used JRE Eclipse in running in.

After that a normal start of the application or test case was possible.
no comments | tags: classloader, Eclipse, Java | posted in Eclipse