<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>dominikdorn.com &#187; JavaEE6</title>
	<atom:link href="http://dominikdorn.com/category/javaee6/feed/" rel="self" type="application/rss+xml" />
	<link>http://dominikdorn.com</link>
	<description>shit happens ;)</description>
	<lastBuildDate>Mon, 06 Sep 2010 16:37:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1-alpha</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>CDI/Weld beans.xml XSD/DTD</title>
		<link>http://dominikdorn.com/2010/08/cdi-weld-beans-xml-xsddtd/</link>
		<comments>http://dominikdorn.com/2010/08/cdi-weld-beans-xml-xsddtd/#comments</comments>
		<pubDate>Fri, 20 Aug 2010 14:21:09 +0000</pubDate>
		<dc:creator>Dominik Dorn</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaEE6]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Weld]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://dominikdorn.com/?p=327</guid>
		<description><![CDATA[Shows how to proper use xml namespaces with CDI / Weld]]></description>
			<content:encoded><![CDATA[<p>As I&#8217;m often looking for the correct header of the <strong>beans.xml</strong> file required for <strong>Web Beans</strong> / <strong>Context and Dependency Injection</strong> (<strong>CDI</strong>) to work, I decided to share this simple header here with you. </p>
<p>If you don&#8217;t have anything to declare, create an empty beans.xml like this one</p>
<pre lang='xml' >
<beans
xmlns="http://java.sun.com/xml/ns/javaee"
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/beans_1_0.xsd" />

If you have to declare alternatives or interceptors, do it like this
<pre lang='xml'>
<beans
xmlns="http://java.sun.com/xml/ns/javaee"
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/beans_1_0.xsd">
    <alternatives>
        <stereotype>
            com.dominikdorn.dc.passwordReset.PasswordResetService
        </stereotype>
        <class>com.dominikdorn.dc.passwordReset.StudyGuruPasswordReset</class>
    </alternatives>
</beans>
</pre>
<p>A <a href="http://www.jetbrains.com/idea/">good IDE</a> will help you with creating a proper beans.xml as soon as you specify the xml namespace.</p>
<p>Popular implementations of <strong>CDI</strong> are</p>
<ol>
<li><a href="http://www.caucho.com/projects/candi/">CanDI</a></li>
<li><a href="http://seamframework.org/Weld/Development">Weld</a></li>
<li><a href="http://openwebbeans.apache.org">OpenWebBeans</a></li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://dominikdorn.com/2010/08/cdi-weld-beans-xml-xsddtd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JPA2 Abstract DAO,  Criteria Query &amp; the &#8220;like&#8221; Operator</title>
		<link>http://dominikdorn.com/2010/06/jpa2-abstract-dao-criteria-query-like-operator/</link>
		<comments>http://dominikdorn.com/2010/06/jpa2-abstract-dao-criteria-query-like-operator/#comments</comments>
		<pubDate>Wed, 16 Jun 2010 13:48:17 +0000</pubDate>
		<dc:creator>Dominik Dorn</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaEE6]]></category>
		<category><![CDATA[Abstract DAO]]></category>
		<category><![CDATA[DAO]]></category>
		<category><![CDATA[EclipseLink]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JPA2]]></category>
		<category><![CDATA[Persistence]]></category>

		<guid isPermaLink="false">http://dominikdorn.com/?p=312</guid>
		<description><![CDATA[Shows an Abstract DAO realized with JPA2. Also includes a method findByAttributes which leverages JPA2s CriteriaQuerys and the like Operator. ]]></description>
			<content:encoded><![CDATA[<p>For a project at the university, I had to implement an abstract search in an abstract JPA Dao. </p>
<p>Maybe this class comes handy for some of you</p>
<pre lang="java" line='1'>
package com.dominikdorn.rest.dao;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.*;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Dominik Dorn
 */
public class AbstractJpaDao<TYPE> {
    @PersistenceContext
    protected EntityManager em;

    protected Class entityClass;

    public Class getEntityClass() {
        return entityClass;
    }

    public void setEntityClass(Class entityClass) {
        this.entityClass = entityClass;
    }

    public AbstractJpaDao() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<TYPE>) genericSuperclass.getActualTypeArguments()[0];
    }

    public AbstractJpaDao(Class clazz) {
        this.entityClass = clazz;
    }

    public EntityManager getEm() {
        return em;
    }

    public AbstractJpaDao setEm(EntityManager em) {
        this.em = em;
        return this;
    }

    @Override
    public TYPE persist(TYPE item) {
        if (item == null)
            throw new PersistenceException("Item may not be null");
        em.persist(item);
        return item;
    }

    @Override
    public TYPE update(TYPE item) {
        if (item == null)
            throw new PersistenceException("Item may not be null");

        em.merge(item);
        return item;
    }

    @Override
    public List<TYPE> getAll() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return em.createQuery(cq).getResultList();
    }

    @Override
    public TYPE getById(Long id) {
        if (id == null || id < 1)
            throw new PersistenceException("Id may not be null or negative");

        return (TYPE) em.find(entityClass, id);
    }

    @Override
    public void delete(TYPE item) {
        if (item == null)
            throw new PersistenceException("Item may not be null");

        em.remove(em.merge(item));
    }

    @Override
    public List<TYPE> findByAttributes(Map<String, String> attributes) {
        List<TYPE> results;
        //set up the Criteria query
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<TYPE> cq = cb.createQuery(getEntityClass());
        Root<TYPE> foo = cq.from(getEntityClass());

        List<Predicate> predicates = new ArrayList<Predicate>();
        for(String s : attributes.keySet())
        {
            if(foo.get(s) != null){
                predicates.add(cb.like((Expression) foo.get(s), "%" + attributes.get(s) + "%" ));
            }
        }
        cq.where(predicates.toArray(new Predicate[]{}));
        TypedQuery<TYPE> q = em.createQuery(cq);

        results = q.getResultList();
        return results;
    }
}
</pre>
<p>To instantiate this for an Entity, e.g. &#8220;Item&#8221;, simply do this</p>
<pre lang="java" line="1">
  // get an entityManager somewhere here
  AbstractJpaDao<Item> dao = new AbstractJpaDao<Item>();
