/blog.html/Outjected Blog2016-09-27T15:20:58-06:00https://www.outjected.com/blog/2013/08/08/embrace-the-jpa-2-criteria-api.htmlEmbrace the JPA 2 Criteria API2016-09-27T15:20:58-06:002013-08-08T00:00:00+00:00Cody Lerum
A bit of history and a problem statement of sorts
I’ve been a big fan of criteria queries for writing dynamic JPA
queries for a long time. Sure I could make the same thing happen with a bit of logic and a whole lot of string
concatenation but that gets old really quick. My first experience with criteria queries was with Hibernate 3 so lets
start there and we will follow a query from SQL to JPA 2 Criteria.
We are all probably all most familiar with SQL so lets make that our starting point.
Assuming we have table in the database of tasks lets select...
<div class="sect3">
<h4 id="_a_bit_of_history_and_a_problem_statement_of_sorts">A bit of history and a problem statement of sorts</h4>
<div class="paragraph">
<p>I’ve been a big fan of criteria queries for writing dynamic <a href="http://en.wikipedia.org/wiki/Java_Persistence_API">JPA</a>
queries for a long time. Sure I could make the same thing happen with a bit of logic and a whole lot of string
concatenation but that gets old really quick. My first experience with criteria queries was with Hibernate 3 so lets
start there and we will follow a query from SQL to JPA 2 Criteria.</p>
</div>
<div class="paragraph">
<p>We are all probably all most familiar with <a href="http://en.wikipedia.org/wiki/Sql">SQL</a> so lets make that our starting point.</p>
</div>
<div class="paragraph">
<p>Assuming we have table in the database of tasks lets select those which are assigned to a specific user which have
not been closed.</p>
</div>
<div class="paragraph">
<p>select * from Task t where t.assignee=1 and t.dateClosed is null</p>
</div>
<div class="paragraph">
<p>However, we are living in an ORM world though so lets see it in
<a href="http://en.wikipedia.org/wiki/Java_Persistence_Query_Language">JPQL</a>
(same syntax in <a href="http://en.wikipedia.org/wiki/Hibernate_(Java)">HQL</a>)</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">List<Task> tasks = entityManager.createQuery("select t from Task t where t.assignee=:user"
+ " and t.dateClosed is null",Task.class).setParameter("user", myUser).getResultList();</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now lets migrate our query to use the Hibernate 3 Criteria API</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">Session session = (Session) entityManager.getDelegate();
Criteria criteria = session.createCriteria(Task.class);
criteria.add(Restrictions.eq("assignee", myUser));
criteria.add(Restrictions.isNull("dateClosed"));
List<Task> tasks = criteria.list();</code></pre>
</div>
</div>
<div class="paragraph">
<p>Obviously this is more verbose but it also has some readability advantages in my opinion. Even if you disagree with
regard to readability you can see that adding restrictions to the query in a programmatic way is much simpler than with
JPQL/HQL.</p>
</div>
<div class="paragraph">
<p>However the one thing always bugged with with JPQL/HQL and Hibernate’s Criteria API is that everything is done with strings
and doing things with strings makes refactoring difficult even with good tooling. This is Java and we want something
type-safe.</p>
</div>
</div>
<div class="sect3">
<h4 id="_jpa_2_criteria_api_to_the_rescue">JPA 2 Criteria API to the rescue.</h4>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Task> cq = cb.createQuery(Task.class);
Root<Task> root = cq.from(Task.class);
List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.equal(root.get(Task_.assignee), myUser));
predicates.add(cb.isNull(root.get(Task_.dateClosed));
cq.where(predicates.toArray(new Predicate[predicates.size()]));
List<Task> tasks = em.createQuery(cq).getResultList();</code></pre>
</div>
</div>
<div class="paragraph">
<p>I will readily admit that upon first taking a look at the JPA 2.0 Criteria API I was really turned off by its verbosity and
complexity. I was turned off so much that I flat out ignored it for the first six months it was available to me. I
still however desired a type-safe way to write my queries so that they would hold up better during refactoring.</p>
</div>
<div class="paragraph">
<p>Finally I blocked out a day to tinker with the API and see if I could convert a few of my more simple queries. After only a few
minutes I was off and running and haven’t looked back. Here are a couple things I’ve learned during my time tinkering.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The code is longer but I can read and understand it much faster than a JPQL/HQL query.</p>
</li>
<li>
<p>I can write a criteria query faster due to IDE code completion and not having to review my entity structure to find the name
of that specific column I’m trying to reference.</p>
</li>
<li>
<p>As the complexity of the query goes up the benefits of the criteria query grow, but you will be forced to do some learning.
I have yet to find a query that I have not been able to convert. The API was very well thought out from this perspective.</p>
</li>
<li>
<p>My speed of development is faster almost 100% of the time as my criteria queries execute and return the desired results on the
first try. I can’t say the same for my JPQl/HQL which are parsing a potentially very long string with lots of
opportunities for syntax issues.</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_it_isn_t_however_all_sunshine_and_lollipops">It isn’t however all sunshine and lollipops</h4>
<div class="paragraph">
<p>This isn’t to say the API is perfect. It actually fights programmatic creation of queries a little bit. The API is designed
so that the base of your query can reused. For example each time you call the criteriaQuery.where(Predicate... predicates)
it replaces what was previously set. To work around this you need to store your predicates in a separate list and then
add them all at once in array form (varargs). It would be nice if a criteriaQuery.where(List<Predicate> predicates) was
exposed like it is for groupBy and orderBy. Additionally here are some other pain points.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Why is a <a href="http://docs.oracle.com/javaee/6/api/javax/persistence/criteria/Fetch.html">Fetch<Z,X></a> not a
<a href="http://docs.oracle.com/javaee/6/api/javax/persistence/criteria/Path.html">Path</a> like
<a href="http://docs.oracle.com/javaee/6/api/javax/persistence/criteria/Join.html">Join<Z,X></a> is? This means I need to define my "join"
twice it I want it "join fetched". Hopefully this is fixed in <a href="http://jcp.org/en/jsr/detail?id=338">JPA 2.1</a></p>
</li>
<li>
<p><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=387956">Metamodel generation is broken in Eclipse</a>. It doesn’t handle the
cyclic nature of the metamodel classes. Thus when I do a project clean I will end up with 20 or so import failed errors.
These are easily resolved by making a meaningless edit to the class to trigger an incremental build but it shouldn’t be this way.</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_just_do_it">Just do it</h4>
<div class="paragraph">
<p>Hopefully I’ve inspired you to take another look if you’ve previous dismissed the API as I had. Block out a few hours
and give it a shot. I’ll try to share my utility classes that I’ve written in an upcoming post that have made things a
it easier for me, but in the meantime you really should get down and dirty with the api to understand it fully.</p>
</div>
<div class="paragraph">
<p>You’ll be glad you did.</p>
</div>
</div>
https://www.outjected.com/blog/2012/12/13/another-mod-proxy-jboss-how-to.htmlJBoss AS7 with Apache + SSL2016-09-27T15:20:58-06:002012-12-13T00:00:00+00:00Cody Lerum
Why would you want to do this?
After years of having my users connect natively to JBoss application servers in production I have had a few little
issues that nagged at me. One of the biggest is that there is not a way to show a custom error page to my users when
the JBoss server is down. Second is that I try and limit as much as I can specific configuration details that go into
the server configuration so that upgrading between minor releases does not require a lot of configuration editing.
Setting up SSL certificates and modifying the default server ports qualifies as...
<div class="sect3">
<h4 id="_why_would_you_want_to_do_this">Why would you want to do this?</h4>
<div class="paragraph">
<p>After years of having my users connect natively to JBoss application servers in production I have had a few little
issues that nagged at me. One of the biggest is that there is not a way to show a custom error page to my users when
the JBoss server is down. Second is that I try and limit as much as I can specific configuration details that go into
the server configuration so that upgrading between minor releases does not require a lot of configuration editing.
Setting up SSL certificates and modifying the default server ports qualifies as hacking up the standard configuration
in my book so that is something I would like to limit/avoid.</p>
</div>
</div>
<div class="sect3">
<h4 id="_the_goal">The Goal</h4>
<div class="paragraph">
<p>What we are ultimately trying to do is have an Apache web server handle all the communication between the user and our
system. This communication will be secured via SSL. The apache server however has no real content so it will "proxy"
the requests to our JBoss application server. The application server will be as simple as possible and will not run SSL.</p>
</div>
</div>
<div class="sect3">
<h4 id="_other_details">Other details</h4>
<div class="ulist">
<ul>
<li>
<p>Our project is named foo</p>
</li>
<li>
<p>Requests come to https://foo.outjected.com and we don’t want to have our users go to https://foo.outjected.com/foo/
so our web-app context root is going to be "/"</p>
</li>
<li>
<p>We will redirect you to https://foo.outjected.com if you happen to browse to the non-secure http://foo.outjected.com</p>
</li>
<li>
<p>We are going to configure the JBoss server with a virtual host so it can support more than one app if needed.</p>
</li>
<li>
<p>We want to serve our own error page if the JBoss server cannot process our request due to being down.</p>
</li>
</ul>
</div>
<div class="imageblock">
<div class="content">
<img src="https://www.outjected.com/blog/2012/12/13/apache_to_jboss_as.svg" alt="apache to jboss as" />
</div>
</div>
<div class="paragraph">
<p>This little example is going to be using Ubuntu 12.04.1 LTS and JBoss AS 7.1.3.Final but should be compatible with similar setups.</p>
</div>
</div>
<div class="sect3">
<h4 id="_let_s_do_it">Let’s do it.</h4>
<div class="paragraph">
<p>I’m going to assume you have a bare bones Apache 2+ server and JBoss AS7 server setup. If you don’t then search around
for some guides. This blog is interested in how to pair them, not the basic setup of each. You should also have a
working application and some basic knowledge of how to deploy on AS7. This isn’t meant to be a soup to nuts guide
for building and deploying your application.</p>
</div>
</div>
<div class="sect3">
<h4 id="_apache_prep">Apache Prep</h4>
<div class="paragraph">
<p>First create a new directory for our non-proxy (error pages) content /var/www/foo.outjected.com</p>
</div>
<div class="paragraph">
<p>Go ahead and create a simple error page at /var/www/foo.outjected.com/errors/503.html. This is the page that will be
served if the app server is down.</p>
</div>
<div class="paragraph">
<p>Run the following commands to enable the needed modules in apache</p>
</div>
<div class="paragraph">
<p>a2enmod proxy<br />
a2enmod proxy_ajp<br />
a2enmod ssl<br /></p>
</div>
<div class="paragraph">
<p>Next go into /etc/apache2/sites-available and create a new file foo.outjected.com+. For this example I’m using a
single server so the server I’m proxying to is localhost Your config may/will/should vary.</p>
</div>
<div class="listingblock">
<div class="content">
<pre><VirtualHost *:80>
ServerName foo.outjected.com
Redirect / https://foo.outjected.com
</VirtualHost>
<VirtualHost *:443>
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/foo.outjected.com.pem
ServerName foo.outjected.com
ProxyRequests Off
ProxyPreserveHost On
ProxyPassReverseCookiePath / /
ProxyPass /errors/ !
ProxyPass / ajp://localhost:8009/
ProxyPassReverse / ajp://localhost:8009/
ErrorDocument 503 /errors/503.html
DocumentRoot /var/www/foo.outjected.com
ErrorLog /var/log/apache2/foo.outjected.com_errors.log
</VirtualHost></pre>
</div>
</div>
<div class="paragraph">
<p>Now enable the site.</p>
</div>
<div class="paragraph">
<p>a2ensite foo.outjected.com</p>
</div>
<div class="paragraph">
<p>If you restart apache you should now see your 503 page as our JBoss server isn’t setup yet.</p>
</div>
</div>
<div class="sect3">
<h4 id="_setting_up_the_jboss_server">Setting up the JBoss Server</h4>
<div class="paragraph">
<p>My JBoss AS7 install is at /usr/local/jboss so adjust your paths as necessary.</p>
</div>
<div class="paragraph">
<p>Edit /usr/local/jboss/standalone/configuration/standalone.xml and make these two modifications under the web subsystem</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Add the ajp connector</p>
</li>
<li>
<p>Add a virtual-server entry for foo.outjected.com</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Should look something like this.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml"><subsystem xmlns="urn:jboss:domain:web:1.2" default-virtual-server="default-host" native="false">
<connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http"/>
<connector name="ajp" protocol="AJP/1.3" scheme="http" socket-binding="ajp" enabled="true"/>
<virtual-server name="default-host" enable-welcome-root="true">
<alias name="localhost"/>
<alias name="example.com"/>
</virtual-server>
<virtual-server name="foo" enable-welcome-root="false" default-web-module="foo">
<alias name="foo.example.com"/>
</virtual-server>
</subsystem></code></pre>
</div>
</div>
<div class="paragraph">
<p>Your EAR/WAR is going to need a jboss-web.xml (foo.war/WEB-INF/jboss-web.xml) which will define the virtual host
and set the context root</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml"><?xml version="1.0"?>
<!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 5.0//EN" "http://www.jboss.org/j2ee/dtd/jboss-web_5_0.dtd">
<jboss-web>
<context-root>/</context-root>
<virtual-host>foo</virtual-host>
</jboss-web></code></pre>
</div>
</div>
<div class="paragraph">
<p>Start up your JBoss server as normal and enjoy your new proxied setup.</p>
</div>
</div>
https://www.outjected.com/blog/2012/09/11/cdi-and-jsf-arent-best-friends-yet.htmlCDI and JSF aren't Best Friends Yet2016-09-27T15:20:58-06:002012-09-11T00:00:00+00:00Cody Lerum
Where I started banging my head into the table.
This specific issue has actually has jumped up and bit me a few times so I’ll just try explain the most recent one.
Basically I have a new object that I am creating through a JSF form page, and that object needs to have a default
value set at creation which is determined at runtime. For the sake of exposing this little issue lets assume that
this value needs to be used multiple times during the request and thus we will make the producer @RequestScoped
to avoid duplicate database calls.
To the code!
@ConversationScoped
@Named
public class CarPricerManager implements...
<div class="sect3">
<h4 id="_where_i_started_banging_my_head_into_the_table">Where I started banging my head into the table.</h4>
<div class="paragraph">
<p>This specific issue has actually has jumped up and bit me a few times so I’ll just try explain the most recent one.
Basically I have a new object that I am creating through a JSF form page, and that object needs to have a default
value set at creation which is determined at runtime. For the sake of exposing this little issue lets assume that
this value needs to be used multiple times during the request and thus we will make the producer @RequestScoped
to avoid duplicate database calls.</p>
</div>
</div>
<div class="sect3">
<h4 id="_to_the_code">To the code!</h4>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@ConversationScoped
@Named
public class CarPricerManager implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
@Active
private PriceBook activePriceBook;
private CarPricer carPricer;
public CarPricer getCarPricer() {
if(carPricer == null) {
carPricer = new CarPricer();
carPricer.setPriceBook(activePriceBook);
}
return carPricer;
}
}
public class PriceBooks {
@Produces
@RequestScoped
@Active
public PriceBook findActivePriceBook() {
return em.createQuery(.....).getSingleResult();
}
@Produces
@RequestScoped
@Named
public List<PriceBook> priceBooks() {
return em.createQuery(.....).getResultList();
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now lets show the JSF snippet to select our price book when creating our new CarPricer</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml"><h:selectOneMenu value="\#{carPricerManager.carPricer.priceBook}" required="true"
converter="PriceBookConverter">
<f:selectItem itemLabel="Choose" />
<f:selectItems value="\#{priceBooks}" var="_apb" itemLabel="\#{_apb.name}" />
</h:selectOneMenu></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_where_it_goes_wrong">Where it goes wrong.</h4>
<div class="paragraph">
<p>What we would expect to happen is the selectOneMenu would initially be selected with the value of our active price book.
However this isn’t going to be the case because the injection of our active price book does not give us an object of
PriceBook.java it gives us an <em>proxy</em> of PriceBook.java and the equals(...) that JSF is going to call
will not return true.</p>
</div>
</div>
<div class="sect2">
<h3 id="_why_it_goes_wrong">Why it goes wrong.</h3>
<div class="paragraph">
<p>The CDI EG has determined that there is not meaningful way to implement .equals() and .hashCode() on a proxy that
can delegate to the underlying bean (See <a href="https://issues.apache.org/jira/browse/OWB-458">OWB-458</a> &
<a href="https://issues.jboss.org/browse/WELD-695">WELD-695</a>). What this means is that two proxies of the same underlying bean
will be equal. However, two proxies to underlying beans which are equal according to .equals will not be equal.</p>
</div>
</div>
<div class="sect2">
<h3 id="_how_can_we_fix_this">How can we fix this?</h3>
<div class="paragraph">
<p>One solution would be to execute the .equals() on the converted value if a converter exists. However, the JSF RI
<a href="http://javaserverfaces.java.net">Mojarra</a> feels (<a href="http://java.net/jira/browse/JAVASERVERFACES-2393">JAVASERVERFACES-2393</a>)
that any proxy must should delegate equals, hashCode and toString to the proxied instance per
<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Proxy.html">java.lang.reflect.Proxy</a>. In the case of CDI the
underlying bean can change during the lifecycle of the proxy and thus delegating isn’t realistic. This appears to be
one of those places where the JSF and CDI expert groups need to step in and find a solution so that developers can
enjoy consistent and predictable behavior in their applications.</p>
</div>
</div>
<div class="sect2">
<h3 id="_a_solutions_that_work_now">A solutions that work now.</h3>
<div class="paragraph">
<p>By making the bean with the producers @RequestScoped and storing the values in the bean after initial population we
can have default dependent scoped producers which don’t produce proxies and hit the database only once.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@RequestScoped
public class PriceBooks {
private PriceBook activeBook;
private List<PriceBook> books;
@Produces
@Active
public PriceBook findActivePriceBook() {
if (activeBook == null)
activeBook = em.createQuery(.....).getSingleResult();
return activeBook;
}
@Produces
@Named
public List<PriceBook> priceBooks() {
if (books == null) {
books = em.createQuery(.....).getResultList();
return books;
}
}</code></pre>
</div>
</div>
</div>
https://www.outjected.com/blog/2012/07/15/seam-mail-3-1-1-final-released.htmlSeam Mail 3.1.1.Final Released2016-09-27T15:20:58-06:002012-07-15T00:00:00+00:00Cody Lerum
Obligatory Links and Compatibility
I’m happy to announce that I’ve released a minor update to Seam 3 Mail
versioned 3.1.1.Final. This is a minor
release which is compatible with Seam 3.1.0.Final.
Whats new?
The main goal of this release was to fill in some gaps in documentation as well as some minor bug fixes which popped up
since the 3.1.0.Final release. I’ve also added in a utility class called
MessageConverter
which allows you to read a MimeMessage back into the internal EmailMessage object used by Seam Mail. This opens up the
option for Seam Mail to receive messages in addition to sending them. Check out
Closed Issues
on the JIRA tracker...
<div class="sect3">
<h4 id="_obligatory_links_and_compatibility">Obligatory Links and Compatibility</h4>
<div class="paragraph">
<p>I’m happy to announce that I’ve released a minor update to <a href="http://www.seamframework.org/Seam3/Mail">Seam 3 Mail</a>
versioned <a href="https://repository.jboss.org/nexus/index.html#nexus-search;quick~seam-mail">3.1.1.Final</a>. This is a minor
release which is compatible with <a href="http://in.relation.to/Bloggers/JBossSeam31FinalReleased">Seam 3.1.0.Final</a>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_whats_new">Whats new?</h4>
<div class="paragraph">
<p>The main goal of this release was to fill in some gaps in documentation as well as some minor bug fixes which popped up
since the 3.1.0.Final release. I’ve also added in a utility class called
<a href="https://github.com/seam/mail/blob/develop/impl/src/main/java/org/jboss/seam/mail/util/MessageConverter.java">MessageConverter</a>
which allows you to read a MimeMessage back into the internal EmailMessage object used by Seam Mail. This opens up the
option for Seam Mail to receive messages in addition to sending them. Check out
<a href="https://issues.jboss.org/browse/SEAMMAIL/fixforversion/12318997#selectedTab=com.atlassian.jira.plugin.system.project%3Aversion-issues-panel">Closed Issues</a>
on the JIRA tracker for details.</p>
</div>
</div>
<div class="sect3">
<h4 id="_what_does_future_look_like">What does future look like?</h4>
<div class="paragraph">
<p>Seam 3 Mail will continue to provide releases in its current format until the time comes for it to transition to
<a href="http://incubator.apache.org/deltaspike/">Apache DeltaSpike</a>. In the meantime if you have features for fixes to contribute
just open a <a href="http://jira.jboss.org/browse/SEAMMAIL">JIRA</a> and I’ll be happy to work them in.</p>
</div>
</div>
<div class="sect3">
<h4 id="_how_about_an_example">How about an example?</h4>
<div class="paragraph">
<p>POP3+SSL to receive an MimeMessage and convert it. It’s basically for gmail but with values changed to protect the
innocent.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import org.jboss.seam.mail.core.EmailMessage;
import org.jboss.seam.mail.util.MessageConverter;
import com.sun.mail.pop3.POP3SSLStore;
public class Popper {
public static void main(String[] args) throws Exception {
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties pop3Props = new Properties();
pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
pop3Props.setProperty("mail.pop3.port", "995");
pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
URLName url = new URLName("pop3", "pop.example.com", 995, "", "foo@example.com", "mypass");
Session session = Session.getInstance(pop3Props, null);
Store store = new POP3SSLStore(session, url);
store.connect();
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.getMessages();
if (messages.length == 0) {
System.out.println("No Messages Found");
}
List<EmailMessage> emailMessages = new ArrayList<EmailMessage>();
for (Message m : messages) {
emailMessages.add(MessageConverter.convert(m));
}
inbox.close(false);
store.close();
}
}</code></pre>
</div>
</div>
</div>
https://www.outjected.com/blog/2012/07/07/sending-queued-mail-with-seam-mail.htmlSending Queued Mail with Seam Mail2016-09-27T15:20:58-06:002012-07-07T00:00:00+00:00Cody Lerum
The Problem
One of the more common questions that I see by users coming to "Seam 3 Mail":http://www.seamframework.org/Seam3/MailModule is about sending email asynchronously like was possible in "Seam 2":http://docs.jboss.org/seam/2.2.2.Final/reference/en-US/html_single/#d0e21609. This usually stems from "slowness" problems that arise when sending mail through an interactive application. The problem is that when your "user" submits that order for his fancy new widgets, the confirmation email sent is using the same thread that handled the processing of the web page. Thus the user is left with their browser in a blocked "loading" state thinking your application is slow when in reality it’s the mail server...
<div class="sect3">
<h4 id="_the_problem">The Problem</h4>
<div class="paragraph">
<p>One of the more common questions that I see by users coming to "Seam 3 Mail":http://www.seamframework.org/Seam3/MailModule is about sending email asynchronously like was possible in "Seam 2":http://docs.jboss.org/seam/2.2.2.Final/reference/en-US/html_single/#d0e21609. This usually stems from "slowness" problems that arise when sending mail through an interactive application. The problem is that when your "user" submits that order for his fancy new widgets, the confirmation email sent is using the same thread that handled the processing of the web page. Thus the user is left with their browser in a blocked "loading" state thinking your application is slow when in reality it’s the mail server that is taking its sweet time.</p>
</div>
</div>
<div class="sect3">
<h4 id="_the_knee_jerk_reaction">The Knee-jerk Reaction</h4>
<div class="paragraph">
<p>A lot of people will see this blocked thread and think the solution is to fire the email asynchronously. This way the email with be dispatched via separate thread and control will be instantly returned to the user . However the problem with asynchronous methods is that they are fire and forget. If an exception occurs during the send process, then the email is lost and there is no notification that it failed. Realistically, outside of a demo application you generally want some guarantee that the email was, or will be sent as having all those order confirmation emails silently lost will not be pretty.</p>
</div>
</div>
<div class="sect3">
<h4 id="_you_really_want">You Really Want</h4>
<div class="paragraph">
<p>What is needed is a system which allows you to send email from your application without blocking the execution on the current thread, while at the same time providing a guarantee that the email will be reliably sent (at least from your application to your "SMTP":http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol server).</p>
</div>
</div>
<div class="sect3">
<h4 id="_the_solution">The Solution</h4>
<div class="paragraph">
<p>Seam Mail provides a way to replace out the default "send" implementation with one of your own via the "MailTransporter":https://github.com/seam/mail/blob/develop/api/src/main/java/org/jboss/seam/mail/core/MailTransporter.java interface. That way when you call @msg.send()@ you can control how and when the email is "sent". What follows is a basic implementation.</p>
</div>
<div class="paragraph">
<p><em>In the code that follows I’m skipping the import statements for the sake of readability, but everything is standard
EE6 + Seam 3 with exception of the Files which comes from <a href="http://code.google.com/p/guava-libraries/">Google Guava</a>.</em></p>
</div>
<div class="paragraph">
<p>The default MailTransporterImpl is very simple and looks as follows.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">public class MailTransporterImpl implements MailTransporter {
private Session session;
public MailTransporterImpl(Session session) {
this.session = session;
}
public EmailMessage send(EmailMessage emailMessage) {
MailUtility.send(emailMessage, session);
return emailMessage;
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The MailUtility.send(emailMessage, session) sends the email using the configured javax.mail.Session. This is a
blocking implementation and will not release the thread until the destination mail server has acknowledged receipt of
the message. This might take a couple milliseconds or a few minutes depending on message size, server performance and
network bandwidth. If this doesn’t work for you then it’s easy to swap out.</p>
</div>
<div class="paragraph">
<p>First lets create a new MailTransporter called MailQueueTransporter</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">public class MailQueueTransporter implements Serializable, MailTransporter {
private static final long serialVersionUID = 1L;
@Inject
@QueuedEmail
private Event<MimeMessage> queueEvent;
@Inject
@ExtensionManaged
private Instance<Session> session;
@Override
public EmailMessage send(EmailMessage emailMessage) {
MimeMessage msg = MailUtility.createMimeMessage(emailMessage, session.get());
queueEvent.fire(msg);
return emailMessage;
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Starting from the top we see that we are injecting a new
<a href="http://docs.oracle.com/javaee/6/api/javax/enterprise/event/package-summary.html">Event</a> qualified with @QueuedMail
and typed to <a href="http://docs.oracle.com/javaee/6/api/javax/mail/internet/MimeMessage.html">MimeMessage</a>. @QueuedMail is a
simple qualifier, and if you have never written one before here is what it looks like.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@Qualifier
@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface QueuedEmail { }</code></pre>
</div>
</div>
<div class="paragraph">
<p>Next we inject the javax.mail.Session as managed by Seam Mail and implement the
public EmailMessage send(EmailMessage emailMessage) as mandated by the interface. Inside this method we use the Seam
MailUtility class to convert our EmailMessage as built by Seam Mail to a standard MimeMessage and then fire it as a
CDI event.</p>
</div>
<div class="paragraph">
<p>A CDI event however is still blocking in its execution so lets see what is observing this event.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">public class MailQueueReceiver {
@Inject
private Logger log;
public static final String mailQueueFolder = "/var/data/mailQueue/";
public void receiveMessage(@Observes @QueuedEmail MimeMessage msg) {
log.debugf("Writing queued message to disk");
OutputStream os;
try {
os = Files.newOutputStreamSupplier(
new File(mailQueueFolder + UUID.randomUUID())).getOutput();
msg.writeTo(os);
os.close();
} catch (IOException e) {
throw new SendFailedException("Failed to Write Message to Queue", e);
} catch (MessagingException e) {
throw new SendFailedException(e);
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>What we have done here is to receive the CDI event and immediately write the message to persistent storage, in this
case to a queue folder on the application server. Now our thread is returned as fast as we can write the message to
disk. You could also write these bytes out to the database or a in memory store if the loss of queued email during a
server shutdown/crash is not an issue.</p>
</div>
<div class="paragraph">
<p>All that is needed now is a process to send these stored messages. I’m using a EJB 3.1 scheduled timer, but the options
are endless.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@Singleton
public class MailQueueSender {
@Inject
private Logger log;
@Inject
@ExtensionManaged
private Session session;
private String mailQueueFolder;
@PostConstruct
public void postConstruct() {
mailQueueFolder = MailQueueReceiver.mailQueueFolder;
File queueFolder = new File(mailQueueFolder);
session.getProperties().put("mail.smtp.connectiontimeout", 15000);
session.getProperties().put("mail.smtp.timeout", 15000);
log.infof("Initialized Mail Queue with %s messages in queue", queueFolder.listFiles().length);
}
@Schedule(second = "15,45", minute = "*", hour = "*", persistent = false)
public void sendQueue() throws InterruptedException {
File queueFolder = new File(mailQueueFolder);
LinkedList<File> files = new LinkedList<File>(Arrays.asList(queueFolder.listFiles()));
while (!files.isEmpty()) {
File file = files.peek();
InputStream is;
try {
is = Files.newInputStreamSupplier(file).getInput();
RootMimeMessage msg = new RootMimeMessage(session, is);
msg.setMessageId(generateMessageId());
Transport.send(msg);
log.debug("Sent Mail Message: " + msg.getMessageID());
is.close();
files.pop();
file.delete();
}
catch (IOException e) {
throw new SendFailedException("Failed to read message from Disk: " + file.getName(), e);
}
catch (MessagingException e) {
throw new SendFailedException("Send Failed for Message: " + file.getName(), e);
}
}
}
private String generateMessageId() {
String mailerDomainName = session.getProperty("mail.seam.domainName");
if (mailerDomainName != null && mailerDomainName.length() > 0) {
return UUID.randomUUID().toString() + "@" + mailerDomainName;
}
else {
return UUID.randomUUID().toString() + "@" + MailUtility.getHostName();
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>One thing to note is that you have to reset the javax.mail.Session as that is lost when the MimeMessage is converted
to a OutputStream. There is a little added complexity going on here as I like to control the domain part of a
Message-ID, but this is a simple reliable way to handle sending mail in a fast and reliable fashion.</p>
</div>
</div>
https://www.outjected.com/blog/2012/01/18/fighting-with-jsf-request-charset-jboss-tomcat.htmlFighting with JSF Request charset: JBoss or Tomcat2016-09-27T15:20:58-06:002012-01-18T00:00:00+00:00Cody Lerum
After just spending a good amount of time troubleshooting an issue with character encoding in JSF + JBoss AS7 I thought
I would throw up a few notes on the subject as there are lots of scattered bits floating around but no real clear
explanation. Hopefully this does more than contribute to the scattered bits :-)
First lets start off with a little background on how servers and clients determine how to encode data for transfer
Server response to Client:
Server Encode: When a server is sending a response to a client with JSF it encodes the response based on the
defined encoding of the file...
<div class="paragraph">
<p>After just spending a good amount of time troubleshooting an issue with character encoding in JSF + JBoss AS7 I thought
I would throw up a few notes on the subject as there are lots of scattered bits floating around but no real clear
explanation. Hopefully this does more than contribute to the scattered bits :-)</p>
</div>
<div class="paragraph">
<p>First lets start off with a little background on how servers and clients determine how to encode data for transfer</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Server response to Client:</p>
<div class="ulist">
<ul>
<li>
<p><strong>Server Encode</strong>: When a server is sending a response to a client with JSF it encodes the response based on the
defined encoding of the file which is usually set at the top of a JSF XHTML file
<?xml version="1.0" encoding="UTF-8"?> The server will also include a Content-Type in the response header sent to the
client.</p>
</li>
<li>
<p><strong>Client Decode</strong>: When the client receives a response it checks the Content-Type defined in the response headers to
decide which charset to use for decode. <em>However If the Content-Type is not listed in the response header then the
client may check the page meta tags for a hint or default to ISO-8955-1</em></p>
</li>
</ul>
</div>
</li>
<li>
<p>Client Request (POST) to Server:</p>
<div class="ulist">
<ul>
<li>
<p><strong>Client Encode</strong>: The client will encode it’s request based on the encoding of the response it received from the server.</p>
</li>
<li>
<p><strong>Server Decode</strong>: This is where things get a little tricky.</p>
<div class="ulist">
<ul>
<li>
<p>The request received from the client will likely lack any hint as to how things were encoded.</p>
<div class="ulist">
<ul>
<li>
<p>It may have a Accept-Charset defined, but that is simply informing the server which charset’s are valid for it’s
response encoding.</p>
</li>
<li>
<p>It will also have a Content-Type which reflects the enctype set on the form element submitting this post. By
default it is application/x-www-form-urlencoded. Notice no reference to the charset this request was encoded in.</p>
</li>
<li>
<p>Some requests like ajax requests will look like this application/x-www-form-urlencoded;charset=utf-8; This does
work and Tomcat/JbossWeb will decode as utf-8 but I have not figured out how to force this on a non-ajax h:form</p>
</li>
</ul>
</div>
</li>
<li>
<p>The catch here is that if there is not a charset defined in the request Content-Type then the request
parameters will be decoded using ISO-8859-1.</p>
</li>
</ul>
</div>
</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="paragraph">
<p>So you’ve configured for pages for UTF-8 and ensured that your server responses are including a charset in the
Content-Type. Everything is great until you submit the form and your UTF-8 encoded client request is decoded as
ISO-8859-1. Depending on the data your users submit you may not even notice this in your app for weeks/months/years/never.
But for example if user may submit something like I’m and you will get I’m</p>
</div>
<div class="paragraph">
<p>Once you accept that this is how things work, there is an easy way to fix this by adding the following snippet to your web.xml</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml"><web-app>
...
<filter>
<filter-name>forceUTF8CharSet</filter-name>
<filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>forceUTF8CharSet</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
...
</web-app></code></pre>
</div>
</div>
<div class="paragraph">
<p>This filter currently is in Tomcat 7.0.20 and up. If you are running JBoss 7 you can just grab the class from
<a href="https://github.com/apache/tomcat70/blob/b6e55ec63249677f88a0a1d9daa93278741726d6/java/org/apache/catalina/filters/SetCharacterEncodingFilter.java">Github</a>
import it into your project. I’ve opened <a href="https://issues.jboss.org/browse/JBWEB-225">JBWEB-225</a> with JBoss Web to have this
filter added.</p>
</div>
https://www.outjected.com/blog/2011/12/16/cdi-instance-injections-and-session-application-scoped-beans.htmlCDI Instance Injections and Session/Application Scoped Beans2016-09-27T15:20:58-06:002011-12-16T00:00:00+00:00Cody Lerum
If you’ve spent much time with CDI you invariably had a use case where you would prefer not to trigger an injection
when the bean is initialized. This can be handy for example if it is an expensive action and the injected bean is only
going be be invoked a small percentage of the time.
There is however caveat that is relevant. The beans produced by the Instance will live until the containing bean is destroyed.
This doesn’t cause an issue with Dependent, Request, View, or Conversation scoped beans, but it would cause a unexpected
memory leak with Application or even Session scoped beans....
<div class="paragraph">
<p>If you’ve spent much time with CDI you invariably had a use case where you would prefer not to trigger an injection
when the bean is initialized. This can be handy for example if it is an expensive action and the injected bean is only
going be be invoked a small percentage of the time.</p>
</div>
<div class="paragraph">
<p>There is however caveat that is relevant. The beans produced by the Instance will live until the containing bean is destroyed.</p>
</div>
<div class="paragraph">
<p>This doesn’t cause an issue with Dependent, Request, View, or Conversation scoped beans, but it would cause a unexpected
memory leak with Application or even Session scoped beans. Since the Instance could be invoked multiple times spanning
hours or days with a @SessionScoped bean and potentially weeks or months with an @ApplicationScoped bean (if your
lucky to run your app uninterrupted that long) the memory leak could bring your app to a halt.</p>
</div>
<div class="paragraph">
<p>Improvement are being made to the CDI 1.1 spec to handled this better <a href="https://issues.jboss.org/browse/CDI-139">CDI-139</a></p>
</div>
<div class="paragraph">
<p>But in the meantime the following will work nicely</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@Inject
BeanManager bm;
public void run() {
CreationalContext<Foo> ctx = bm.createCreationalContext(null);
Bean<?> beans = BeanManagerTools.beans(bm, Foo.class);
Foo f = bm.getReference(beans, Foo.class, ctx);
//Do Work
ctx.release();
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Calling the release at the end destroys all the beans created in the Context we initialized (ctx)</p>
</div>
https://www.outjected.com/blog/2011/02/28/fighting-with-empty-github-directories-and-egit.htmlFighting with empty github directories...and EGit2016-09-27T15:20:58-06:002011-02-28T00:00:00+00:00Cody Lerum
Occasionally I run into an issue where if I do a refactoring on my git project in eclipse that requires renaming a
folder those folders will still show up on the github website (completely empty) even though they are not in the local
workspace.
It appears that happens only when I commit the changes through eclipse via EGit via JGit. It appears to be
https://bugs.eclipse.org/bugs/show_bug.cgi?id=314105
Anyway the easiest way to fix this is to do a commit outside of eclipse via the command line git. Once pushed to the
remote the empty folders disappear....
<div class="paragraph">
<p>Occasionally I run into an issue where if I do a refactoring on my git project in eclipse that requires renaming a
folder those folders will still show up on the github website (completely empty) even though they are not in the local
workspace.</p>
</div>
<div class="paragraph">
<p>It appears that happens only when I commit the changes through eclipse via EGit via JGit. It appears to be
<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=314105" class="bare">https://bugs.eclipse.org/bugs/show_bug.cgi?id=314105</a></p>
</div>
<div class="paragraph">
<p>Anyway the easiest way to fix this is to do a commit outside of eclipse via the command line git. Once pushed to the
remote the empty folders disappear.</p>
</div>
https://www.outjected.com/blog/2010/05/21/sorting-java-enums.htmlSorting Java Enums2016-09-27T15:20:58-06:002010-05-21T00:00:00+00:00Cody Lerum
Occasionally when working with JSF I have the need to display the values of a Java Enum in a pick-list.
public enum Cars {
KIA,
BMW,
TOYOTA,
FERRARI
}
Returning an array of these values is easy enough. Cars.values();
The ordering of the values in the array is set by the ordinal value of the enum, or more simply the order which it
appears in the source code. {"KIA", "BMW", "TOYOTA", FERRARI"}
Now depending on your application, if you need to change the order you can simply change the order they appear in
the source code. However if you are like me and...
<div class="paragraph">
<p>Occasionally when working with JSF I have the need to display the values of a Java Enum in a pick-list.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">public enum Cars {
KIA,
BMW,
TOYOTA,
FERRARI
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Returning an array of these values is easy enough. Cars.values();</p>
</div>
<div class="paragraph">
<p>The ordering of the values in the array is set by the ordinal value of the enum, or more simply the order which it
appears in the source code. {"KIA", "BMW", "TOYOTA", FERRARI"}</p>
</div>
<div class="paragraph">
<p>Now depending on your application, if you need to change the order you can simply change the order they appear in
the source code. However if you are like me and persisting these values to a database based on their ordinal value to
save space then changing the order will break your application.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@NotNull
@Column(columnDefinition = "tinyint")
@Enumerated(EnumType.ORDINAL)
public Cars getCar() {
return car;
}
public void setEgressCodec(Cars car) {
this.car = car;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The first thing you might want to do is implement Comparable on the Enum and override the compareTo with your own
to control the ordering. Unfortunately
<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Enum.html">compareTo() is final</a> on the Enum so we can’t
override it.</p>
</div>
<div class="paragraph">
<p><strong>Here is the solution that I’ve come up with.</strong></p>
</div>
<div class="paragraph">
<p>First I create a new interface called ComparableEnum</p>
</div>
<div class="paragraph">
<p><strong>ComparableEnum.java</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">public interface ComparableEnum {
public String getDisplayName();
public int getPriority();
public boolean isDisplayed();
public int ordinal();
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then I can implement this on my Cars Enum using the cost a car as a value for the priority</p>
</div>
<div class="paragraph">
<p><strong>Cars.java</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">public enum Cars implements ComparableEnum {
KIA("Kia Motors", 15000, true),
BMW("Bavarian Motor Works", 55000, true),
TOYOTA("Toyota Motors", 35000, true),
FERRARI("Ferrari S.p.A.", 150000, true)
private String displayName;
private int priority;
private boolean displayed;
private Cars(String displayName, int priority, boolean displayed) {
this.displayName = displayName;
this.priority = priority;
this.displayed = displayed;
}
public String getDisplayName() {
return displayName;
}
public int getPriority() {
return priority;
}
public boolean isDisplayed() {
return displayed;
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now it’s just a matter adding a couple comparators</p>
</div>
<div class="paragraph">
<p><strong>EnumNameComparator.java</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">public class EnumNameComparator<T extends ComparableEnum> implements Comparator<T> {
public int compare(T o1, T o2)
{
if (o1.getDisplayName().compareTo(o2.getDisplayName()) != 0){
return o1.getDisplayName().compareTo(o2.getDisplayName());
}
else if (o1.toString().compareTo(o2.toString()) != 0) {
return o1.toString().compareTo(o2.toString());
}
else {
return new Integer(o1.ordinal()).compareTo(new Integer(o2.ordinal()));
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>EnumPriorityComparator.java</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">public class EnumPriorityComparator<T extends ComparableEnum> implements Comparator<T> {
public int compare(T o1, T o2)
{
if (new Integer(o1.getPriority()).compareTo(new Integer(o2.getPriority())) != 0)
{
return new Integer(o1.getPriority()).compareTo(new Integer(o2.getPriority()));
}
else if (o1.toString().compareTo(o2.toString()) != 0)
{
return o1.toString().compareTo(o2.toString());
}
else
{
return new Integer(o1.ordinal()).compareTo(new Integer(o2.ordinal()));
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now I want to be able to sort these easily using any enum I have which implements Comparable enum so I add a generic method.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">private static <T extends ComparableEnum> List<T> getEnumSortedByPriority(T[] t) {
EnumPriorityComparator<T> c = new EnumPriorityComparator<T>();
List<T> list = removeNonDispalyedValues(t);
Collections.sort(list, c);
return list;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now I can create a simple method to return my enum sorted how I wish</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">public static List<Cars> componentTypes() {
return getEnumSortedByPriority(ComponentType.values());
}</code></pre>
</div>
</div>
https://www.outjected.com/blog/2010/01/12/composite-primary-key-with-manytoone.htmlComposite Primary Key with @ManyToOne2016-09-27T15:20:58-06:002010-01-12T00:00:00+00:00Cody Lerum
Here is a fun issue that I ran into the other day while working with a legacy database.
Three tables:
Nodes
NodeID(pk)
Interfaces
InterfaceID(pk)
NodeID(fk)
InterfaceTraffic_Detail
InterfaceID(pk)
DateTime(pk)
NodeID(fk)
The InterfaceTraffic_Detail table turned out to be a little tricky for me since I have never worked with composite
indexes in hibernate. It took a little trial and error but here is what I came up with
My environment is Hibernate 3.4
NmsNode.java
@Name("nmsNode")
@Entity
@Table(name="Nodes")
public class NmsNode implements Serializable {
private static final long serialVersionUID = 1462044144509159489L;
private int id;
private List<NmsInterface> interfaces;
@Id
@Column(name="NodeID")
public int getId() {
return id;
}
public void setId(int...
<div class="paragraph">
<p>Here is a fun issue that I ran into the other day while working with a legacy database.</p>
</div>
<div class="paragraph">
<p>Three tables:</p>
</div>
<div class="paragraph">
<p><strong>Nodes</strong></p>
</div>
<div class="ulist">
<ul>
<li>
<p>NodeID(pk)</p>
</li>
</ul>
</div>
<div class="paragraph">
<p><strong>Interfaces</strong></p>
</div>
<div class="ulist">
<ul>
<li>
<p>InterfaceID(pk)</p>
</li>
<li>
<p>NodeID(fk)</p>
</li>
</ul>
</div>
<div class="paragraph">
<p><strong>InterfaceTraffic_Detail</strong></p>
</div>
<div class="ulist">
<ul>
<li>
<p>InterfaceID(pk)</p>
</li>
<li>
<p>DateTime(pk)</p>
</li>
<li>
<p>NodeID(fk)</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The InterfaceTraffic_Detail table turned out to be a little tricky for me since I have never worked with composite
indexes in hibernate. It took a little trial and error but here is what I came up with</p>
</div>
<div class="paragraph">
<p>My environment is Hibernate 3.4</p>
</div>
<div class="paragraph">
<p><strong>NmsNode.java</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@Name("nmsNode")
@Entity
@Table(name="Nodes")
public class NmsNode implements Serializable {
private static final long serialVersionUID = 1462044144509159489L;
private int id;
private List&lt;NmsInterface&gt; interfaces;
@Id
@Column(name="NodeID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@OneToMany(mappedBy="node", fetch=FetchType.LAZY)
public List&lt;NmsInterface&gt; getInterfaces() {
return interfaces;
}
public void setInterfaces(List&lt;NmsInterface&gt; interfaces) {
this.interfaces = interfaces;
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>NmsInterface.java</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@Name("nmsInterface")
@Entity
@Table(name="Interfaces")
public class NmsInterface implements Serializable
{
private static final long serialVersionUID = 1L;
private int id;
private NmsNode node;
@Id
@Column(name="InterfaceID")
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
@ManyToOne
@JoinColumn(name="NodeID")
public NmsNode getNode()
{
return node;
}
public void setNode(NmsNode node)
{
this.node = node;
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>InterfaceTraffic_Detail.java</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@Entity
@Table(name="InterfaceTraffic_Detail")
@AssociationOverrides
(
{
@AssociationOverride(name = "id.nmsInterface",
joinColumns = @JoinColumn(name = "InterfaceID"))
}
)
public class InterfaceTraffic_Detail implements Serializable
{
private static final long serialVersionUID = 1L;
private InterfaceTraffic_PrimaryKey id;
private NmsNode nmsNode;
@EmbeddedId
@AttributeOverrides
(
{
@AttributeOverride(name="id.dateTime", column=@Column(name="DateTime"))
}
)
public InterfaceTraffic_PrimaryKey getId()
{
return id;
}
public void setId(InterfaceTraffic_PrimaryKey id)
{
this.id = id;
}
@ManyToOne
@JoinColumn(name="NodeID")
public NmsNode getNmsNode()
{
return nmsNode;
}
public void setNmsNode(NmsNode nmsNode)
{
this.nmsNode = nmsNode;
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>InterfaceTraffic_PrimaryKey.java</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@Embeddable
public class InterfaceTraffic_PrimaryKey implements Serializable
{
private static final long serialVersionUID = 1L;
private NmsInterface nmsInterface;
private Date dateTime;
@ManyToOne
public NmsInterface getNmsInterface()
{
return nmsInterface;
}
public void setNmsInterface(NmsInterface nmsInterface)
{
this.nmsInterface = nmsInterface;
}
public Date getDateTime()
{
return dateTime;
}
public void setDateTime(Date dateTime)
{
this.dateTime = dateTime;
}
public int hashCode() {
return (int) dateTime.hashCode() + nmsInterface.getId();
}
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null) return false;
if (!(obj instanceof InterfaceTraffic_PrimaryKey)) return false;
InterfaceTraffic_PrimaryKey pk = (InterfaceTraffic_PrimaryKey) obj;
return pk.nmsInterface.getId() == nmsInterface.getId() &amp;&amp; pk.dateTime.equals(dateTime);
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The important part here is the @EmbeddedId and @Embeddable on the InterfaceTraffic_Detail and
InterfaceTraffic_PrimaryKey as well as the name "id.nmsInterface" on the @AssociationOverride so that I could
reference the variable on the embedded class and define the @JoinColumn</p>
</div>
<div class="paragraph">
<p>Hopefully this saves someone else some time.</p>
</div>
https://www.outjected.com/blog/2010/01/04/jsf-lacking-support-for-collections.htmlJSF 2.0 still lacking support for collections2016-09-27T15:20:58-06:002010-01-04T00:00:00+00:00Cody Lerum
Unfortunately the freshly minted JSF 2.0 spec still doesn’t support a
generic Collection interface. Currently only
a List is supported and while this does work for many
situations, it does cause many issues when you are working with a full JavaEE stack
since it may be necessary to use Set or
SortedSet when working with
JPA.
It hasn’t been used in the past, but it’s time for the users to start voting on java.net. So go there, register and
throw some of your votes towards this painful issue.
Issue 479 - UIData should support the collection interface rather than the List interface...
<div class="paragraph">
<p>Unfortunately the freshly minted <a href="http://java.sun.com/javaee/javaserverfaces/">JSF 2.0</a> spec still doesn’t support a
generic <a href="http://java.sun.com/javase/6/docs/technotes/guides/collections/index.html">Collection</a> interface. Currently only
a <a href="http://java.sun.com/javase/6/docs/api/java/util/List.html">List</a> is supported and while this does work for many
situations, it does cause many issues when you are working with a full <a href="http://java.sun.com/javaee/">JavaEE</a> stack
since it may be necessary to use <a href="http://java.sun.com/javase/6/docs/api/java/util/Set.html">Set</a> or
<a href="http://java.sun.com/javase/6/docs/api/java/util/SortedSet.html">SortedSet</a> when working with
<a href="http://java.sun.com/javaee/technologies/persistence.jsp">JPA</a>.</p>
</div>
<div class="paragraph">
<p>It hasn’t been used in the past, but it’s time for the users to start voting on java.net. So go there, register and
throw some of your votes towards this painful issue.</p>
</div>
<div class="paragraph">
<p><a href="http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-479">Issue 479 - UIData should support the collection interface rather than the List interface</a></p>
</div>
https://www.outjected.com/blog/2009/12/29/hibernate-optimistic-locking-and-mySQL.htmlHibernate Optimistic Locking and MySQL2016-09-27T15:20:58-06:002009-12-29T00:00:00+00:00Cody Lerum
So I ran into a fun little issue the other day while working with MySQL and Hibernate.
Hibernate provides optimistic locking via the Version
function. This can either be a numeric field or a timestamp. I use Hibernate Annotations, so for me it simply involves
placing the following annotation inside my entity.
private Date dateModified;
@Version
private Date getDateModified() {
return dateModified;
}
private void setDateModified(Date dateModified) {
this.dateModified = dateModified;
}
This worked great for me, and provided both an optimistic lock as well as a dateModified field I could use to show
the last time the entity was updated. I should say that this worked great during...
<div class="paragraph">
<p>So I ran into a fun little issue the other day while working with MySQL and Hibernate.</p>
</div>
<div class="paragraph">
<p>Hibernate provides optimistic locking via the <a href="http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-mapping-entity-version">Version</a>
function. This can either be a numeric field or a timestamp. I use Hibernate Annotations, so for me it simply involves
placing the following annotation inside my entity.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">private Date dateModified;
@Version
private Date getDateModified() {
return dateModified;
}
private void setDateModified(Date dateModified) {
this.dateModified = dateModified;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This worked great for me, and provided both an optimistic lock as well as a dateModified field I could use to show
the last time the entity was updated. I should say that this worked great during development while I was using
hypersonic as my database. When I deployed to a lab server for testing against our MySQL database I started to run
into some <a href="http://java.sun.com/javaee/5/docs/api/javax/persistence/OptimisticLockException.html">OptimisticLockExceptions</a></p>
</div>
<div class="paragraph">
<p>After doing some digging around I found out that <a href="http://bugs.mysql.com/bug.php?id=8523">MySQL doesn’t store date/time with millisecond precision</a>.
This is a well known feature request / bug and it doesn’t appear that it will be fixed anytime soon. So I was forced to
<a href="http://en.wikipedia.org/wiki/Code_refactoring">refactor my code</a> so that the "version" was a int and still maintain a
dateModified field since the user interface had made use of it in various places.</p>
</div>
<div class="paragraph">
<p>Thankfully Hibernate provides <a href="http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html_single/#listeners">Call Back</a>
annotations which allow me to trigger an update of the dateModified when a Persist or Update is called. I also used
this logic to automatically set the dateCreated field on entities when needed.</p>
</div>
<div class="paragraph">
<p>I also added an @Deprecated to the setters for dateCreated and dateModified to discourage others from setting those
fields manually.</p>
</div>
<div class="paragraph">
<p>Here is what the final code looks like.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">private int version;
private Date dateCreated;
private Date dateModified;
@NotNull
public Date getDateCreated() {
return dateCreated;
}
@Deprecated
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
@PrePersist
public void updateDateCreated() {
dateCreated = new Date();
dateModified = dateCreated;
}
@NotNull
public Date getDateModified() {
return dateModified;
}
@Deprecated
public void setDateModified(Date dateModified) {
this.dateModified = dateModified;
}
@PreUpdate
public void updateDateModified() {
dateModified = new Date();
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>Update!</strong></p>
</div>
<div class="paragraph">
<p>It looks like mysql has this on their roadmap and outlines their plans with a fairly extensive
<a href="http://forge.mysql.com/worklog/task.php?id=946">worklog</a>. However this is slated for MySQL 6.0 or 7.0 and thus will be
a few years out. Maybe it’s time to checkout what PostgreSQL is all about.</p>
</div>