dao.setEm(em);
</pre>
<p>now you can use this Data Access Object for your persistence stuff. </p>
<p>To now <strong>search for entities</strong> in your DB, you can use the method <strong>findByAttributes</strong> which takes a map&lt;String,String&gt; and searches for appropriate items.<br />
If your Entity looks like this</p>
<pre lang='java' line='1'>
@Entity
public class Item {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "ITEM_GEN")
    @SequenceGenerator(name="ITEM_GEN", allocationSize=25, sequenceName = "item_seq")
    private long id;

    @Basic
    private String name;

    @Basic
    private String description;

    @Basic
    private Integer size;
// constructors, getters, setters
</pre>
<p>you could search for an item which names contain &#8220;test&#8221; like this</p>
<pre lang='java' line='1'>

Map<String,String> attr = new Hashmap<String,String>();
attr.put("name", "test");
List<Item> results = dao.findByAttributes(attr);
</pre>
<p>which comes quite handy in my opinion. Also note, that <strong>you don&#8217;t have to pre-generate your JPA2 Model classes</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://dominikdorn.com/2010/06/jpa2-abstract-dao-criteria-query-like-operator/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Essential Glassfish Performance Tuning Blogs</title>
		<link>http://dominikdorn.com/2010/06/essential-glassfish-performance-tuning-blogs/</link>
		<comments>http://dominikdorn.com/2010/06/essential-glassfish-performance-tuning-blogs/#comments</comments>
		<pubDate>Mon, 14 Jun 2010 14:42:53 +0000</pubDate>
		<dc:creator>Dominik Dorn</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaEE6]]></category>
		<category><![CDATA[Open Source]]></category>

		<guid isPermaLink="false">http://dominikdorn.com/?p=308</guid>
		<description><![CDATA[This post tries to collect a list of important links for everyone wanting to optimize his/her Glassfish v3 Server for production use.]]></description>
			<content:encoded><![CDATA[<p>In my time on the Glassfish users mailinglist, I came across some important links for everyone setting up a Glassfish server for production.</p>
<p>This is my personal bookmarks list, that may also serve its purpose to others.  </p>
<ol>
<li><a href="http://jfarcand.wordpress.com/2009/11/27/putting-glassfish-v3-in-production-essential-surviving-guide/">Putting Glassfish v3 in Production &#8211; Essential surviving Guide</a>: This post describes basic performance enhancements you can get with changing settings in your domain.xml configuration and adjusting jvm settings</li>
<li><a href="http://blogs.sun.com/binublog/entry/monitoring_in_glassfish">Monitoring in Glassfish</a>: This post shows how to further enhance the thread pool settings for your Glassfish domain and how to determine the correct settings for your system</li>
<li><a href="http://dominikdorn.com/2010/04/tomcat-glassfish-jetty-port-80-iptables-nat/">Tomcat/Glassfish/Jetty on Port 80 with IPTables + NAT</a>: This post describes, how you can run your Glassfish hosted webapps on Port 80 without running a Apache or other web server in front of it, thus you are able to fully utilize every aspect of Glassfishs new asynchronous architecture without always have to think of that old Indian making problems (Comet etc.)</li>
<li><a href="http://forums.java.net/jive/thread.jspa?messageID=474193">Blog Post on Java.net</a>: This post by user &quot;radix_zero&quot; also suggests a few other tricks, like creating multiple connection pools to the same data source or running multiple real-domains, each in a own JVM.</li>
<li><a href="http://forums.java.net/jive/thread.jspa?messageID=475828">Another Post on Java.net</a>: The thread points out that one should use distinct thread pools for each http-listener to prevent locking between the listeners</li>
</ol>
<p>This post will be updated with new additional &#038; helpful links, as soon as I get aware of them. </p>
<p><strong>Do you have interesting links? Post them in the comments!</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://dominikdorn.com/2010/06/essential-glassfish-performance-tuning-blogs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Maven + JUnit + ClassFormatError: Absent Code attribute in method that is not native or abstract in class file</title>
		<link>http://dominikdorn.com/2010/05/maven-junit-classformaterror-absent-code-attribute/</link>
		<comments>http://dominikdorn.com/2010/05/maven-junit-classformaterror-absent-code-attribute/#comments</comments>
		<pubDate>Tue, 11 May 2010 19:39:29 +0000</pubDate>
		<dc:creator>Dominik Dorn</dc:creator>
				<category><![CDATA[JSF]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaEE6]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mail]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[servlet]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://dominikdorn.com/?p=294</guid>
		<description><![CDATA[Solutions to the Absent Code attribute problem often encountered when trying to do unit testing with Maven&#038;/JUnit.]]></description>
			<content:encoded><![CDATA[<p>Once in a while one stumbles upon an error message like this</p>
<pre>
java.lang.<strong>ClassFormatError</strong>: <strong>Absent Code attribute</strong> in method that is not native or abstract in class file javax/mail/Session
</pre>
<p>This happens if your code compiles against incomplete classes, like the JavaEE6 Api and your Unit tests try to access code thats not there. JUnit will simply fail and mark the test as error, printing something like this</p>
<pre>
Tests in error:
  initializationError(com.dominikdorn.dc.passwordReset.SimplePasswordResetServiceTest)
</pre>
<p>and the corresponding surefire text file starts like this:</p>
<pre>
-------------------------------------------------------------------------------
Test set: com.dominikdorn.dc.passwordReset.SimplePasswordResetServiceTest
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.022 sec <<< FAILURE!
initializationError(com.dominikdorn.dc.passwordReset.SimplePasswordResetServiceTest)  Time elapsed: 0.005 sec  <<< ERROR!
java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/mail/Session
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
        at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
....
</pre>
<p><strong>The Solution</strong><br />
You have to compile against real-implementations of the classes. You do that by adding those dependencies before the most generic dependency in your pom.xml</p>
<p>As example, we add javax.mail BEFORE javaee6-api like this</p>
<pre lang='xml' line='1'>
<project ...>
...
    <dependencies>

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
</project>
</pre>
<p>If you are deploying your App on an Appserver like Glassfish or JBoss AS, leave the scope of javax.mail:mail as provided to prevent the inclusion of the jar in the final webapp. </p>
<p>I now list required dependencies for various Absent Code Errors I've encountered and still encountering. This post will be updated every time I solve another of these problems.</p>
<p><strong>JavaMail</strong>: <strong>javax/mail/Session</strong></p>
<pre lang='xml' line='1'>
<project ...>
...
    <dependencies>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>
</pre>
<p><strong>Servlet 3.0</strong></p>
<pre lang='xml' line='1'>
<project ...>
...
    <dependencies>
               <dependency>
                       <groupId>org.glassfish</groupId>
                       <artifactId>javax.servlet</artifactId>
                       <version>3.0</version>
                       <scope>provided</scope>
               </dependency>
...
    </dependencies>
....
    <repositories>
               <!-- Required until the Servlet 3.0 API can be resolved in Central -->
               <repository>
                       <id>Glassfish</id>
                       <name>Glassfish Maven2 Repository</name>
                       <url>http://download.java.net/maven/glassfish/</url>
               </repository>
    </repositories>
 </project>
</pre>
<p><strong>JPA2</strong>: <strong>javax/persistence/PersistenceException</strong></p>
<pre lang="xml" line="1">
<dependencies>...
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
            <scope>provided</scope>
        </dependency>
...</dependencies>
..
<repositories>
...
    <repositories>
...
        <repository>
            <id>eclipse</id>
            <name>Eclipse Maven Repository</name>
            <url>http://www.eclipse.org/downloads/download.php?r=1&amp;nf=1&amp;file=/rt/eclipselink/maven.repo</url>
        </repository>
    </repositories>
</pre>
<p><strong>JAX-RS</strong>: <strong>javax/ws/rs/core/UriBuilder</strong></p>
<pre lang='xml' line='1'>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>1.1.5</version>
            <scope>provided</scope>
        </dependency>
<!-- for json support -->
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>1.1.5</version>
            <scope>provided</scope>
        </dependency>
<!-- for testing -->
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-test-framework</artifactId>
            <version>1.1.5.1</version>
            <scope>test</scope>
        </dependency>
</pre>
<p>more to come soon!</p>
]]></content:encoded>
			<wfw:commentRss>http://dominikdorn.com/2010/05/maven-junit-classformaterror-absent-code-attribute/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>CDI/Weld manual lookup</title>
		<link>http://dominikdorn.com/2010/04/cdi-weld-manual-bean-lookup/</link>
		<comments>http://dominikdorn.com/2010/04/cdi-weld-manual-bean-lookup/#comments</comments>
		<pubDate>Wed, 21 Apr 2010 18:04:28 +0000</pubDate>
		<dc:creator>Dominik Dorn</dc:creator>
				<category><![CDATA[JSF]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaEE6]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF2]]></category>
		<category><![CDATA[Weld]]></category>

		<guid isPermaLink="false">http://dominikdorn.com/?p=279</guid>
		<description><![CDATA[This post describes how to manually lookup beans in a CDI / Weld managed environment when you are somewhere where a simple @Inject does not work because the object itself is not managed by CDI / Weld. ]]></description>
			<content:encoded><![CDATA[<p>So, you&#8217;re ended up in a situation, where you are somewhere (e.g. a javax.faces.Converter) where you are <strong>unable to simple @Inject SomeClass</strong> ? </p>
<p>I had the problem, that I had a FacesConverter like this:</p>
<pre lang="java" line='1'>
import javax.annotation.ManagedBean;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.inject.Inject;

@FacesConverter(forClass = AvailableCountry.class)
@ManagedBean // does not help <img src='http://dominikdorn.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />
@RequestScoped // does not help <img src='http://dominikdorn.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />
public class AvailableCountryConverter implements Converter
{
	@Inject
	AvailableCountryDao dao;

	@PostConstruct
	public void postConstruct()
	{
		System.out.println("calling postConstruct");
	}

	public Object getAsObject(FacesContext facesContext, UIComponent
			component, String value) {
		if (value == null || value.length() == 0) {
			return null;
		}
		return dao.find(getKey(value));
	}

	Long getKey(String value) {
		Long key;
		key = Long.valueOf(value);
		return key;
	}

	String getStringKey(long value) {
		StringBuffer sb = new StringBuffer();
		sb.append(value);
		return sb.toString();
	}

	public String getAsString(FacesContext facesContext, UIComponent
			component, Object object) {
		if (object == null) {
			return null;
		}
		if (object instanceof AvailableCountry) {
			AvailableCountry o = (AvailableCountry) object;
			return getStringKey(o.getCountry().getId());
		} else {
			throw new IllegalArgumentException("object " + object + "
					is of type " + object.getClass().getName() + "; expected type: " +
					AvailableCountry.class.getName());
		}
	}
}
</pre>
<p>But my <strong>DAO was <u>not</u> injected</strong>, nor was the postConstruct method triggered by CDI.</p>
<p>Why?<br />
<strong>Because the bean is not managed by CDI</strong>, not even when annotating it with @ManagedBean because it gets created by the JSF-Lifecycle and not by CDI. </p>
<p>Well.. but <strong>how to manually lookup a Bean with CDI / Weld? </strong></p>
<p>First, you need to get the <strong>BeanManager</strong>. When you have a <strong>FacesContext</strong> (like in the converter above), you can get it like this:</p>
<pre lang="java" line="1">
    public BeanManager getBeanManager()
    {
        return (BeanManager)
              ((ServletContext) facesContext.getExternalContext().getContext())
                   .getAttribute("javax.enterprise.inject.spi.BeanManager");
    }
</pre>
<p>If you don&#8217;t have access to a FacesContext, ServletContext or similar, you can<strong> lookup the BeanManager through JNDI</strong></p>
<pre lang="java" line='1'>
    public BeanManager getBeanManager()
    {
        try{
            InitialContext initialContext = new InitialContext();
            return (BeanManager) initialContext.lookup("java:comp/BeanManager");
        catch (NamingException e) {
            log.error("Couldn't get BeanManager through JNDI");
            return null;
        }
    }
</pre>
<p>After you&#8217;ve got your <strong>BeanManager</strong>, simply <strong>lookup</strong> your Bean like this:<br />
(In my case, I wanted to lookup a bean with the type AvailableCountryDao)<br />
<strong>Type-based CDI manual lookup</strong></p>
<pre lang='java' line='1'>
    public AvailableCountryDao getFacade()
    {
        BeanManager bm = getBeanManager();
        Bean<AvailableCountryDao> bean = (Bean<AvailableCountryDao>) bm.getBeans(AvailableCountryDao.class).iterator().next();
        CreationalContext<AvailableCountryDao> ctx = bm.createCreationalContext(bean);
        AvailableCountryDao dao = (AvailableCountryDao) bm.getReference(bean, AvailableCountryDao.class, ctx); // this could be inlined, but intentionally left this way
        return dao;
    }
</pre>
<p>Thanks to my friend <a href="http://ocpsoft.com/">Lincoln Baxter, III</a> for the snipped. </p>
<p><strong>Name-based CDI manual lookup</strong></p>
<pre lang='java' line='1'>
    public Object getBeanByName(String name) // eg. name=availableCountryDao
    {
        BeanManager bm = getBeanManager();
        Bean bean = bm.getBeans(name).iterator().next();
        CreationalContext ctx = bm.createCreationalContext(bean); // could be inlined below
        Object o = bm.getReference(bean, bean.getClass(), ctx); // could be inlined with return
        return o;
    }
</pre>
<p>So, now you&#8217;re able to manually lookup beans with CDI.<br />
In case you have the same problem (with Converters/Validators) like I had above, checkout <a href="http://seamframework.org/Seam3/FacesModule">Seam Faces</a>, where this <strong>problem already is fixed</strong>,<br />
meaning your <strong>@ManagedBean annotated Converter/Validator is working as expected with @Inject, @PostConstruct &#038; @PreDestroy</strong> <img src='http://dominikdorn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
]]></content:encoded>
			<wfw:commentRss>http://dominikdorn.com/2010/04/cdi-weld-manual-bean-lookup/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>File Templates for web.xml &amp; web-fragment.xml (Servlet 2.3, 2.4, 2.5 + 3.0)</title>
		<link>http://dominikdorn.com/2010/03/web-xml-web-fragment-xml-2-3-2-4-2-5-3-0/</link>
		<comments>http://dominikdorn.com/2010/03/web-xml-web-fragment-xml-2-3-2-4-2-5-3-0/#comments</comments>
		<pubDate>Thu, 25 Mar 2010 12:20:55 +0000</pubDate>
		<dc:creator>Dominik Dorn</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaEE6]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://dominikdorn.com/?p=254</guid>
		<description><![CDATA[Here you'll find the web.xml headers for servlet 2.3, 2.4, 2.5 and 3.0 + web-fragment.xml for servlet 3.0]]></description>
			<content:encoded><![CDATA[<p>As I sometimes need these, I have compiled a list of the valid headers of the web.xml and web-fragment.xml file for servlet version 2.3 until 3.0.<br />
Maybe you find them as handy as I do.</p>
<p>web.xml v2.3</p>
<pre lang="xml" line="1">
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

</web-app>
</pre>
<p>web.xml v2.4</p>
<pre lang="xml" line="1">
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

</web-app>
</pre>
<p>web.xml v2.5</p>
<pre lang="xml" line="1">
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"

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-app_2_5.xsd"

version="2.5">

</web-app>
</pre>
<p>web.xml v3.0</p>
<pre lang="xml" line="1">
<?xml version="1.0" encoding="UTF-8"?>

<web-app
        version="3.0"
        xmlns="http://java.sun.com/xml/ns/javaee"
        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-app_3_0.xsd">

</web-app>
</pre>
<p>web-fragment.xml:</p>
<pre lang="xml" line="1">
<web-fragment xmlns="http://java.sun.com/xml/ns/javaee"
              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-fragment_3_0.xsd" version="3.0">

</web-fragment>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://dominikdorn.com/2010/03/web-xml-web-fragment-xml-2-3-2-4-2-5-3-0/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using complex urls &amp; regular expressions with PrettyFaces</title>
		<link>http://dominikdorn.com/2010/03/complex-urls-regular-expressions-validators-prettyfaces/</link>
		<comments>http://dominikdorn.com/2010/03/complex-urls-regular-expressions-validators-prettyfaces/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 20:15:24 +0000</pubDate>
		<dc:creator>Dominik Dorn</dc:creator>
				<category><![CDATA[JSF]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaEE6]]></category>
		<category><![CDATA[Facelets]]></category>
		<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF2]]></category>
		<category><![CDATA[PrettyFaces]]></category>
		<category><![CDATA[Regex]]></category>
		<category><![CDATA[Validator]]></category>

		<guid isPermaLink="false">http://dominikdorn.com/?p=249</guid>
		<description><![CDATA[In this post you will learn how to match complex urls with regular expressions and PrettyFaces in JSF2 Web Applications.]]></description>
			<content:encoded><![CDATA[<p>If you like to construct complex &#038; pretty urls with JSF2 &#038; PrettyFaces, you might be interested in the following few lines of code.</p>
<p>In our example, we want to match a URL like this one</p>
<pre lang='xml' line='1'>

http://www.studyguru.eu/at/tuwien/184.153--Entwurfsmethoden-fuer-verteilte-Systeme
</pre>
<p>Previously I tried to match it with a PrettyFaces Pattern/Regex like this:</p>
<pre lang="xml">
<pattern value="/([a-z]{2})/([a-z0-9\-_]*)/([a-z0-9\-_\.]*)\-\-.*"/>
</pre>
<p>But thankfully, PrettyFaces >2.0.4 supports directly populating the RequestParams! </p>
<p>Configure your pretty-config like this:</p>
<pre lang='xml' line='1'>
<pretty-config xmlns="http://ocpsoft.com/prettyfaces/2.0.4"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://ocpsoft.com/prettyfaces/2.0.4
                http://ocpsoft.com/xml/ns/prettyfaces/ocpsoft-pretty-faces-2.0.4.xsd">
....

    <url-mapping id="coursePage">
<pattern value="/#{countryCode}/#{uniShortName}/#{courseId}--.*"/>
        <view-id>/path/to/coursePage.xhtml</view-id>
    </url-mapping>
....
</pre>
<p>and use JSF2&#8242;s viewParams like this:</p>
<pre lang='xml' line='1'>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
        PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:pretty="http://ocpsoft.com/prettyfaces"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.prime.com.tr/ui"
        >
<body>
<f:metadata>
    <f:viewParam id="countryCodeId"
                 required="true"
                 requiredMessage="Kein Land spezifiziert"
                 name="countryCode" value="#{coursePageBean.countryCode}"
            >
        <f:validateRegex pattern="([a-z]{2})"/>
    </f:viewParam>

    <f:viewParam id="universityCodeId"
                 required="true"
                 requiredMessage="Keine Hochschule spezifiziert"
                 name="uniShortName" value="#{coursePageBean.universityCode}"
            >
        <f:validateRegex pattern="([a-z0-9\-_]*)"/>
    </f:viewParam>
    <f:viewParam id="courseIdId"
                 required="true"
                 requiredMessage="Keine KursId spezifiziert"
                 name="courseId" value="#{coursePageBean.courseId}"
            >
        <f:validateRegex pattern="([a-z0-9\-_\.]*)"/>
    </f:viewParam>

    <f:event type="preRenderView" listener="#{coursePageBean.populate}"/>
</f:metadata>
<h1>coursePage</h1>

countryCode #{ coursePageBean.countryCode} <br/>
courseId #{coursePageBean.courseId}<br/>
universityCode #{coursePageBean.universityCode}<br/>
</body>
</html>
</pre>
<p>Voila! You now can match complex urls with PrettyFaces and apply all your custom validators<br />
to your Pretty URL <img src='http://dominikdorn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
]]></content:encoded>
			<wfw:commentRss>http://dominikdorn.com/2010/03/complex-urls-regular-expressions-validators-prettyfaces/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Disabling ;jsessionid url-appending Servlet 3.0</title>
		<link>http://dominikdorn.com/2010/03/disabling-jsessionid-url-appending-servlet-3-0/</link>
		<comments>http://dominikdorn.com/2010/03/disabling-jsessionid-url-appending-servlet-3-0/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 16:36:30 +0000</pubDate>
		<dc:creator>Dominik Dorn</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaEE6]]></category>

		<guid isPermaLink="false">http://dominikdorn.com/?p=245</guid>
		<description><![CDATA[But how to disable Session Tracking by URL? How to set it to Cookie only? Thats described in this article.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve noticed that google indexed various pages of mine with appended &#8220;;jsessionid=somehash&#8221;<br />
Thats not only ugly, but also a security risk. </p>
<p><strong>But how to disable Session Tracking by URL? How to set it to Cookie only ? </strong></p>
<p>Take this!</p>
<p><strong>Update: <a href="http://blogs.sun.com/jluehe/">Jan Luehe</a> showed me a way, how to do this in web.xml only &#8211; without a listener</strong></p>
<pre lang='xml' line='1'>
 <web-app ...>
    <session-config>
<tracking-mode>COOKIE</tracking-mode>
<tracking-mode>URL</tracking-mode>
<tracking-mode>SSL</tracking-mode>
    </session-config>
 </web-app>
</pre>
<p>if you prefer to do it programmatically (e.g. when doing a custom web-app configuration wizzard or something like this), do it this way:</p>
<pre lang="java" line="1">
package com.dominikdorn.dc.listeners;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.SessionTrackingMode;
import javax.servlet.annotation.WebListener;
import java.util.HashSet;
import java.util.Set;

/**
 * This Listener sets the tracking modes used by the servletContext
 */
@WebListener(value = "This listener sets the session tracking modes")
public class SetSessionTrackingModeListener implements ServletContextListener {

    // Public constructor is required by servlet spec

    public SetSessionTrackingModeListener() {
    }

    public void contextInitialized(ServletContextEvent sce) {
        Set<SessionTrackingMode> modes = new HashSet<SessionTrackingMode>();
        // modes.add(SessionTrackingMode.URL); // thats the default behaviour!
        modes.add(SessionTrackingMode.COOKIE);
//        modes.add(SessionTrackingMode.SSL); // this works only with client certs.
        sce.getServletContext().setSessionTrackingModes(modes);
    }

    public void contextDestroyed(ServletContextEvent sce) {
    }

}
</pre>
<p>Questions? Comments? Post them here!</p>
]]></content:encoded>
			<wfw:commentRss>http://dominikdorn.com/2010/03/disabling-jsessionid-url-appending-servlet-3-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>X-UA-Compatible Java Servlets / JSF</title>
		<link>http://dominikdorn.com/2010/03/x-ua-compatible-ie7-ie8-java-servlets-jsf/</link>
		<comments>http://dominikdorn.com/2010/03/x-ua-compatible-ie7-ie8-java-servlets-jsf/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 16:16:41 +0000</pubDate>
		<dc:creator>Dominik Dorn</dc:creator>
				<category><![CDATA[JSF]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaEE6]]></category>

		<guid isPermaLink="false">http://dominikdorn.com/?p=240</guid>
		<description><![CDATA[A User on the glassfish mailing list posted a question: I would like to aks it. How must set up ie8 compatibility mode in glassfish? This is the iis setting: Well&#8230; how to do that? Simply create a Servlet Filter! package com.dominikdorn.dc.filters; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.logging.Logger; @WebFilter(urlPatterns [...]]]></description>
			<content:encoded><![CDATA[<p>A User on the glassfish mailing list posted a question:</p>
<blockquote><p>
I would like to aks it. How must set up ie8 compatibility mode in glassfish?<br />
This is the iis setting:</p>
<pre lang="xml" line="0">
<system.webServer>
       <httpProtocol>
               <customHeaders>
                       <clear />
                       <add name="X-UA-Compatible" value="IE=EmulateIE7" />
               </customHeaders>
       </httpProtocol>
</system.webServer>
</pre>
</blockquote>
<p>Well&#8230; how to do that? </p>
<p>Simply create a Servlet Filter!</p>
<pre lang="java" line="1">
package com.dominikdorn.dc.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

@WebFilter(urlPatterns = {"/*"}, initParams = {@WebInitParam(name = "compatibilityMode", value = "IE=EmulateIE7")})
public class UserAgentCompatibleFilter implements javax.servlet.Filter {
    private Logger log = Logger.getLogger("UserAgentCompatibleFilter");
    private String compatibilityMode;

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        if (compatibilityMode != null) {
            HttpServletResponse res = (HttpServletResponse) resp;
            res.addHeader("X-UA-Compatible", compatibilityMode);
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
        compatibilityMode = config.getInitParameter("compatibilityMode");
        if (compatibilityMode == null) {
            log.warning("No CompatibilityMode set for UserAgentCompatibleFilter, thus disabling it");
        }
    }
}
</pre>
<p>If you&#8217;re not using Servlet 3.0, simply comment out the @WebServlet annotation. If you want to customize<br />
the header, add this to your web.xml and modify it, so that it suit your needs.</p>
<pre lang="xml" line="1">
    <filter>
        <filter-name>UserAgentCompatibleFilter</filter-name>
        <filter-class>com.dominikdorn.dc.filters.UserAgentCompatibleFilter</filter-class>
        <init-param>
<param-name>compatibilityMode</param-name>
<param-value>IE=EmulateIE7</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>UserAgentCompatibleFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</pre>
<p>To see if it works, compile and redeploy your app.. you can then test it, e.g. with curl:</p>
<pre lang="bash" line="0">
curl -D - http://localhost:8080/info.xhtml
HTTP/1.1 200 OK
X-Powered-By: Servlet/3.0
Server: GlassFish v3
Set-Cookie: JSESSIONID=3afbe6498aa3f495e8340d8e67ef; Path=/
X-UA-Compatible: IE=EmulateIE7
X-Powered-By: JSF/2.0
Content-Type: text/html;charset=UTF-8
Content-Length: 2997
Date: Tue, 09 Mar 2010 16:09:03 GMT
</pre>
<p>Suggestions? Comment here!</p>
]]></content:encoded>
			<wfw:commentRss>http://dominikdorn.com/2010/03/x-ua-compatible-ie7-ie8-java-servlets-jsf/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Really basic file upload with HTML + JSF2</title>
		<link>http://dominikdorn.com/2010/03/really-basic-file-upload-with-html-jsf2/</link>
		<comments>http://dominikdorn.com/2010/03/really-basic-file-upload-with-html-jsf2/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 18:34:12 +0000</pubDate>
		<dc:creator>Dominik Dorn</dc:creator>
				<category><![CDATA[JSF]]></category>
		<category><![CDATA[JavaEE6]]></category>

		<guid isPermaLink="false">http://dominikdorn.com/?p=234</guid>
		<description><![CDATA[The &#8220;ironic programmer&#8221; published an article, how to create a really basic file upload with jsf2. He has not created any custom tags, but simply added a file-input field in his view and made the server populate a byte-array in his bean. His post was influenced by Uploading files with JSF 2.0 and Servlet 3.0 [...]]]></description>
			<content:encoded><![CDATA[<p>The &#8220;ironic programmer&#8221; published an article, <a href="http://ironicprogrammer.blogspot.com/2010/03/file-upload-in-jsf2.html">how to create a really basic file upload with jsf2</a>. He has not created any custom tags, but simply added a file-input field in his view and made the server populate a byte-array in his bean. </p>
<p>His post was influenced by <a href="http://balusc.blogspot.com/2009/12/uploading-files-with-jsf-20-and-servlet.html">Uploading files with JSF 2.0 and Servlet 3.0</a> by <a href="http://balusc.blogspot.com">BalusC</a>. </p>
<p>He probably missed our <a href="http://github.com/domdorn/fileUploadServlet3JSF2">JSF2 FileUpload-Github-Project</a> where the taglib is ready for usage and really simple to integrate.</p>
<p>Still, thumbs up for the nice post!</p>
]]></content:encoded>
			<wfw:commentRss>http://dominikdorn.com/2010/03/really-basic-file-upload-with-html-jsf2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
