<?xml version="1.0" encoding='utf-8'?>
<?xml-stylesheet type="text/xsl" href="https://nozaki.me/roller/roller-ui/styles/atom.xsl" media="screen"?><feed xmlns="http://www.w3.org/2005/Atom">
    <title type="html">Kohei Nozaki&apos;s blog</title>
    <subtitle type="html">Notes of my experiments</subtitle>
    <id>https://nozaki.me/roller/kyle/feed/entries/atom</id>
            <link rel="self" type="application/atom+xml" href="https://nozaki.me/roller/kyle/feed/entries/atom" />
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/" />
        <updated>2024-05-01T08:28:13+00:00</updated>
    <generator uri="http://roller.apache.org" version="5.2.0">Apache Roller</generator>
        <entry>
        <id>https://nozaki.me/roller/kyle/entry/the-state-pattern</id>
        <title type="html">The State Pattern</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/the-state-pattern"/>
        <published>2022-08-11T04:21:15+00:00</published>
        <updated>2022-08-11T04:21:15+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="design-patterns" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_what_is_the_state_pattern&quot;&gt;What is the State Pattern?&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;It&amp;#8217;s one of the GoF Design Patterns which helps to organize code that handles multiple states. If you have a code base where there are many boolean fields or an enum field used to determine the state, similar if/switch branches and unclear state transitions, a giant class where there is all of the stuff in messy code causing a maintainability issue, applying the State Pattern might be worth considering.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The State Pattern consists of the following participants:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/fa37dd6b-3a52-4a9a-afa4-ccc5079d9f10&quot; alt=&quot;fa37dd6b 3a52 4a9a afa4 ccc5079d9f10&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The Context class provides the clients of your code with the public API. All of the other participants are implementation details which the clients of your class don&amp;#8217;t have to know about.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The Context class holds a reference to an object which implements the State interface. The Context class forwards some of the API calls to the state object. The State interface defines part of the API whose behavior has to be changed depending on the state.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The ConcreteState classes implement the State interface. Each implementation exists for each possible state of your application. It handles the API calls forwarded from the Context class appropriately according to the requirement of the state it corresponds to. A ConcreteState class can trigger a state transition.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_case_study_the_smtp_protocol&quot;&gt;Case study: the SMTP protocol&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;As an example application for the State Pattern, let&amp;#8217;s think about an SMTP server. SMTP is a protocol used for email transport. Usually email client software like Mozilla Thunderbird supports this protocol. When such software sends an email, it connects to an SMTP server and talks to the server using this protocol to send an email.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This is a typical flow of an SMTP communication session (taken from Wikipedia):&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;S: 220 smtp.example.com ESMTP Postfix
C: HELO relay.example.com
S: 250 smtp.example.com, I am glad to meet you
C: MAIL FROM:&amp;lt;bob@example.com&amp;gt;
S: 250 Ok
C: RCPT TO:&amp;lt;alice@example.com&amp;gt;
S: 250 Ok
C: RCPT TO:&amp;lt;theboss@example.com&amp;gt;
S: 250 Ok
C: DATA
S: 354 End data with &amp;lt;CR&amp;gt;&amp;lt;LF&amp;gt;.&amp;lt;CR&amp;gt;&amp;lt;LF&amp;gt;
C: From: &quot;Bob Example&quot; &amp;lt;bob@example.com&amp;gt;
C: To: Alice Example &amp;lt;alice@example.com&amp;gt;
C: Cc: theboss@example.com
C: Date: Tue, 15 Jan 2008 16:02:43 -0500
C: Subject: Test message
C:
C: Hello Alice.
C: This is a test message with 5 header fields and 4 lines in the message body.
C: Your friend,
C: Bob
C: .
S: 250 Ok: queued as 12345
C: QUIT
S: 221 Bye
{The server closes the connection}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The lines beginning with &quot;S:&quot; are sent by the server and the ones beginning with &quot;C: &quot; are sent by the client.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Typically, after establishing a TCP connection, the server sends a short message which indicates it is ready to accept a command from the client. The client first sends an HELO message with its hostname, then begins an email transaction with specifying the email address of the sender of the email with a MAIL FROM command. After that, the client sends the email addresses of the recipients of the email with RCPT TO commands. Then finally, the client sends a DATA command, sends the content of the email and finishes it with a line which contains only a period. If everything goes fine, the server responds with an OK message which means the email is accepted by the server and the email will be delivered to the recipients specified.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;What we can see from here is that in this protocol a client has to send necessary information to the server in a specific order. The server reacts differently for each state of the communication process. For example, the client must provide a sender identification first. Otherwise, any other command from the client doesn&amp;#8217;t get processed and the server returns an error. It means that the server remembers the current communication state at any given moment.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;So, what are those states? A good way to find that out is drawing a state diagram. It will look like the following:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/0334ad5d-100e-4b11-98a3-8705c9cb832b&quot; alt=&quot;0334ad5d 100e 4b11 98a3 8705c9cb832b&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;There are 4 states in the communication process. The first one is the idle state where the client has to start a session with an HELO command. Then it proceeds to the initial state, where the client has to provide the email address of the sender of the email with a MAIL FROM command. Then we proceed to the transaction started state where the client provides the recipients of the email with an RCPT TO command. The client might stay in this state until it finishes sending all of the recipients and that is why there is this transition which goes back to the same state. After that, finally it proceeds to the data transfer state with a DATA command where the client sends the body of the email and finishes the transaction with a line which contains only a period. Then it gets back to the initial state and if the client wants to send another email, it can start over from there.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_implementing_an_smtp_server_with_the_state_pattern&quot;&gt;Implementing an SMTP server with the State Pattern&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In order to implement such a communication process which consists of multiple stages or states, applying the State Pattern can be a good way to keep the implementation clean and organized. Otherwise, we might end up having a giant class where there are a lot of mutable states and if/switch conditionals which are highly likely to be a maintenance problem.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Let&amp;#8217;s look at one possible design based on the State Pattern which can handle the SMTP protocol:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/53b553bd-9d02-4c68-965b-2adad582e346&quot; alt=&quot;53b553bd 9d02 4c68 965b 2adad582e346&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The SMTPSessionHandler class corresponds to the Context class in the previous class diagram. An instance of this class exists for each SMTP conversation session. There is a public method called handleCommand() which receives a command from the client and returns the response for the command. This method has to handle the commands from the client appropriately depending on the current state. In order to achieve that, we have those 4 concrete state classes that correspond to the states in the state diagram given earlier, and what this method does is basically just forwarding the method calls to the currentState object.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In this design, state transitions are done by each concrete state class. For that purpose, the SMTPSessionHandler class has the setCurrentState() method. And when the SMTPSessionHandler class forwards the method calls to the currentState object, it also passes its own reference as an additional parameter. It allows each concrete state class to call the setCurrentState() method.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Let&amp;#8217;s look at the source code of each participant. The SMTPSessionHandler class just holds the currentState object and forwards any handleCommand() calls to the currentState object with a reference to this object. It also has the setCurrentState() method for the concrete state classes.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class SMTPSessionHandler {
    private State currentState = new IdleState();

    public String handleCommand(String command) {
        return currentState.handleCommand(command, this);
    }

    void setCurrentState(State newState) {
        this.currentState = newState;
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The SMTPSessionHandler class calls the underlying current state object through this State interface, which has 4 concrete implementations.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;interface State {
    String handleCommand(String command, SMTPSessionHandler context);
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The IdleState class corresponds to the very first state when a connection is established with the client. The only command it accepts is the HELO command. When it receives the HELO command, it makes a state transition by calling the setCurrentState() method of the context object with a new instance of the InitialState class and returns a greeting to the client. Otherwise, it returns an error.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class IdleState implements State {
    @Override
    public String handleCommand(String command, SMTPSessionHandler context) {
        if (command.startsWith(&quot;HELO&quot;)) {
            context.setCurrentState(new InitialState());
            return &quot;250 smtp.example.com, I am glad to meet you&quot;;
        } else {
            return &quot;500 5.5.1 Invalid command&quot;;
        }
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;When the state transition in the IdleState class happens, the InitialState class takes over. The only command it accepts is the MAIL FROM command. When it happens, it extracts the email address which the client has sent and makes another state transition with a new instance of the TransactionStartedState class. When it creates the instance, it passes the email address it has extracted in order to let the subsequent process use it. Otherwise it returns an error.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class InitialState implements State {

    private static final Pattern PATTERN_FOR_EXTRACTING_EMAIL =
            Pattern.compile(&quot;MAIL FROM:&amp;lt;([^&amp;gt;]+)&amp;gt;&quot;);

    @Override
    public String handleCommand(String command, SMTPSessionHandler context) {
        Matcher matcher = PATTERN_FOR_EXTRACTING_EMAIL.matcher(command);
        if (matcher.find()) {
            String from = matcher.group(1);
            context.setCurrentState(new TransactionStartedState(from));
            return &quot;250 Ok&quot;;
        } else {
            return &quot;500 5.5.1 Invalid command&quot;;
        }
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The TransactionStartedState class is where we receive the destinations of the email. After specifying at least one destination, we can proceed to the next state but if there is none, it returns an error. The client has to send the destinations with the RCPT TO command. When it receives the RCPT TO command, it extracts the email address and keeps it in the List object. After sending at least one destination, the client can proceed to the next state with the DATA command. At this point, we have the address of the sender and the destinations and those are passed as the parameters of the constructor of the DataTransferState class.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class TransactionStartedState implements State {
    private static final Pattern PATTERN_FOR_EXTRACTING_EMAIL =
            Pattern.compile(&quot;RCPT TO:&amp;lt;([^&amp;gt;]+)&amp;gt;&quot;);
    private final String from;
    private final List&amp;lt;String&amp;gt; destinations = new ArrayList&amp;lt;&amp;gt;();

    TransactionStartedState(String from) {
        this.from = from;
    }

    @Override
    public String handleCommand(String command, SMTPSessionHandler context) {
        if (command.equals(&quot;DATA&quot;)) {
            if (destinations.isEmpty()) {
                return &quot;500 5.5.1 Invalid command&quot;;
            } else {
                context.setCurrentState(new DataTransferState(from, destinations));
                return &quot;354 End data with &amp;lt;CR&amp;gt;&amp;lt;LF&amp;gt;.&amp;lt;CR&amp;gt;&amp;lt;LF&amp;gt;&quot;;
            }
        }

        Matcher matcher = PATTERN_FOR_EXTRACTING_EMAIL.matcher(command);
        if (matcher.find()) {
            String to = matcher.group(1);
            destinations.add(to);
            return &quot;250 Ok&quot;;
        } else {
            return &quot;500 5.5.1 Invalid command&quot;;
        }
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The DataTransferState class corresponds to the final state of this communication process. What it does is just accumulating the body of the email in a StringBuilder object until it receives one single period which means the end of the body. After that, it will trigger the email delivery process which involves a DNS lookup, relaying the message to another SMTP server using the pieces of the data we received from the client during the process and making a state transition to the initial state. If the client wants to send another email, the client can start all over from there.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class DataTransferState implements State {
    private final String from;
    private final List&amp;lt;String&amp;gt; destinations;
    private final StringBuilder body = new StringBuilder();

    static DeliverySystem deliverySystem = (from, destinations, body) -&amp;gt; {
        // looks up MX records, connects to external SMTP servers and relays the message
    };

    DataTransferState(String from, List&amp;lt;String&amp;gt; destinations) {
        this.from = from;
        this.destinations = destinations;
    }

    @Override
    public String handleCommand(String command, SMTPSessionHandler context) {
        if (command.equals(&quot;.&quot;)) {
            deliverySystem.deliver(from, destinations, body.toString());
            context.setCurrentState(new InitialState());
            return &quot;250 Ok: the email has been delivered&quot;;
        } else {
            body.append(command);
            body.append(&apos;\n&apos;);
            return null;
        }
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_conclusion_benefits_of_the_state_pattern&quot;&gt;Conclusion: benefits of the State Pattern&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;That&amp;#8217;s all of the implementation. The responsibility of each concrete state class is clear and it helps to make each class concise and short. The state transitions are also clear because when they happen, they are done in a clear way, which is the setCurrentState() method in our example. There are no cryptic boolean flags that maintain states in an unclear way. It makes the code readable, easy to maintain and extend.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;For example, when you need to add a new state, what you need to do is write a new class which corresponds to the new state and add state transitions to the relevant existing state classes that are likely to be much simpler than a giant single class maintaining all of the states. It will reduce the risk of degradation.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In my experience, there are not so many use cases where this pattern is a great match, but it greatly improves the maintainability if it matches the use case and is applied appropriately.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/synchronize-access-to-shared-mutable</id>
        <title type="html">Synchronize access to shared mutable data</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/synchronize-access-to-shared-mutable"/>
        <published>2020-12-17T09:00:34+00:00</published>
        <updated>2020-12-17T09:02:23+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="java" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In Java, an update on mutable data made by one thread may not be visible by other threads unless an appropriate synchronization is applied. Such unsynchronized mutable data can be the cause of a nasty bug which is difficult to spot, reproduce and fix.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_why_do_we_need_a_synchronization&quot;&gt;Why do we need a synchronization?&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Let&amp;#8217;s say we have a class called Counter which holds mutable data:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class Counter {
    int count = 0;
    int getCount() { return count; }
    int increment() { return ++count; }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;There is an int field named count. There are also a simple getter and a method which increments the counter. The increment method can change the value in the count field which means that this class holds mutable data.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Now let&amp;#8217;s see what happens when an instance of the Counter class is shared across 2 threads without any synchronization. We have this client code of the Counter class:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class ThisNeverFinishesOnMyLaptop {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread backgroundThread = new Thread(() -&amp;gt; {
            while (true) { // wait until the counter gets incremented
                if (counter.getCount() != 0) break;
            }
            System.out.println(&quot;Finished&quot;);
        });
        backgroundThread.start();
        TimeUnit.SECONDS.sleep(1);
        counter.increment();
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;First we create an instance of the Counter class then we launch a background thread which starts a while loop and waits until the counter gets incremented. Then the main thread sleeps for 1 second and calls the increment method. This increment() call is supposed to make the background thread get out of the while loop. So what this code is supposed to do is to finish after 1 second with having the &quot;Finished&quot; message printed into the console.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;But in some environment, this code never even finishes which means the while loop becomes an infinite loop. The problem here is that due to lack of synchronization, the background thread fails to see the new value which the main thread set. In Java, without synchronization, it&amp;#8217;s not guaranteed that updates that have been made by one thread will be visible by other threads. Another thread might see the update at some point or might not see at all like in this example on my laptop. The behavior might vary depending on the environment where this code runs in and it is totally unpredictable.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_how_do_we_do_a_synchronization&quot;&gt;How do we do a synchronization?&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Then how can we make it work properly? One way to do that is the following:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class NowItFinishesOnMyLaptop {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Object lock = new Object();
        Thread backgroundThread = new Thread(() -&amp;gt; {
            while (true) { // wait until the counter gets incremented
                synchronized (lock) {
                    if (counter.getCount() != 0) break;
                }
            }
            System.out.println(&quot;Finished&quot;);
        });
        backgroundThread.start();
        TimeUnit.SECONDS.sleep(1);
        synchronized (lock) {
            counter.increment();
        }
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Now we create an object named lock and when we read or write data in the counter object, we do it in a synchronized block with the lock object. This guarantees that any update which is done in a synchronized block will be seen by any other code inside a synchronized block that uses the same lock object.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;There is also another way to fix this. We can add the volatile keyword to the count field:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class VolatileCounter {
    volatile int count = 0;
    int getCount() { return count; }
    int increment() { return ++count; }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;And we can replace the use of the Counter class in the ThisNeverFinishesOnMyLaptop class by the VolatileCounter class. The volatile keyword guarantees that updates made by one thread will be visible to other threads.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class ThisAlsoFinishesOnMyLaptop {
    public static void main(String[] args) throws InterruptedException {
        VolatileCounter counter = new VolatileCounter();
        Thread backgroundThread = new Thread(() -&amp;gt; {
            while (true) { // wait until the counter gets incremented
                if (counter.getCount() != 0) break;
            }
            System.out.println(&quot;Finished&quot;);
        });
        backgroundThread.start();
        TimeUnit.SECONDS.sleep(1);
        counter.increment();
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;But there are some cases where the volatile keyword is not enough. Let&amp;#8217;s think about the following code:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class IncrementByMultipleThreads {
    public static void main(String[] args) {
        VolatileCounter counter = new VolatileCounter();
        Set&amp;lt;Integer&amp;gt; ints = Collections.synchronizedSet(new HashSet&amp;lt;&amp;gt;());
        Runnable incrementer = () -&amp;gt; {
            while (true) {
                int increment = counter.increment();
                boolean added = ints.add(increment);
                if (!added) System.out.println(&quot;duplicate number detected&quot;);
            }
        };
        Thread t1 = new Thread(incrementer), t2 = new Thread(incrementer), t3 = new Thread(incrementer);
        t1.start(); t2.start(); t3.start();
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;First we create a volatile counter object and a Set of integers. We use a synchronized wrapper for the set in order to make it work properly in a concurrent usecase like this. And create a Runnable object which launches an infinite loop. In the loop, it increments the counter object and puts the return value of the increment method into the set. The set will be keeping all of the numbers the counter returned. And when it fails to add the number to the set, which means the same number was already added to the set, it prints that &quot;duplicate number detected&quot; message. And we launch 3 threads that execute the same Runnable object.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;It prints out a lot of the &quot;duplicate number detected&quot; messages immediately when I run it on my laptop. Which means the counter object has returned duplicate numbers. The reason behind this behavior is that the incrementation done by &lt;code&gt;++count&lt;/code&gt; is not atomic. What it does is that first it reads the number stored in the count field, adds 1 to it and stores the result into the count field and those are not atomically executed. And since we have 3 threads that are executing the increment method concurrently, there are chances that some of those threads read, calculate and return the same value.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;If we want the counter to return unique values for all of the threads, volatile is not sufficient. We can use a synchronized block to make it happen instead:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class IncrementByMultipleThreadsWithLock {
    public static void main(String[] args) {
        Counter counter = new Counter();
        Object lock = new Object();
        Set&amp;lt;Integer&amp;gt; ints = Collections.synchronizedSet(new HashSet&amp;lt;&amp;gt;());
        Runnable incrementer = () -&amp;gt; {
            while (true) {
                int increment;
                synchronized (lock) {
                    increment = counter.increment();
                }
                boolean added = ints.add(increment);
                if (!added) System.out.println(&quot;duplicate number detected&quot;);
            }
        };
        Thread t1 = new Thread(incrementer), t2 = new Thread(incrementer), t3 = new Thread(incrementer);
        t1.start(); t2.start(); t3.start();
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;We have introduced the lock object again, and put the increment() call inside the synchronized block. Since we have the synchronized block, we don&amp;#8217;t need the counter to be volatile anymore, therefore we can simply use the plain Counter class instead.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Now we get unique numbers from the counter and it doesn&amp;#8217;t show the &quot;duplicate number detected&quot; message anymore at least until the overflow of the counter field. In addition to the guarantee about the memory synchronization of mutable data, the synchronized block also guarantees that only one thread can execute the code placed inside the block at any given time. It effectively prevents the race condition where the counter returns duplicate numbers.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_which_classes_in_the_jdk_require_synchronization&quot;&gt;Which classes in the JDK require synchronization?&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;So we have seen that we need to use an appropriate way of synchronization for mutable data when it&amp;#8217;s shared across multiple threads. There are many classes in the Java standard library that contain mutable data or require synchronization if they are shared across multiple threads. It includes some of collection classes (HashMap, ArrayList etc.) and the Format class and its subclasses (e.g. SimpleDateFormat). To find out if a class requires synchronization, the first thing you can do is to consult the documentation of the class.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;If we fail to apply necessary synchronization, the consequences can be horrible. I once saw code which uses a HashMap shared across multiple threads without a synchronization. The HashMap was used as some kind of cache and there are multiple threads that update the HashMap and it could happen simultaneously. It eventually broke the underlying data structure of the HashMap and triggered an infinite loop under heavy load. Due to the fact that this kind of problem rarely shows up, it passed all of the QA processes we had and unfortunately ended up appearing in the production environment. I will never forget this incident because I was the one to fix the issue in midnight. There is a great article on the web which explains how an unsynchronized HashMap triggers an infinite loop: &lt;a href=&quot;https://mailinator.blogspot.com/2009/06/beautiful-race-condition.html&quot; class=&quot;bare&quot;&gt;https://mailinator.blogspot.com/2009/06/beautiful-race-condition.html&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;I also sometimes see a SimpleDateFormat object stored in a static field and shared across multiple threads. This is also dangerous. It might seem to be working fine for most of the time but occasionally it produces a wrong result or throws a mysterious exception under heavy load.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_how_do_we_do_synchronization_for_an_unsynchronized_class_in_the_jdk&quot;&gt;How do we do synchronization for an unsynchronized class in the JDK?&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Whenever we encounter a situation where we need to use some class which requires a synchronization in concurrent usecases, the first thing we can do is to look for a thread-safe equivalent.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;As for collection classes, there are quite a few thread-safe classes which cover almost all of the interfaces in the collection framework (e.g. ConcurrentHashMap, CopyOnWriteArrayList). If one of those suits your usecase, simply using one of them is the safest and easiest way to apply the synchronization. But one thing we need to keep in mind is that just using thread-safe classes doesn&amp;#8217;t always make your code work properly in concurrent usecases. For example, sometimes we need to make certain operations atomic like we did in one of the examples earlier. In such cases, we still need to use some kind of mutual execution exclusion mechanism like we did with the synchronization blocks.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;As for SimpleDateFormat, if the version of your Java is 8 or greater, please check the DateTimeFormatter class, which is immutable and thread-safe.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Also one important thing to remember is that just putting volatile doesn&amp;#8217;t make unsynchronized objects thread-safe. For example, when you have a HashMap field shared across multiple threads and you put volatile into the declaration of the HashMap field, it doesn&amp;#8217;t guarantee that the HashMap will work property in concurrent use cases.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;We have discussed why we need to synchronize mutable data, how we can do that and what happens when we fail to do that in concurrent usecases. The consequences can be horrible and a nasty thing about the failure of applying an appropriate synchronization is that everything looks fine for most of the time and the problem shows up only occasionally and sometimes it&amp;#8217;s even hard to reproduce. So I recommend paying extra attention when you have to deal with mutable data in concurrent usecases.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Another good way to reduce this kind of risk is minimizing mutability in the code. Immutable data is always safe to share across threads which means we don&amp;#8217;t have to even think about it if no mutable data is shared. One good starting point is that whenever you write a class, I recommend trying making the fields in your class final as much as possible. It will make your class one step closer to immutable.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;There are a lot of more things to learn for writing safe concurrent applications in Java. If you are interested, I recommend checking this book out: &lt;a href=&quot;https://jcip.net&quot; class=&quot;bare&quot;&gt;https://jcip.net&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/the-singleton-pattern-in-java</id>
        <title type="html">The Singleton Pattern in Java</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/the-singleton-pattern-in-java"/>
        <published>2020-09-22T03:47:08+00:00</published>
        <updated>2020-09-22T03:47:08+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="design-patterns" scheme="http://roller.apache.org/ns/tags/" />
        <category term="oop" scheme="http://roller.apache.org/ns/tags/" />
        <category term="software-design" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In this entry, I&amp;#8217;ll introduce some common ways to apply the Singleton Pattern in Java and a problem that can harm maintainability of your code base and a solution for the problem.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_what_is_it&quot;&gt;What is it?&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The Singleton Pattern is a commonly used idiom to create and maintain objects called singletons. A singleton is the only instance of a class.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Common use cases are an object which keeps the user&amp;#8217;s preferences in a desktop application, cache or a resource pool. One example would be a TCP connection pool where there are multiple active connections to a backend service like a database server or a web service. Typically there should be only one pool object which maintains all of the connections. Having multiple separate pool objects in one application doesn&amp;#8217;t make much sense in most cases because it will make the use of the pool less effective.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;As an example, let&amp;#8217;s imagine that there is the following interface which allows us to fetch the weather data from some external web service:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;interface WeatherFetcher {
    String fetchWeather(String cityCode) throws IOException;
    int fetchTemperature(String cityCode) throws IOException;
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;There are a couple of methods to fetch the weather (atmospheric conditions) and the temperature of a city. Since it involves network communcation, there can be an IOException.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Now imagine that you are working on implementing a feature which uses this interface. You are told that the performance requirement for this feature is strict, therefore you have decided to maintain a pool of active TCP connections to the external web service in order to keep the latency low. Applying the Singleton Pattern here sounds like a good idea because it will make sure that you will have only one pool object in your application.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_class_with_a_private_constructor&quot;&gt;Class with a private constructor&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Let&amp;#8217;s see how we can implement this with the Singleton Pattern. One simple implementation would be something like this:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class SimpleSingleton implements WeatherFetcher {
    private static final SimpleSingleton INSTANCE = new SimpleSingleton();
    public static WeatherFetcher getInstance() { return INSTANCE; }
    private SimpleSingleton() { System.out.println(&quot;Populating the connection pool...&quot;); }

    @Override
    public int fetchTemperature(String cityCode) {
        // gets an idle connection from the pool, sends a request
        return 71; // please assume it&apos;s from a response
    }

    @Override
    public String fetchWeather(String cityCode) {
        // gets an idle connection from the pool, sends a request
        return &quot;Sunny&quot;; // please assume it&apos;s from a response
    }

    // client code
    public static void main(String[] args) throws IOException {
        WeatherFetcher singleton = SimpleSingleton.getInstance();
        System.out.printf(&quot;Weather in New York: %s, %dF\n&quot;,
                singleton.fetchWeather(&quot;NewYork&quot;), singleton.fetchTemperature(&quot;NewYork&quot;));
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The class has a static final field called INSTANCE, where the only instance of this class is kept. There is a simple getter for that.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This class has a constructor populating the pool. Let&amp;#8217;s imagine that it opens a lot of connections to an external web service and makes those ready to use. The constructor is private, which prevents creation of another instance of the class. Without this, any other class can create an instance of this class, which means that there is no guarantee that there is only one instance of this class. It also prevents inheritance because there is no constructor a subclass can call.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In order to get the singleton, the client needs to call the static method getInstance() first. After that, the client can fetch the weather data via the methods defined in the WeatherFetcher interface.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_class_with_a_static_holder_class_for_lazy_initialization&quot;&gt;Class with a static holder class for lazy initialization&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The SimpleSingleton class works fine, but there is one common requirement you might encounter. Populating the connection pool can be expensive and there might be a situation where the feature we just implemented will be used by only a very small number of your users, and you want to make sure that the connection pool gets populated only when it&amp;#8217;s really needed.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;We cannot guarantee that with the SimpleSingleton class. Let&amp;#8217;s add a System.out.println() call to the main method and see what is happening there:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public static void main(String[] args) throws IOException {
    System.out.println(&quot;Doing some other stuff - I don&apos;t need the singleton yet&quot;); // added
    WeatherFetcher singleton = SimpleSingleton.getInstance();
    System.out.printf(&quot;Weather in New York: %s, %dF\n&quot;,
            singleton.fetchWeather(&quot;NewYork&quot;), singleton.fetchTemperature(&quot;NewYork&quot;));
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The main method yields the following output:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Populating the connection pool...
Doing some other stuff - I don&apos;t need the singleton yet
Weather in New York: Sunny, 71F&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;As you can see, the pool has got initialized even though it&amp;#8217;s not needed yet; the constructor gets executed before the getInstance() method is called because the constructor invocation is written in the static initializer of the class. It can lead to a situation where unnecessary resource consumption is imposed on the user even though the user might not need the feature. We can work around this with having a simple private static holder class like the following:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class LazySingleton implements WeatherFetcher {
    private static class SingletonHolder {
        static final LazySingleton INSTANCE = new LazySingleton();
    }
    public static WeatherFetcher getInstance() { return SingletonHolder.INSTANCE; }
    private LazySingleton() { System.out.println(&quot;Populating the connection pool...&quot;); }
    ...
    // client code
    public static void main(String[] args) throws IOException {
        System.out.println(&quot;Doing some other stuff - I don&apos;t need the singleton yet&quot;);
        WeatherFetcher singleton = LazySingleton.getInstance();
        System.out.printf(&quot;Weather in New York: %s, %dF\n&quot;,
                singleton.fetchWeather(&quot;NewYork&quot;), singleton.fetchTemperature(&quot;NewYork&quot;));
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The LazySingleton singleton instance is kept in the static field in the static inner class called SingletonHolder and the getInstance() method returns that. Executing the main method will show the following output, as expected:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Doing some other stuff - I don&apos;t need the singleton yet
Populating the connection pool...
Weather in New York: Sunny, 71F&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_a_problem_that_can_harm_maintainability_getinstance_everywhere&quot;&gt;A problem that can harm maintainability: getInstance() everywhere&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Let&amp;#8217;s imagine that now you need to implement some code for generating a report about the weather of some cities with the singleton we just wrote. It might be implemented like this:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class WeatherReporter {
    String generateWeatherReport(List&amp;lt;String&amp;gt; cityCodeList) {
        StringBuilder sb = new StringBuilder(&quot;=== Weather Report ===\n&quot;);
        for (String cityCode : cityCodeList) {
            try {
                String weather = LazySingleton.getInstance().fetchWeather(cityCode);
                int temperature = LazySingleton.getInstance().fetchTemperature(cityCode);
                sb.append(String.format(&quot;%s: %s, %dF\n&quot;, cityCode, weather, temperature));
            } catch (IOException e) {
                sb.append(String.format(&quot;%s: Failed to fetch data\n&quot;, cityCode));
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        WeatherReporter reporter = new WeatherReporter();
        System.out.println(reporter.generateWeatherReport(
                Arrays.asList(&quot;NewYork&quot;, &quot;Montreal&quot;, &quot;Tokyo&quot;)));
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;It receives a List of city code which we need to create the report for. Then it constructs the header, iterates the list of city code and fetches the weather and the temperature for each city and builds the String which represents the report. If there is an I/O problem, we just mention that it failed to fetch the data for the city.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Executing the main method should produce the following output:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Populating the connection pool...
=== Weather Report ===
NewYork: Sunny, 71F
Montreal: Cloudy, 68F
Tokyo: Rainy, 69F&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;That&amp;#8217;s a fairly complicated piece of code. Therefore, having some unit tests for the WeatherReporter class would be nice, but unfortunately it&amp;#8217;s almost impossible because the current implementation is hard-coded to directly call the static getInstance() method to get the WeatherFetcher object, which means it always sends requests to the real external web service.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;We cannot make a reliable assertion if it depends on the output of the real external service that way. One option would be running a fake of the external service, but it would require a lot of effort. And it would be nice if we could write a test case for IOException handling, but reproducing IOException in a real environment is also too much work. And the connection pool population might take a lot of time. The LazySingleton class might be hard-coded to create thousands of TCP connections and in that case it might take a few tens of seconds to populate. Waiting for such a long time with every unit test execution doesn&amp;#8217;t sound reasonable.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;So, the problem here is that we have business logic tightly coupled to an external data source. Having that kind of a method call in the middle of business logic makes writing unit tests very difficult or almost impossible because in order to make that kind of thing work, in many cases it requires some sort of specific setup or configuration and oftentimes that is too much work.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;One thing we can try to work around this problem is replacing the static getInstance() method call by a functional interface. In our case, we can do something like this:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class ImprovedWeatherReporter {

    private final Supplier&amp;lt;? extends WeatherFetcher&amp;gt; weatherFetcherSupplier;

    public ImprovedWeatherReporter(Supplier&amp;lt;? extends WeatherFetcher&amp;gt; weatherFetcherSupplier) {
        this.weatherFetcherSupplier = weatherFetcherSupplier;
    }

    String generateWeatherReport(List&amp;lt;String&amp;gt; cityCodeList) {
        StringBuilder sb = new StringBuilder(&quot;=== Weather Report ===\n&quot;);
        for (String cityCode : cityCodeList) {
            try {
                String weather = weatherFetcherSupplier.get().fetchWeather(cityCode);
                int temperature = weatherFetcherSupplier.get().fetchTemperature(cityCode);
                sb.append(String.format(&quot;%s: %s, %dF\n&quot;, cityCode, weather, temperature));
            } catch (IOException e) {
                sb.append(String.format(&quot;%s: Failed to fetch data\n&quot;, cityCode));
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        ImprovedWeatherReporter reporter = new ImprovedWeatherReporter(LazySingleton::getInstance);
        System.out.println(reporter.generateWeatherReport(
                Arrays.asList(&quot;NewYork&quot;, &quot;Montreal&quot;, &quot;Tokyo&quot;)));
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The ImprovedWeatherReporter class is not tightly coupled to the getInstance() method anymore. Instead, now it has a field for a Supplier object which returns a WeatherFetcher object. The client of this class can inject the Supplier via its constructor. In our case, we can inject LazySingleton.getInstance() for the production use.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;That seems to be not much change, but it is a great improvement from the perspective of unit testing. Now we can inject any Supplier returning a WeatherFeather object, and it enables us to write reliable, fast and stable unit tests like the following:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@ExtendWith(MockitoExtension.class)
class ImprovedWeatherReporterTest {

    @Mock
    WeatherFetcher weatherFetcher;
    ImprovedWeatherReporter sut;

    @BeforeEach
    void setUp() {
        sut = new ImprovedWeatherReporter(() -&amp;gt; weatherFetcher);
    }

    @Test
    void producesReports() throws IOException {
        when(weatherFetcher.fetchTemperature(&quot;NewYork&quot;)).thenReturn(71);
        when(weatherFetcher.fetchWeather(&quot;NewYork&quot;)).thenReturn(&quot;Sunny&quot;);
        when(weatherFetcher.fetchTemperature(&quot;Montreal&quot;)).thenReturn(68);
        when(weatherFetcher.fetchWeather(&quot;Montreal&quot;)).thenReturn(&quot;Cloudy&quot;);

        String actual = sut.generateWeatherReport(Arrays.asList(&quot;NewYork&quot;, &quot;Montreal&quot;));

        assertThat(actual).isEqualTo(&quot;=== Weather Report ===\n&quot; +
                &quot;NewYork: Sunny, 71F\n&quot; +
                &quot;Montreal: Cloudy, 68F\n&quot;);
    }

    @Test
    void exception() throws IOException {
        when(weatherFetcher.fetchTemperature(&quot;Tokyo&quot;)).thenThrow(new IOException(&quot;catch this&quot;));

        String actual = sut.generateWeatherReport(Collections.singletonList(&quot;Tokyo&quot;));

        assertThat(actual).isEqualTo(&quot;=== Weather Report ===\n&quot; +
                &quot;Tokyo: Failed to fetch data\n&quot;);
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;First, we create a mock of WeatherFetcher and inject a Supplier which returns the mock. With that, we can have complete control of the WeatherFetcher object the ImprovedWeatherReporter class relies on. Now we can specify what the WeatherFetcher object returns for what parameter with the mock framework you use. It will even enable us to test a case where the IOException is thrown, which was impossible with the tightly-coupled version of the WeatherReporter class. Just having a simple abstraction layer between your business logic and an external service makes writing unit tests much easier.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Another solution you might want to check is using a dependency injection framework to maintain singletons. You can easily make an object singleton and let the framework inject the singleton to the objects the framework maintains. It will reduce a lot of boilerplates, and some of the code I introduced here will be unnecessary. Especially if your code base has a dependency injection framework already, I recommend checking the documentation of your framework. For Google Guice, check this out: &lt;a href=&quot;https://github.com/google/guice/wiki/Scopes&quot; class=&quot;bare&quot;&gt;https://github.com/google/guice/wiki/Scopes&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;We&amp;#8217;ve seen a couple of common idioms that can be used to apply the Singleton Pattern in Java, and discussed a common maintainability issue that is sometimes caused by applying the pattern. When you see code where there are a lot of getInstance() calls in the middle of business logic, it might be good to take some time to see if you would be able to run your business logic in isolation for unit tests. If your code was unit test friendly, your code would be likely to have wider coverage of tests and it would make future maintenance easier and the code base more stable.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/favor-composition-over-inheritance</id>
        <title type="html">Favor composition over inheritance</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/favor-composition-over-inheritance"/>
        <published>2020-08-14T07:52:30+00:00</published>
        <updated>2020-11-11T13:45:02+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="oop" scheme="http://roller.apache.org/ns/tags/" />
        <category term="software-design" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In this entry, I&amp;#8217;ll discuss problems of inheritance, which is often overused in software written in an object oriented programming language, and how we can do better with composition, which is usually a much better alternative to inheritance.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_inheritance_can_make_your_code_fragile&quot;&gt;Inheritance can make your code fragile&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Let&amp;#8217;s think about some piece of software used by some cafe. It contains the following classes:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/1e95a7ea-3a54-4fcc-ad6b-798b5b3d1ebf&quot; alt=&quot;1e95a7ea 3a54 4fcc ad6b 798b5b3d1ebf&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;There is an interface called Beverage, which can return the price and description of a beverage. Most probably there are Coffee or Tea classes that implement the interface. And there is a class called Order, where you can add Beverage objects to it in order to calculate the grand total on the bill for a customer of the cafe. The code of these looks like this:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;interface Beverage {
    BigDecimal price();
    String description();
}

class Order {

    private static final BigDecimal TAX_RATE = new BigDecimal(&quot;0.1&quot;);
    private BigDecimal subTotal = BigDecimal.ZERO;

    void add(Beverage beverage) {
        subTotal = subTotal.add(beverage.price());
    }

    void addAll(Collection&amp;lt;? extends Beverage&amp;gt; beverages) {
        for (Beverage beverage : beverages)
            subTotal = subTotal.add(beverage.price());
    }

    BigDecimal grandTotal() {
        BigDecimal tax = subTotal.multiply(TAX_RATE);
        return subTotal.add(tax);
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Now, let&amp;#8217;s consider the following scenario: the owner of the cafe wants to start a campaign to boost their sales. The idea of the campaign is that if a customer orders more than 2 beverages at the same time, he/she will get 20% discount from the grand total. In order to implement this requirement, a programmer comes up with the CampaignOrder class which extends the Order class. It looks like the following:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class CampaignOrder extends Order {

    private static final BigDecimal DISCOUNT_RATE = new BigDecimal(&quot;0.2&quot;);
    private int numberOfBeverages;

    @Override
    void add(Beverage beverage) {
        super.add(beverage);
        numberOfBeverages++;
    }

    @Override
    void addAll(Collection&amp;lt;? extends Beverage&amp;gt; beverages) {
        super.addAll(beverages);
        numberOfBeverages += beverages.size();
    }

    @Override
    BigDecimal grandTotal() {
        BigDecimal grandTotal = super.grandTotal();
        if (numberOfBeverages &amp;gt; 2) {
            BigDecimal discount = grandTotal.multiply(DISCOUNT_RATE);
            grandTotal = grandTotal.subtract(discount);
        }
        return grandTotal;
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;It captures add() and addAll() method calls, forwards them to its superclass and keeps track of the number of the beverages which are added in the numberOfBeverages variable. And it also captures grandTotal() method calls, forwards them to its superclass and applies the 20% discount to the grand total the superclass calculated depending on the numberOfBeverages variable.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;It might look reasonable as it reuses the Order class effectively so that it won&amp;#8217;t introduce any duplicate code. But this approach can lead to an unforseen issue due to the fact that the CampaignOrder class relies on a hidden behavior of the Order class, which is that the add() method and the addAll() method work independently. Consider that at some point some other programmer has done some quick refactoring in the addAll() method:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class Order {
    ...
    void add(Beverage beverage) {
        subTotal = subTotal.add(beverage.price());
    }

    void addAll(Collection&amp;lt;? extends Beverage&amp;gt; beverages) {
        for (Beverage beverage : beverages)
            // Someone has done refactoring. Original code was:
            // subTotal = subTotal.add(beverage.price());
            // Now:
            add(beverage);
    }
    ...
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;It hasn&amp;#8217;t broken anything in terms of the functionality of the Order class but unfortunately it has just broken the CampaignOrder class. Remember the implementation of the CampaignOrder class which captures both of the add() and the addAll() method calls and counts the number of the beverage objects it receives. Due to the fact that now the Order class calls the add() method from the addAll() method, whenever the addAll() method of the CampaignOrder class gets called, the number of the beverage objects gets counted twice in the CampaignOrder class. In other words, now the following test case fails:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@ExtendWith(MockitoExtension.class)
class CampaignOrderTest {

    @Mock
    Beverage coffee, tea;
    CampaignOrder sut = new CampaignOrder();

    @Test
    void addAll() {
        when(coffee.price()).thenReturn(new BigDecimal(&quot;2.0&quot;));
        when(tea.price()).thenReturn(new BigDecimal(&quot;3.0&quot;));

        sut.addAll(Arrays.asList(coffee, tea));

        // It fails after the refactoring. Now grandTotal() returns 4.4
        // The discount is applied unexpectedly since the logic which counts beverages is broken
        // Now it&apos;s counted as 4, which is over the threshold of the discount
        assertThat(sut.grandTotal()).isEqualByComparingTo(&quot;5.5&quot;);
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The person who has done this refactoring should not be blamed. In fact this person removed a duplicate piece of code, which is a good thing, and it&amp;#8217;s not easy to catch such an error. The real problem here is the wrong use of inheritance, which is writing a subclass that relies on an implementation detail of its super class. That introduces fragility to the codebase. Hence using inheritance this way should be avoided.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;And also there can be another problematic case where a new method has been added to the Order class. If the new method can be used for adding a beverage, we need to make sure that the CampaignOrder class captures method calls to the new method, but chances are we would not even notice that there was a subclass which we might have to change.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;What could have been done instead of inheritance then? The most obvious approach is using composition instead. Let&amp;#8217;s rework the class hierarchy and make it like this:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/1d07a6e0-893d-4104-bfdb-177221cd449b&quot; alt=&quot;1d07a6e0 893d 4104 bfdb 177221cd449b&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The implementation:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;interface Order {
    void add(Beverage beverage);
    void addAll(Collection&amp;lt;? extends Beverage&amp;gt; beverages);
    BigDecimal grandTotal();
}

class RegularOrder implements Order {

    private static final BigDecimal TAX_RATE = new BigDecimal(&quot;0.1&quot;);
    private BigDecimal subTotal = BigDecimal.ZERO;

    @Override
    public void add(Beverage beverage) {
        subTotal = subTotal.add(beverage.price());
    }

    @Override
    public void addAll(Collection&amp;lt;? extends Beverage&amp;gt; beverages) {
        for (Beverage beverage : beverages)
            subTotal = subTotal.add(beverage.price());
    }

    @Override
    public BigDecimal grandTotal() {
        BigDecimal tax = subTotal.multiply(TAX_RATE);
        return subTotal.add(tax);
    }
}

class CampaignOrder implements Order {

    private static final BigDecimal DISCOUNT_RATE = new BigDecimal(&quot;0.2&quot;);
    private int numberOfBeverages;

    private final Order delegate;

    CampaignOrder() {
        this(new RegularOrder());
    }

    private CampaignOrder(Order delegate) {
        this.delegate = delegate;
    }

    @Override
    public void add(Beverage beverage) {
        delegate.add(beverage);
        numberOfBeverages++;
    }

    @Override
    public void addAll(Collection&amp;lt;? extends Beverage&amp;gt; beverages) {
        delegate.addAll(beverages);
        numberOfBeverages += beverages.size();
    }

    @Override
    public BigDecimal grandTotal() {
        BigDecimal grandTotal = delegate.grandTotal();
        if (numberOfBeverages &amp;gt; 2) {
            BigDecimal discount = grandTotal.multiply(DISCOUNT_RATE);
            grandTotal = grandTotal.subtract(discount);
        }
        return grandTotal;
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Now the Order class has become an interface which has 2 implementations. One is the RegularOrder class, which was formerly the Order class, and the other one is the CampaignOrder class. An instance of the CampaignOrder class has a reference to a RegularOrder instance in order to reuse its functionality, but the CampaignOrder class doesn&amp;#8217;t have any superclass anymore. With the new design, no refactoring of the RegularCampaign class can break the CampaignOrder class as long as the RegularOrder class keeps the contract of the public methods.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;One important difference from the inheritance approach is that now the CampaignOrder class no longer relies on any of the implementation details of the RegularOrder class. What it relies on now is the behavior of the public methods of the RegularOrder class, which are all defined in the Order interface.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The good thing about sticking with this approach is that as long as a class keeps its functionality on the public interface level the same, it can change its internal structure without you worrying about breaking something accidentally. It greatly reduces chances of unforseen breakage. Therefore, it will make your codebase more stable. Also, with having the interface, when a new method has been added to the interface, it will make the compilation of its implementors fail since the implementation is missing. With that, unlike with the inheritance solution, we can notice that we have to add the missing implementation to its implementors immediately.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_inheritance_is_inflexible&quot;&gt;Inheritance is inflexible&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Now let&amp;#8217;s think about some details of the Beverage interface in the codebase. It has an implemention class called Coffee. The customer can add a condiment such as milk, whip or sugar into it if they want to. For some reason, the original programmer implemented this requirement using inheritance:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/faea3261-015d-43d8-be9a-69c44d88c388&quot; alt=&quot;faea3261 015d 43d8 be9a 69c44d88c388&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;interface Beverage {
    BigDecimal price();
    String description();
}

class Coffee implements Beverage {
    @Override public BigDecimal price() { return new BigDecimal(&quot;1.99&quot;); }
    @Override public String description() { return &quot;Coffee&quot;; }
}

class CoffeeWithMilk extends Coffee {
    @Override public BigDecimal price() { return super.price().add(new BigDecimal(&quot;0.10&quot;)); }
    @Override public String description() { return super.description() + &quot;, Milk&quot;; }
}

class CoffeeWithWhip extends Coffee {
    @Override public BigDecimal price() { return super.price().add(new BigDecimal(&quot;0.15&quot;)); }
    @Override public String description() { return super.description() + &quot;, Whip&quot;; }
}

class CoffeeWithSugar extends Coffee {
    @Override public BigDecimal price() { super.price().add(new BigDecimal(&quot;0.05&quot;)); }
    @Override public String description() { return super.description() + &quot;, Sugar&quot;; }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Now we&amp;#8217;ve got a new requirement to implement, which is that a customer should be able to add multiple condiments into coffee. Let&amp;#8217;s see if we can do that with inheritance. It would look like the following:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/2d51746f-83fd-43ba-b0c5-3628272b7d88&quot; alt=&quot;2d51746f 83fd 43ba b0c5 3628272b7d88&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;We ended up creating a lot of subclasses for all of the combinations. That will do for the time being but think about the future expansion. We will need to create many subclasses everytime we introduce a new condiment. And what if we want to reuse code which is responsible for a condiment for another beverage class, say, a Tea class? It&amp;#8217;s not clear if we can do that in a reasonable way with this approach.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Let&amp;#8217;s see if we could do better with composition. It would look like the following:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/9b0b3122-c78b-4f45-b358-b30e682519dc&quot; alt=&quot;9b0b3122 c78b 4f45 b358 b30e682519dc&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The implementation (the Beverage interface and the Coffee class are the same as the ones we have seen before):&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class MilkWrapper implements Beverage {
    private final Beverage delegate;

    MilkWrapper(Beverage delegate) { this.delegate = delegate; }

    @Override public BigDecimal price() { return delegate.price().add(new BigDecimal(&quot;0.10&quot;)); }
    @Override public String description() { return delegate.description() + &quot;, Milk&quot;; }
}

class WhipWrapper implements Beverage {
    private final Beverage delegate;

    WhipWrapper(Beverage delegate) { this.delegate = delegate; }

    @Override public BigDecimal price() { return delegate.price().add(new BigDecimal(&quot;0.15&quot;)); }
    @Override public String description() { return delegate.description() + &quot;, Whip&quot;; }
}

class SugarWrapper implements Beverage {
    private final Beverage delegate;

    SugarWrapper(Beverage delegate) { this.delegate = delegate; }

    @Override public BigDecimal price() { return delegate.price().add(new BigDecimal(&quot;0.05&quot;)); }
    @Override public String description() { return delegate.description() + &quot;, Sugar&quot;; }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In the new implementation, the classes responsible for condiments hold a reference to a Beverage object instead of extending the Coffee class. They can still reuse the code of the Coffee class but through the Beverage interface. Instead of creating an instance of a subclass of the Coffee class, you need to provide a Coffee instance to the constructor of one of the wrapper classes. Let&amp;#8217;s do it like this:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@Test
void coffeeWithMilk() {
    Beverage coffeeWithMilk = new MilkWrapper(new Coffee());
    assertThat(coffeeWithMilk.description()).isEqualTo(&quot;Coffee, Milk&quot;);
    assertThat(coffeeWithMilk.price()).isEqualByComparingTo(&quot;2.09&quot;);
}

@Test
void coffeeWithWhip() {
    Beverage coffeeWithWhip = new WhipWrapper(new Coffee());
    assertThat(coffeeWithWhip.description()).isEqualTo(&quot;Coffee, Whip&quot;);
    assertThat(coffeeWithWhip.price()).isEqualByComparingTo(&quot;2.14&quot;);
}

@Test
void coffeeWithSugar() {
    Beverage coffeeWithSugar = new SugarWrapper(new Coffee());
    assertThat(coffeeWithSugar.description()).isEqualTo(&quot;Coffee, Sugar&quot;);
    assertThat(coffeeWithSugar.price()).isEqualByComparingTo(&quot;2.04&quot;);
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Now, let&amp;#8217;s see how we can implement the new requirement about multiple condiments with the new design. In fact, no change is needed in the Coffee class and the other classes in the diagram. We can do that like this:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@Test
void coffeeWithMilkAndWhip() {
    Beverage coffee = new Coffee();
    coffee = new MilkWrapper(coffee);
    coffee = new WhipWrapper(coffee);

    assertThat(coffee.description()).isEqualTo(&quot;Coffee, Milk, Whip&quot;);
    assertThat(coffee.price()).isEqualByComparingTo(&quot;2.24&quot;);
}

@Test
void coffeeWithMilkAndSugar() {
    Beverage coffee = new Coffee();
    coffee = new MilkWrapper(coffee);
    coffee = new SugarWrapper(coffee);

    assertThat(coffee.description()).isEqualTo(&quot;Coffee, Milk, Sugar&quot;);
    assertThat(coffee.price()).isEqualByComparingTo(&quot;2.14&quot;);
}

@Test
void coffeeWithMilkAndWhipAndSugar() {
    Beverage coffee = new Coffee();
    coffee = new MilkWrapper(coffee);
    coffee = new WhipWrapper(coffee);
    coffee = new SugarWrapper(coffee);

    assertThat(coffee.description()).isEqualTo(&quot;Coffee, Milk, Whip, Sugar&quot;);
    assertThat(coffee.price()).isEqualByComparingTo(&quot;2.29&quot;);
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;First, we create an instance of the Coffee class and then wrap it with the wrapper classes as needed. This is much more flexible than the old approach which required having subclasses for all of the combinations. We can even combine one particular condiment multiple times, which would have been much harder with the inheritance approach:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@Test
void coffeeWithTripleWhip() {
    Beverage coffee = new Coffee();
    coffee = new WhipWrapper(coffee);
    coffee = new WhipWrapper(coffee);
    coffee = new WhipWrapper(coffee);

    assertThat(coffee.description()).isEqualTo(&quot;Coffee, Whip, Whip, Whip&quot;);
    assertThat(coffee.price()).isEqualByComparingTo(&quot;2.44&quot;);
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This design is also better in terms of maintainability. Introducing a new condiment doesn&amp;#8217;t impact any other class in the diagram (i.e. there will be no class explosion). Those wrapper classes are highly reusable because they can be reused for anything which implements the Beverage interface. Also, they don&amp;#8217;t depend on anything but the Beverage interface. They solely rely on the public methods in the Beverage interface. There will be no breakage as long as the contract of the Beverage interface stays the same.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;We&amp;#8217;ve seen how improper use of inheritance can make your code fragile and inflexible. Using inheritance just for code reuse can lead to an unforseen problem in the future. And inheritance is not flexible as you might expect. When you are tempted to use inheritance, I recommend considering if you can do it using composition instead. In my experience, inheritance is not the best option for most of such cases.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;I would also like to mention that composition opens up a whole new world of clever design ideas in an object oriented programming language. If you want to learn more about it, I recommend checking out the following books:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://www.oreilly.com/library/view/head-first-design/0596007124/&quot;&gt;Head First Design Patterns&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610&quot;&gt;Design Patterns: Elements of Reusable Object-Oriented Software&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/java-generics-wildcards</id>
        <title type="html">Java Generics wildcards</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/java-generics-wildcards"/>
        <published>2020-07-17T09:49:22+00:00</published>
        <updated>2024-05-01T08:28:13+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="generics" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This entry is a quick introduction to Java Generics wildcards, which make Java code more flexible and type-safe.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_wildcards_with_extends&quot;&gt;Wildcards with extends&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Wildcards with extends provide flexibility to code which gets a value out of a container object. For example, let&amp;#8217;s consider the following variable definition:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;List&amp;lt;? extends Number&amp;gt; list_extendsNumber;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;You can think of it as a List which contains elements whose type is a subtype of Number. For example, we can assign the following instances to the variable:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;list_extendsNumber = new ArrayList&amp;lt;Number&amp;gt;();
list_extendsNumber = new ArrayList&amp;lt;Integer&amp;gt;(); // Integer extends Number
list_extendsNumber = new ArrayList&amp;lt;BigDecimal&amp;gt;(); // BigDecimal extends Number&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;But the following doesn&amp;#8217;t compile since neither of them is a subtype of Number:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;list_extendsNumber = new ArrayList&amp;lt;String&amp;gt;(); // compilation error; a String is not a Number
list_extendsNumber = new ArrayList&amp;lt;Object&amp;gt;(); // compilation error; Number extends Object but not the other way around&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;As you can see from the examples above, it&amp;#8217;s guaranteed that a List which is assigned to the list_extendsNumber variable contains a Number or a value whose type is a subtype of Number. We can use the variable for getting a value out of it as a Number. For example:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// It&apos;s guaranteed that it contains a Number or its subtype
Number firstNumber = list_extendsNumber.get(0);&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;You can even write some utility method like this:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;double avg(List&amp;lt;? extends Number&amp;gt; nums) {
    return nums.stream().mapToDouble(Number::doubleValue).average().orElse(0);
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The avg() method accepts any List whose type parameter is a subtype of Number. For example, the following code which calls the method works fine:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;List&amp;lt;Number&amp;gt; nums = Arrays.asList(1, 0.5d, 3);
assert avg(nums) == 1.5d;

List&amp;lt;Integer&amp;gt; ints = Arrays.asList(1, 2, 3);
assert avg(ints) == 2d;

List&amp;lt;BigDecimal&amp;gt; bds = Arrays.asList(new BigDecimal(1), new BigDecimal(2), new BigDecimal(3));
assert avg(bds) == 2d;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;But the following is invalid:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;List&amp;lt;String&amp;gt; strs = Arrays.asList(&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;);
avg(strs) // compilation error; a String is not a Number

List&amp;lt;Object&amp;gt; objs = Arrays.asList(&quot;foo&quot;, 0.5d, 3);
avg(objs) // compilation error; Number extends Object but not the other way around&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;What&amp;#8217;s good about it? Let&amp;#8217;s see what happens if we don&amp;#8217;t use the wildcard here. Now the method looks like this:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;double avg(List&amp;lt;Number&amp;gt; nums) {
    return nums.stream().mapToDouble(Number::doubleValue).average().orElse(0);
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Now the method can accept  only List&amp;lt;Number&amp;gt; that is much less flexible. The following still works:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;List&amp;lt;Number&amp;gt; nums = Arrays.asList(1, 0.5d, 3);
assert avg(nums) == 1.5d; // still fine&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;But neither of them compiles anymore:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;List&amp;lt;Integer&amp;gt; ints = Arrays.asList(1, 2, 3);
assert avg(ints) == 2d; // compilation error

List&amp;lt;BigDecimal&amp;gt; bds = Arrays.asList(new BigDecimal(1), new BigDecimal(2), new BigDecimal(3));
assert avg(bds) == 2d; // compilation error&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Which means that when you write code which gets values out of a container object (e.g. List), using wildcards with extends provides more flexibility. In other words, your code (or method) will be able to accept a wider range of parameters if wildcards with extends are used appropriately.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The limitation imposed by the use of wildcards with extends is that you won&amp;#8217;t be able to put any value except for null through a variable which uses extends. For example:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;List&amp;lt;? extends Number&amp;gt; list_extendsNumber = new ArrayList&amp;lt;Integer&amp;gt;();
list_extendsNumber.add(null); // compiles; null is the only exception
list_extendsNumber.add(1); // compilation error&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Why? Remember that we can assign any List whose type parameter is a subtype of Number. For example, you can also assign a List whose type parameter is BigDecimal to the list_extendsNumber variable. In that case adding an Integer to the List should be invalid since an Integer is not a BigDecimal. The compiler prevents it from happening thanks to generics and wildcards. Adding a null is fine since null is not tied to a particular type.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_wildcards_with_super&quot;&gt;Wildcards with super&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;While wildcards with extends make code which &lt;em&gt;gets&lt;/em&gt; a value more flexible, wildcards with super provide flexibility to code which &lt;em&gt;puts&lt;/em&gt; a value into a container object. Let&amp;#8217;s consider the following variable definition:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;List&amp;lt;? super Integer&amp;gt; list_superInteger;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;It means a List which contains elements whose type is a supertype of Integer. For example, we can assign the following instances into the variable:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;list_superInteger = new ArrayList&amp;lt;Integer&amp;gt;();
list_superInteger = new ArrayList&amp;lt;Number&amp;gt;(); // Number is a supertype of Integer
list_superInteger = new ArrayList&amp;lt;Object&amp;gt;(); // Object is a supertype of Integer&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;But the following doesn&amp;#8217;t compile:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;list_superInteger = new ArrayList&amp;lt;String&amp;gt;(); // compilation error; String is not a supertype of Integer&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;What we can see from the example above is that it&amp;#8217;s guaranteed that the List which is assigned to the list_superInteger variable can accept an Integer. We can use it for putting a value into it. For example:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// It&apos;s guaranteed that it can accept an Integer
list_superInteger.put(123);&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Or you can write some method with it like this:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;void addInts(List&amp;lt;? super Integer&amp;gt; ints) {
    Collections.addAll(ints, 1, 2, 3);
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The method can accept any of the following:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;List&amp;lt;Integer&amp;gt; ints = new ArrayList&amp;lt;&amp;gt;();
addInts(ints);
assert ints.toString().equals(&quot;[1, 2, 3]&quot;);

List&amp;lt;Number&amp;gt; nums = new ArrayList&amp;lt;&amp;gt;();
addInts(nums);
assert nums.toString().equals(&quot;[1, 2, 3]&quot;);

List&amp;lt;Object&amp;gt; objs = new ArrayList&amp;lt;&amp;gt;();
addInts(objs);
assert objs.toString().equals(&quot;[1, 2, 3]&quot;);&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;But the following doesn&amp;#8217;t compile:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;List&amp;lt;String&amp;gt; strs = new ArrayList&amp;lt;&amp;gt;();
addInts(strs); // compilation error; List&amp;lt;String&amp;gt; cannot accept an Integer&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;If we didn&amp;#8217;t use the wildcard, the method would be less flexible. Let&amp;#8217;s say now we have this without a wildcard:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;void addInts(List&amp;lt;Integer&amp;gt; ints) {
    Collections.addAll(ints, 1, 2, 3);
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The following still compiles:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;List&amp;lt;Integer&amp;gt; ints = new ArrayList&amp;lt;&amp;gt;();
addInts(ints);
assert ints.toString().equals(&quot;[1, 2, 3]&quot;);&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;But the following does not compile anymore:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;List&amp;lt;Number&amp;gt; nums = new ArrayList&amp;lt;&amp;gt;();
addInts(nums); // compilation error

List&amp;lt;Object&amp;gt; objs = new ArrayList&amp;lt;&amp;gt;();
addInts(objs); // compilation error&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The limitation imposed by the use of wildcards with super is that you will be able to get a value out of a container object only with the Object type. In other words, if you want to get a value out of the list_superInteger variable, this is the only thing you can do:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;List&amp;lt;Integer&amp;gt; ints = new ArrayList&amp;lt;&amp;gt;();
ints.add(123);
List&amp;lt;? super Integer&amp;gt; list_superInteger = ints;

Object head = list_superInteger.get(0); // only Object can be used as the type of head
assert head.equals(123);&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The following doesn&amp;#8217;t compile:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Integer head = list_superInteger.get(0); // compilation error&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Why? Remember that we can also assign a List&amp;lt;Number&amp;gt; or a List&amp;lt;Object&amp;gt; to the list_superInteger variable, which means that the only type that we can safely use to get a value out of it is the Object type.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_the_get_and_put_principle&quot;&gt;The Get and Put Principle&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;As we have seen, appropriate use of wildcards provides more flexibility to your code. To summarize when we should use which, there is a good principle to follow:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;&amp;#8220;The Get and Put Principle: Use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don&amp;#8217;t use a wildcard when you both get and put.&amp;#8221; - Naftalin, M., Wadler, P. (2007). Java Generics And Collections, O&amp;#8217;Reilly. p.19&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Functional interfaces exemplify this principle. For example, consider a method which accepts objects that implement functional interfaces as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;void myMethod(Supplier&amp;lt;? extends Number&amp;gt; numberSupplier, Consumer&amp;lt;? super String&amp;gt; stringConsumer) {
    Number number = numberSupplier.get();
    String result = &quot;I got a number whose value in double is: &quot; + number.doubleValue();
    stringConsumer.accept(result);
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Supplier is something which you can apply the get principle to; you only get values out of it. And Consumer is the same for the put principle; you only put values into it.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;myMethod() can accept various types of parameters. The user of the method doesn&amp;#8217;t necessarily have to pass a Supplier&amp;lt;Number&amp;gt; and a Consumer&amp;lt;String&amp;gt;. The user can also pass a Supplier&amp;lt;BigDecimal&amp;gt; and a Consumer&amp;lt;Object&amp;gt; as follows, but that&amp;#8217;s possible only with the use of the wildcards:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Supplier&amp;lt;BigDecimal&amp;gt; bigDecimalSupplier = () -&amp;gt; new BigDecimal(&quot;0.5&quot;);
AtomicReference&amp;lt;Object&amp;gt; reference = new AtomicReference&amp;lt;&amp;gt;();
Consumer&amp;lt;Object&amp;gt; objectConsumer = reference::set;

myMethod(bigDecimalSupplier, objectConsumer);

assert reference.get().equals(&quot;I got a number whose value in double is: 0.5&quot;);&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;We have seen how we can use wildcards, what the benefits of them are and when to use them. To make your code more flexible and reusable, especially when you write a method or a constructor, it&amp;#8217;s good practice to think if you can apply wildcards to code which handles an object that has a type parameter. Remembering the get and put principle will be helpful when you do so.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_references&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://www.oreilly.com/library/view/java-generics-and/0596527756/&quot;&gt;Naftalin, M., Wadler, P. (2007). Java Generics And Collections, O&amp;#8217;Reilly&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/junit-and-mockito-tips</id>
        <title type="html">JUnit and Mockito tips</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/junit-and-mockito-tips"/>
        <published>2020-07-03T09:40:03+00:00</published>
        <updated>2020-07-03T09:40:03+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="test" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In this entry I&amp;#8217;ll share some tips about JUnit and Mockito for making unit tests better.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_mockito_annotations&quot;&gt;Mockito annotations&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Mockito has some annotations that can be used for reducing redundancy of tests:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;@Mock&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;@InjectMocks&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;@Captor&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Before looking into the usage of those annotations, let&amp;#8217;s assume we have the following production code which consists of 2 classes.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The first one is called MailServer, which has a method called send() that sends an SMTP message which this object receives as the parameter of the method. Note that the MailServer class most probably needs to be mocked out when you want to write a unit test for a class which uses the MailServer class because it really opens a TCP connection to an SMTP server, which is not a preferable thing for unit tests.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class MailServer {
    void send(String smtpMessage) throws IOException {
        // Opens a connection to an SMTP server, sends the SMTP message
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The other class is called Messenger, which depends on the MailServer class. This class requires an instance of the MailServer class in its constructor. This class has a method called sendMail(), which has 3 parameters. The responsibility of this method is first constructing an SMTP message based on those 3 parameters and then asking the MailServer object to send the SMTP message. It also does quick error handling which translates IOException into an unchecked one with embedding the content.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class Messenger {

    private final MailServer mailServer;

    Messenger(MailServer mailServer) {
        this.mailServer = mailServer;
    }

    void sendMail(String from, String to, String body) {
        String smtpMessage = String.join(&quot;\n&quot;, &quot;From: &quot; + from, &quot;To: &quot; + to, &quot;&quot;, body);
        try {
            mailServer.send(smtpMessage);
        } catch (IOException e) {
            throw new UncheckedIOException(&quot;Error! smtpMessage=&quot; + smtpMessage, e);
        }
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Let&amp;#8217;s try writing a unit test for the Messenger class. But we don&amp;#8217;t want to use the real MailServer class because it really tries to open a connection to an SMTP server. It will make testing harder because in order to test with the real MailServer class, we really need an SMTP server which is up and running. Let&amp;#8217;s avoid doing that and try using a mocked version of a MailServer instance for the testing here.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;A happy path test case would look like the following:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class MessengerPlainTest {

    MailServer mailServer;
    Messenger sut;

    @BeforeEach
    void setUp() {
        mailServer = Mockito.mock(MailServer.class);
        sut = new Messenger(mailServer);
    }

    @Test
    @DisplayName(&quot;Messenger constructs the SMTP message and feeds MailServer&quot;)
    void test() throws IOException {
        String expected = &quot;From: joe@example.com\n&quot;
                + &quot;To: jane@example.com\n\n&quot;
                + &quot;Hello!&quot;;

        sut.sendMail(&quot;joe@example.com&quot;, &quot;jane@example.com&quot;, &quot;Hello!&quot;);

        Mockito.verify(mailServer).send(expected);
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In the setUp() method, a mock MailServer object is created and injected into the constructor of the Messenger class. And in the test() method, first we create the expected SMTP message which the Messenger class has to create, then we call the sendMail() method and finally we verify that the send() method of the mock MailServer object has been called with the expected SMTP message.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;With annotations, the test above can be written as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@ExtendWith(MockitoExtension.class)
class MessengerTest {

    @Mock
    MailServer mailServer;
    @InjectMocks
    Messenger sut;

    @Test
    @DisplayName(&quot;Messenger constructs the SMTP message and feeds MailServer&quot;)
    void test() throws IOException {
        String expected = &quot;From: joe@example.com\n&quot;
                + &quot;To: jane@example.com\n\n&quot;
                + &quot;Hello!&quot;;

        sut.sendMail(&quot;joe@example.com&quot;, &quot;jane@example.com&quot;, &quot;Hello!&quot;);

        Mockito.verify(mailServer).send(expected);
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;First we annotate the test class with @ExtendWith(MockitoExtension.class) (Note that it&amp;#8217;s a JUnit5 specific annotation, so for JUnit4 tests we need something different). Having the test class annotated with that one, when there is a field annotated with @Mock in the test class, Mockito will automatically create a mock for the field and inject it. And when there is a field annotated with @InjectMocks, Mockito will automatically create a real instance of the declared type and inject the mocks that are created by the @Mock annotation.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This is especially beneficial when many mock objects are needed because it reduces the amount of repetitive mock() method calls and also removes the need for creating the object which gets tested and injecting the mocks into the object.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;And also it provides a clean way to create a mock instance of a class which has a parameterized type. When we create a mock instance of the Consumer class, a straightforward way would be the following:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Consumer&amp;lt;String&amp;gt; consumer = Mockito.mock(Consumer.class);&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The problem here is that it produces an unchecked assignment warning. Your IDE will complain about it and you will get this warning when the code compiles with -Xlint:unchecked :&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Warning:(35, 49) java: unchecked conversion
  required: java.util.function.Consumer&amp;lt;java.lang.String&amp;gt;
  found:    java.util.function.Consumer&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;With the @Mock annotation, we can get rid of the warning:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@ExtendWith(MockitoExtension.class)
class MyTest {

    @Mock
    Consumer&amp;lt;String&amp;gt; consumer;
...&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;There is another useful annotation called @Captor. Let&amp;#8217;s see the following test case:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@ExtendWith(MockitoExtension.class)
class MessengerCaptorTest {

    @Mock
    MailServer mailServer;
    @InjectMocks
    Messenger sut;

    @Captor
    ArgumentCaptor&amp;lt;String&amp;gt; captor;

    @Test
    @DisplayName(&quot;Messenger constructs the SMTP message and feeds MailServer&quot;)
    void test() throws IOException {
        sut.sendMail(&quot;joe@example.com&quot;, &quot;jane@example.com&quot;, &quot;Hello!&quot;);

        Mockito.verify(mailServer).send(captor.capture());
        String capturedValue = captor.getValue();
        assertTrue(capturedValue.endsWith(&quot;Hello!&quot;));
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The @Captor annotation creates an object called ArgumentCaptor which captures a method parameter of a method call of a mock object. In order to capture a parameter with an ArgumentCaptor, first we need to call the capture() method in a method call chain of the Mockito.verify() method. Then we can get the captured value with the getValue() method and we can do any assertion against it. It&amp;#8217;s especially useful in a situation where checking the equality is not sufficient and a complex verification is needed.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_assertj&quot;&gt;AssertJ&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;AssertJ is an assertion library for unit tests written in Java. It provides better readability and richer assertions than its older equivalents like the one shipped with JUnit. Let&amp;#8217;s see some example code from &lt;a href=&quot;https://assertj.github.io/doc/&quot;&gt;the official website&lt;/a&gt;:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// entry point for all assertThat methods and utility methods (e.g. entry)
import static org.assertj.core.api.Assertions.*;

// basic assertions
assertThat(frodo.getName()).isEqualTo(&quot;Frodo&quot;);
assertThat(frodo).isNotEqualTo(sauron);

// chaining string specific assertions
assertThat(frodo.getName()).startsWith(&quot;Fro&quot;)
                           .endsWith(&quot;do&quot;)
                           .isEqualToIgnoringCase(&quot;frodo&quot;);

// collection specific assertions (there are plenty more)
// in the examples below fellowshipOfTheRing is a List&amp;lt;TolkienCharacter&amp;gt;
assertThat(fellowshipOfTheRing).hasSize(9)
                               .contains(frodo, sam)
                               .doesNotContain(sauron);&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;A unique feature of AssertJ is that all of the assertions here begin with the method assertThat() which receives the parameter that gets asserted. After that we specify the conditions the parameter needs to fulfill. An advantage of this approach is that we can specify multiple conditions with method call chain. It&amp;#8217;s more readable and less verbose than the old way where repetitive assertTrue() or assertEquals() calls are involved. It also provides rich assertions for widely used classes like List, Set or Map.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Another useful feature of AssertJ is for verifying an unhappy path where an Exception is involved. Let&amp;#8217;s remember the production code we used in the Mockito annotation section and consider a situation where the MailServer cannot connect to the SMTP server. Due to that, the send() method throws IOException. In this situation, the Messenger class is expected to catch the IOException and translate it into UncheckedIOException with the SMTP message embedded. A unit test for this can be written as follows with AssertJ:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@ExtendWith(MockitoExtension.class)
class MessengerUnhappyTest {

    @Mock
    MailServer mailServer;
    @InjectMocks
    Messenger sut;

    @Test
    @DisplayName(&quot;Messenger throws UncheckedIOException with the SMTP message when MailServer has thrown IOException&quot;)
    void test() throws IOException {
        doThrow(new IOException(&quot;The server is down&quot;)).when(mailServer).send(any());
        String expectedMessage = &quot;From: joe@example.com\n&quot;
                + &quot;To: jane@example.com\n\n&quot;
                + &quot;Hello!&quot;;

        assertThatThrownBy(() -&amp;gt; sut.sendMail(&quot;joe@example.com&quot;, &quot;jane@example.com&quot;, &quot;Hello!&quot;))
                .isInstanceOf(UncheckedIOException.class)
                .hasMessage(&quot;Error! smtpMessage=%s&quot;, expectedMessage)
                .hasCauseInstanceOf(IOException.class);
   }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;First we make the mock MailServer instance throw IOException when its send() method is called. After that we pass a lambda expression which calls the sendMail() method to the assertThatThrownBy() method of AssertJ. After that we can do various assertions. What we are checking here is that the sendMail() method throws UncheckedIOException with the SMTP message embedded and it also contains a parent Exception whose class is IOException.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;We&amp;#8217;ve discussed some tips about Mockito and the basic uses of AssertJ for test cases that are written in JUnit. Both Mockito and AssertJ have extensive documents and rich functionality which greatly helps writing unit tests. I highly recommend checking the references below:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://site.mockito.org/&quot;&gt;Mockito framework site&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://assertj.github.io/doc/&quot;&gt;AssertJ - fluent assertions java library&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://kaczanowscy.pl/books/practical_unit_testing_junit_testng_mockito.html&quot;&gt;Practical Unit Testing: JUnit 5, Mockito, TestNG, AssertJ - book by Tomek Kaczanowski&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The pieces of code which are used in this entry can be found on GitHub: &lt;a href=&quot;https://github.com/nuzayats/junittips&quot; class=&quot;bare&quot;&gt;https://github.com/nuzayats/junittips&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/jpa-builder-%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3</id>
        <title type="html">JPA Builder パターン</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/jpa-builder-%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3"/>
        <published>2016-12-03T15:00:00+00:00</published>
        <updated>2016-12-04T00:36:06+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="jpa" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;このエントリは &lt;a href=&quot;http://qiita.com/advent-calendar/2016/javaee&quot;&gt;Java EE Advent Calendar 2016&lt;/a&gt; の4日目の記事です．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;昨日は &lt;a href=&quot;http://qiita.com/opengl-8080/items/5190ee953cfbab5ce3e9&quot;&gt;opengl-8080 さんの「JPA マッピングカタログ」&lt;/a&gt; でした．明日は &lt;a href=&quot;http://qiita.com/tyru&quot;&gt;tyru さん&lt;/a&gt; です．&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;JPA のおかげで，多数のカラムや複雑なリレーションを持つテーブルへのレコード生成は，プレーンな JDBC を使っていた時代に比べると，たいへん楽になりました．しかし，いぜん頭を悩ませる局面もあります．例えば，以下の図のようなスキーマを考えてみてください:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/829fc6f6-cccb-44c2-816a-b7f397e83309&quot; alt=&quot;829fc6f6 cccb 44c2 816a b7f397e83309&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;このスキーマ中の Employee テーブルへレコードを生成するコードを考えてみてください．以下のようになると思います:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class EmployeeService {

    private final EntityManager em;

    EmployeeService(final EntityManager em) {
        this.em = em;
    }

    public long create(long deptId,
                       String name,
                       boolean temporary,
                       Set&amp;lt;Long&amp;gt; projectIds,
                       Set&amp;lt;String&amp;gt; phoneNumbers) {

        // instantiating and setting attributes of employee
        final Employee employee = new Employee();
        employee.setName(name);
        employee.setTemporary(temporary);
        employee.setProjects(new HashSet&amp;lt;&amp;gt;());
        employee.setPhones(new HashSet&amp;lt;&amp;gt;());

        // making a relation between employee and dept
        final Dept dept = em.find(Dept.class, deptId);
        employee.setDept(dept);
        em.persist(employee);
        dept.getEmployees().add(employee);

        // making relations between employee and projects
        for (final Long projectId : projectIds) {
            final Project project = em.find(Project.class, projectId);
            project.getEmployees().add(employee);
            employee.getProjects().add(project);
        }

        // creating phones
        for (final String phoneNumber : phoneNumbers) {
            final Phone phone = new Phone();
            phone.setNumber(phoneNumber);
            phone.setEmployee(employee);
            em.persist(phone);
            employee.getPhones().add(phone);
        }

        em.flush(); // making sure a generated id is present

        return employee.getId();
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;いま書いたメソッド create() を呼び出すコードは，以下のようになります:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;final Set&amp;lt;Long&amp;gt; projectIds = new HashSet&amp;lt;&amp;gt;();
Collections.addAll(projectIds, project1Id, project2Id);
final Set&amp;lt;String&amp;gt; phoneNumbers = new HashSet&amp;lt;&amp;gt;();
Collections.addAll(phoneNumbers, &quot;000-0000-0001&quot;, &quot;000-0000-0002&quot;, &quot;000-0000-0003&quot;);

final long savedEmployeeId = service.create(
        engineeringDeptId,
        &quot;Jane Doe&quot;,
        true,
        projectIds,
        phoneNumbers);&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;悪くはありません．しかし，もっと複雑なリレーションや省略可能なカラムが多数存在するケースを考えてみてください．それらに対応するメソッドの引数も多くなるのにしたがって，省略可能な引数に対応するためのオーバーロードや null の引数が並ぶメソッド呼び出しも増殖していき，だんだんメンテナンスが大変になっていきます．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;このようなケースでは，私が個人的に「JPA Builder パターン」と呼んでいる書き方がおすすめです．以下に示すような非 static のネストされた Builder クラスと，そのインスタンスを生成するためのメソッドを，前述の EmployeeService クラスに対して追加します:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;...

public Builder builder(long deptId, String name) {
    return new Builder(deptId, name);
}

public final class Builder { // non-static
    private final long deptId;
    private final String name;
    private boolean temporary;
    private Set&amp;lt;Long&amp;gt; projectIds = new HashSet&amp;lt;&amp;gt;();
    private Set&amp;lt;String&amp;gt; phoneNumbers = new HashSet&amp;lt;&amp;gt;();

    private Builder(final long deptId, final String name) {
        this.deptId = deptId;
        this.name = name;
    }

    public Builder temporary(boolean temporary) {
        this.temporary = temporary;
        return this;
    }

    public Builder projectIds(Long... ids) {
        Collections.addAll(projectIds, ids);
        return this;
    }

    public Builder phoneNumbers(String... numbers) {
        Collections.addAll(phoneNumbers, numbers);
        return this;
    }

    public long build() {
        // In reality, passing &quot;this&quot; instead of actual values (deptId, name, ...) is recommended
        return EmployeeService.this.create(deptId, name, temporary, projectIds, phoneNumbers);
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;これを呼び出すコードは，以下のようになります:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;final long savedEmployeeId = service.builder(engineeringDeptId, &quot;Jane Doe&quot;)
        .temporary(true)
        .projectIds(project1Id, project2Id)
        .phoneNumbers(&quot;000-0000-0001&quot;, &quot;000-0000-0002&quot;, &quot;000-0000-0003&quot;)
        .build();&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;今回の例のようにリレーションや省略可能なカラムの数がさほど多くない場合，あまりメリットがないように見えるかもしれませんが，現実には，もっと多い数になることは珍しくありません．そのようなケースでは，このパターンを使うことで保守性・可読性を維持・向上させることができます．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;このエントリで使用したクラスとテストを含むサンプルの一式は以下にありますので，実際に動かしてみたい方はチェックしてみてください．EclipseLink と Hibernate での動作を確認しています．DB のセットアップなどは必要なく，単に &quot;mvn test&quot; を叩くとインメモリの Apache Derby 上でテストが走ります:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/lbtc-xxx/jpa-builder-pattern&quot; class=&quot;bare&quot;&gt;https://github.com/lbtc-xxx/jpa-builder-pattern&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_宣伝_求人のご案内&quot;&gt;宣伝: 求人のご案内&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;現在，私の勤めている (株) L is B では，エンジニアを募集しています．主に &quot;direct&quot; という企業向けメッセンジャーの開発と運用を行っている会社です．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;残念ながら，今のところ GlassFish や WildFly のようなフルの Java EE コンテナは使われていないのですが，Java EE の構成要素，例えば JPA や JAX-RS などはヘビーに使われています．「Java EE を使って自社サービス開発したい！」という方，ぜひ以下をチェックしてみてください:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://www.l-is-b.com/ja/recruit/&quot; class=&quot;bare&quot;&gt;https://www.l-is-b.com/ja/recruit/&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://www.direct4b.com/&quot; class=&quot;bare&quot;&gt;https://www.direct4b.com/&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/lisb&quot; class=&quot;bare&quot;&gt;https://github.com/lisb&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/jersey-1-x-exceptionmapper-examples</id>
        <title type="html">Jersey 1.x ExceptionMapper examples</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/jersey-1-x-exceptionmapper-examples"/>
        <published>2016-10-29T03:42:56+00:00</published>
        <updated>2016-11-01T11:08:52+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="arquillian" scheme="http://roller.apache.org/ns/tags/" />
        <category term="jax-rs" scheme="http://roller.apache.org/ns/tags/" />
        <category term="jersey" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;&lt;strong&gt;CAUTION: this posting is about Jersey 1.x which is obsoleted. If you use more modern JAX-RS implementation such as Jersey 2.x or above, please check if there are any better approaches.&lt;/strong&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;JAX-RS (Jersey) provides a mechanism called &lt;strong&gt;ExceptionMapper&lt;/strong&gt; which is an universal way to map an exception that thrown by a JAX-RS implementation itself or application code, to any HTTP response. In this posting, I&amp;#8217;ll introduce some basic but useful usages of it that I have found.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_exceptionmapper_for_runtimeexception&quot;&gt;ExceptionMapper for RuntimeException&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;When your resource method throw an Exception, say, an unintentional NullPointerException which caused by a bug or something, typically this produces a 500 Error page which created by your application container. You can catch, log those exceptions and produce a customer-friendly response with an ExceptionMapper which is something like following:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@Provider
public class RuntimeExceptionMapper implements ExceptionMapper&amp;lt;RuntimeException&amp;gt; {

    private static final Logger LOGGER = Logger.getLogger(RuntimeExceptionMapper.class.getName());

    @Override
    public Response toResponse(final RuntimeException e) {
        // taken from http://stackoverflow.com/questions/13716793/jersey-how-to-register-a-exceptionmapper-that-omits-some-subclasses
        if (e instanceof WebApplicationException) {
            return ((WebApplicationException) e).getResponse();
        }

        LOGGER.log(Level.WARNING, &quot;RuntimeException occurred&quot;, e);

        return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(&quot;Sorry, something went wrong&quot;)
                .build();
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_exceptionmapper_for_notfoundexception&quot;&gt;ExceptionMapper for NotFoundException&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;When your app receive a request which has no corresponding resource method, typically this produces a 404 Error page created by your container as well as an uncaught Exception. You can handle this situation with an ExceptionMapper as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@Provider
public class NotFoundExceptionMapper implements ExceptionMapper&amp;lt;NotFoundException&amp;gt; {

    private static final Logger LOGGER = Logger.getLogger(NotFoundExceptionMapper.class.getName());

    @Override
    public Response toResponse(final NotFoundException e) {
        LOGGER.log(Level.FINE, &quot;NotFoundException occurred&quot;, e);

        return Response.status(Response.Status.NOT_FOUND)
                .entity(&quot;Check the destination path of your request - we have no API here&quot;)
                .build();
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_exceptionmapper_for_paramexceptionmapper&quot;&gt;ExceptionMapper for ParamExceptionMapper&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Let&amp;#8217;s say you have a value class which is something like following:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class EmployeeId {

    private final long value;

    public EmployeeId(final long value) {
        if (value &amp;lt; 1) {
            throw new IllegalArgumentException(&quot;EmployeeId must be larger than zero&quot;);
        }

        this.value = value;
    }

    public EmployeeId(final String value) {
        this(Long.parseLong(value));
    }

    // getter and toString omitted
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;And you have a resource method which receives an &lt;code&gt;EmployeeId&lt;/code&gt; as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@Path(&quot;myresource&quot;)
public class MyResource {

    @GET
    @Path(&quot;emp&quot;)
    @Produces(MediaType.TEXT_PLAIN)
    public String emp(@QueryParam(&quot;id&quot;) EmployeeId id) {
        ...
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;When the resource method receives a valid &lt;code&gt;id&lt;/code&gt;, say &lt;code&gt;123&lt;/code&gt;, Jersey automatically constructs an &lt;code&gt;EmployeeId&lt;/code&gt; instance and passes it to the application code. That&amp;#8217;s fine, but consider if a malicious user has sent an invalid value, say &lt;code&gt;-1&lt;/code&gt;. Typically this produces an error page which created by your container as well. You may want to return a more informational response with HTTP status code &lt;code&gt;400&lt;/code&gt; with an ExceptionMapper which is something like:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@Provider
public class ParamExceptionMapper implements ExceptionMapper&amp;lt;ParamException&amp;gt; {

    private static final Logger LOGGER = Logger.getLogger(ParamExceptionMapper.class.getName());

    @Override
    public Response toResponse(final ParamException e) {
        LOGGER.log(Level.FINE, &quot;ParamException occurred&quot;, e);

        final StringBuilder sb = new StringBuilder(&quot;Your parameter &apos;&quot; + e.getParameterName() + &quot;&apos; is invalid&quot;);

        final Throwable cause = e.getCause();
        if (cause instanceof IllegalArgumentException) {
            final String message = cause.getMessage();
            if (message != null &amp;amp;&amp;amp; !message.isEmpty()) {
                sb.append(&quot;: &quot;).append(message);
            }
        }

        return Response.status(Response.Status.BAD_REQUEST)
                .entity(sb.toString())
                .build();
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;ExceptionMapper helps making error responses of your REST APIs more helpful. And it reduces repetitive exception handling code in your resource classes that tend to be tons of boilarplate.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;You can obtain complete code based on Jersey 1.x and testcases that powered by Arquillian, Embedded Tomcat and Apache HttpClient, from &lt;a href=&quot;https://github.com/lbtc-xxx/jersey1-validation&quot;&gt;my GitHub repository&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_references&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://stackoverflow.com/questions/15185299/jax-rs-jersey-exceptionmappers-user-defined-exception&quot; class=&quot;bare&quot;&gt;http://stackoverflow.com/questions/15185299/jax-rs-jersey-exceptionmappers-user-defined-exception&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://maxenglander.com/2013/01/11/validating-jersey-request.html&quot; class=&quot;bare&quot;&gt;http://maxenglander.com/2013/01/11/validating-jersey-request.html&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/jpa-builder-pattern</id>
        <title type="html">JPA Builder Pattern</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/jpa-builder-pattern"/>
        <published>2016-10-16T09:07:19+00:00</published>
        <updated>2016-12-02T14:10:12+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="jpa" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Thanks to JPA, creating an entity which has tons of fields and complex relations has become much easier than the plain old JDBC era. but there are still some difficulties with it. for example, consider that you have a database schema which is something like following diagram:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/829fc6f6-cccb-44c2-816a-b7f397e83309&quot; alt=&quot;829fc6f6 cccb 44c2 816a b7f397e83309&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;With those entities, let&amp;#8217;s say you have to write some code for creating an employee. this would be something like:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class EmployeeService {

    private final EntityManager em;

    EmployeeService(final EntityManager em) {
        this.em = em;
    }

    public long create(long deptId,
                       String name,
                       boolean temporary,
                       Set&amp;lt;Long&amp;gt; projectIds,
                       Set&amp;lt;String&amp;gt; phoneNumbers) {

        // instantiating and setting attributes of employee
        final Employee employee = new Employee();
        employee.setName(name);
        employee.setTemporary(temporary);
        employee.setProjects(new HashSet&amp;lt;&amp;gt;());
        employee.setPhones(new HashSet&amp;lt;&amp;gt;());

        // making a relation between employee and dept
        final Dept dept = em.find(Dept.class, deptId);
        employee.setDept(dept);
        em.persist(employee);
        dept.getEmployees().add(employee);

        // making relations between employee and projects
        for (final Long projectId : projectIds) {
            final Project project = em.find(Project.class, projectId);
            project.getEmployees().add(employee);
            employee.getProjects().add(project);
        }

        // creating phones
        for (final String phoneNumber : phoneNumbers) {
            final Phone phone = new Phone();
            phone.setNumber(phoneNumber);
            phone.setEmployee(employee);
            em.persist(phone);
            employee.getPhones().add(phone);
        }

        em.flush(); // making sure a generated id is present

        return employee.getId();
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;And you will use the method &lt;code&gt;create()&lt;/code&gt; as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;final Set&amp;lt;Long&amp;gt; projectIds = new HashSet&amp;lt;&amp;gt;();
Collections.addAll(projectIds, project1Id, project2Id);
final Set&amp;lt;String&amp;gt; phoneNumbers = new HashSet&amp;lt;&amp;gt;();
Collections.addAll(phoneNumbers, &quot;000-0000-0001&quot;, &quot;000-0000-0002&quot;, &quot;000-0000-0003&quot;);

final long savedEmployeeId = service.create(
        engineeringDeptId,
        &quot;Jane Doe&quot;,
        true,
        projectIds,
        phoneNumbers);&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Not so bad, but think about if there are more complex relations or attributes that may be optional. the arguments of the method will be much longer, and hard to maintain.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In such a case, a pattern which I call &quot;JPA builder pattern&quot; would be nice. you create a non-static nested builder class and a method which creates a builder, into the class &lt;code&gt;EmployeeService&lt;/code&gt;, as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;...

public Builder builder(long deptId, String name) {
    return new Builder(deptId, name);
}

public final class Builder { // non-static
    private final long deptId;
    private final String name;
    private boolean temporary;
    private Set&amp;lt;Long&amp;gt; projectIds = new HashSet&amp;lt;&amp;gt;();
    private Set&amp;lt;String&amp;gt; phoneNumbers = new HashSet&amp;lt;&amp;gt;();

    private Builder(final long deptId, final String name) {
        this.deptId = deptId;
        this.name = name;
    }

    public Builder temporary(boolean temporary) {
        this.temporary = temporary;
        return this;
    }

    public Builder projectIds(Long... ids) {
        Collections.addAll(projectIds, ids);
        return this;
    }

    public Builder phoneNumbers(String... numbers) {
        Collections.addAll(phoneNumbers, numbers);
        return this;
    }

    public long build() {
        // In reality, passing &quot;this&quot; instead of actual values (deptId, name, ...) is recommended
        return EmployeeService.this.create(deptId, name, temporary, projectIds, phoneNumbers);
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;And you will use the builder as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;final long savedEmployeeId = service.builder(engineeringDeptId, &quot;Jane Doe&quot;)
        .temporary(true)
        .projectIds(project1Id, project2Id)
        .phoneNumbers(&quot;000-0000-0001&quot;, &quot;000-0000-0002&quot;, &quot;000-0000-0003&quot;)
        .build();&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;It doesn&amp;#8217;t make much sense if relations or attributes that may be optional are not that many as this example, but in reality, entities likely to have those much more. in such a case, I believe this pattern makes your code much clean, readable and maintainable.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;You can obtain the entire project which contains entities, the service class and executable tests that run with an embedded database, from &lt;a href=&quot;https://github.com/lbtc-xxx/jpa-builder-pattern&quot;&gt;my GitHub repo&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/jukito-integration-with-jpa-and</id>
        <title type="html">Jukito integration with JPA and guice-persist</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/jukito-integration-with-jpa-and"/>
        <published>2016-07-31T02:28:48+00:00</published>
        <updated>2016-09-22T04:06:53+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="guice" scheme="http://roller.apache.org/ns/tags/" />
        <category term="guice-persist" scheme="http://roller.apache.org/ns/tags/" />
        <category term="jpa" scheme="http://roller.apache.org/ns/tags/" />
        <category term="jukito" scheme="http://roller.apache.org/ns/tags/" />
        <category term="test" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;A DI container such as Guice helps you to assemble loosely-coupled classes that easy to write unit tests.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;But integration tests, that are necessary thing as well as unit tests, it&amp;#8217;s a different story from writing unit tests. writing integration tests involve many cumbersome initialization code of frameworks such as DI container, JPA provider or an application server. they tend to spread across testcases and make testcases messy.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;If you use Guice as DI container, Jukito helps you to write integration tests. &lt;a href=&quot;https://github.com/ArcBees/Jukito&quot;&gt;its official documentation&lt;/a&gt; covers some simple usecases, but not mentioned about integration with guice-persist. so in this entry I&amp;#8217;ll introduce you how to integrate and begin writing clean testcases without messy boilarplate code with them.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_create_an_application_to_be_tested&quot;&gt;Create an application to be tested&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Consider we have a simple JPA entity and a service class which uses it.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;An entity class named &lt;code&gt;Employee&lt;/code&gt;:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@Entity
public class Employee implements Serializable {
    @Id
    @GeneratedValue
    private Long id;
    private String name;

    public Employee(final String name) {
        this.name = name;
    }
...&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The service class to be tested named &lt;code&gt;EmployeeService&lt;/code&gt;:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class EmployeeService {

    @Inject
    private EntityManager em;

    @Transactional
    public Long save(final String name) {
        final Employee employee = new Employee(name);
        em.persist(employee);
        em.flush();
        return employee.getId();
    }

    public List&amp;lt;String&amp;gt; findAllNames() {
        return em.createQuery(&quot;SELECT e.name FROM Employee e ORDER BY e.name&quot;, String.class).getResultList();
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_create_a_module_for_testing&quot;&gt;Create a module for testing&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Next, we will create a module for testing (BTW I recommend you to use &lt;a href=&quot;http://google.github.io/guice/api-docs/latest/javadoc/index.html?com/google/inject/util/Modules.html&quot;&gt;Module overriding&lt;/a&gt; for creating one for testing, based on production one). this would be something like:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// Taken from https://gist.github.com/JWGmeligMeyling/785e459c4cbaab606ed8 , thanks!
public class DatabaseModule extends AbstractModule {

    @Override
    protected void configure() {
        install(new JpaPersistModule(&quot;myPU&quot;));
        bind(JPAInitializer.class).asEagerSingleton();
    }

    @Singleton
    private static class JPAInitializer {
        @Inject
        public JPAInitializer(final PersistService service) {
            service.start();
        }
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_create_jpajukitorunner&quot;&gt;Create JpaJukitoRunner&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Then, create a special TestRunner which extends &lt;code&gt;JukitoRunner&lt;/code&gt; as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class JpaJukitoRunner extends JukitoRunner {

    public JpaJukitoRunner(final Class&amp;lt;?&amp;gt; klass) throws InitializationError, InvocationTargetException, InstantiationException, IllegalAccessException {
        super(klass);
    }

    public JpaJukitoRunner(final Class&amp;lt;?&amp;gt; klass, final Injector injector) throws InitializationError, InvocationTargetException, InstantiationException, IllegalAccessException {
        super(klass, injector);
    }

    private UnitOfWork unitOfWork;

    @Override
    protected Object createTest() throws Exception {
        this.unitOfWork = getInjector().getInstance(UnitOfWork.class);
        this.unitOfWork.begin();
        return super.createTest();
    }

    @Override
    public void run(final RunNotifier notifier) {
        notifier.addListener(new RunListener() {

            @Override
            public void testFinished(final Description description) throws Exception {
                // this ensures every tests use distinct entity manager instances
                unitOfWork.end();
            }
        });
        super.run(notifier);
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This ensures every tests use distinct &lt;code&gt;EntityManager&lt;/code&gt; instances for each execution. without this, only one &lt;code&gt;EntityManager&lt;/code&gt; instance will be used for all of executions of test cases because it is stored in a &lt;code&gt;ThreadLocal&lt;/code&gt; and JUnit uses only one Thread by default for all test executions.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;That means that many entities will be kept managed during an execution. consider if you have thousands of test classes in your project - entities will be shared across all of test execution. it will make your EntityManager fat, also your tests may get affected by 1st level cache which got dirty by other test executions.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_create_a_testcase&quot;&gt;Create a testcase&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Finally, you can write a testcase as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@RunWith(JpaJukitoRunner.class)
@UseModules(DatabaseModule.class)
public class EmployeeServiceTest {

    @Inject
    private EmployeeService sut;
    @Inject
    private EntityManager em;

    @Before
    @Transactional
    public void setUp() throws Exception {
        em.createQuery(&quot;DELETE FROM Employee&quot;).executeUpdate();
    }

    @Test
    public void saveShouldPersistJohnDoe() throws Exception {
        final String name = &quot;John Doe&quot;;

        final long id = sut.save(name);

        final Employee employee = em.find(Employee.class, id);
        assertThat(employee.getName(), is(name));
    }

    @Test
    public void findAllNamesShouldReturnExpectedResult() throws Exception {
        sut.save(&quot;Jane Doe&quot;);
        sut.save(&quot;John Doe&quot;);

        final List&amp;lt;String&amp;gt; result = sut.findAllNames();

        assertThat(result.size(), is(2));
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;You can see that there are no any cumbersome initialization code of JPA or database stuff. and note that you can use declarative transaction management by &lt;code&gt;@Transactional&lt;/code&gt;, for both the sut class and populating test data into your database.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_cleaning_1st_level_cache&quot;&gt;Cleaning 1st level cache&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;I have mentioned about bad effect of 1st level cache of EntityManager earlier in this entry, so you may consider that you want to clean 1st level cache. you can do it with &lt;code&gt;em.clear()&lt;/code&gt;, or also something like following:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@RunWith(JpaJukitoRunner.class)
@UseModules(DatabaseModule.class)
public class EmployeeServiceTestManagesUOW {

    @Inject
    private Provider&amp;lt;EmployeeService&amp;gt; sut;
    @Inject
    private Provider&amp;lt;EntityManager&amp;gt; em;
    @Inject
    private UnitOfWork unitOfWork;

    @Before
    @Transactional
    public void setUp() throws Exception {
        em.get().createQuery(&quot;DELETE FROM Employee&quot;).executeUpdate();
    }

    @Test
    public void saveShouldPersistJohnDoe() throws Exception {
        final String name = &quot;John Doe&quot;;
        newEntityManager();

        final long id = sut.get().save(name);

        newEntityManager();
        final Employee employee = em.get().find(Employee.class, id);
        assertThat(employee.getName(), is(name));
    }

    private void newEntityManager() {
        unitOfWork.end();
        unitOfWork.begin();
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In this test, there are three distinct EntityManagers involved in a test execution. the one in &lt;code&gt;setUp()&lt;/code&gt;, another one in invocation of &lt;code&gt;sut#save()&lt;/code&gt; and finally one for &lt;code&gt;em#find()&lt;/code&gt; which is used for assertion.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;But in my opinion, this is an overkill and using one shared EntityManager for one test execution would be sufficient. if it didn&amp;#8217;t work well, something may wrong with your usage of JPA.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;We have seen how testcases which involve JPA and guice-persist could be written cleanly with Jukito. it enables us to eliminate cumbersome boilarplate code for managing and invoking &lt;code&gt;Injector&lt;/code&gt;, JPA initialization and manual transaction management. now our testcases look pretty clean.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Executable testcases and the example project can be obtained from &lt;a href=&quot;https://github.com/lbtc-xxx/jukito-jpa&quot;&gt;my GitHub repository&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_references&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://gist.github.com/JWGmeligMeyling/785e459c4cbaab606ed8&quot; class=&quot;bare&quot;&gt;https://gist.github.com/JWGmeligMeyling/785e459c4cbaab606ed8&lt;/a&gt; - many part of this entry taken from this gist. thank you so much!&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/managing-multiple-jpa-persistence-units</id>
        <title type="html">Managing multiple JPA persistence units with guice-persist</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/managing-multiple-jpa-persistence-units"/>
        <published>2016-06-19T09:15:35+00:00</published>
        <updated>2016-07-10T21:10:18+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="guice" scheme="http://roller.apache.org/ns/tags/" />
        <category term="jpa" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Guice has an extension named &lt;a href=&quot;https://github.com/google/guice/wiki/GuicePersist&quot;&gt;guice-persist&lt;/a&gt; which aim for providing integration between Guice and a data persistence mechanism. it gives declarative transaction management functionality with the annotation &lt;code&gt;@com.google.inject.persist.Transactional&lt;/code&gt; which works with  a standalone environment or plain servlet containers such as Tomcat or Jetty.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;&lt;code&gt;guice-persist&lt;/code&gt; supports JPA and it&amp;#8217;s simple to use with only one persistence unit, but to use it with multiple persistence units, it requires some tricks.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/google/guice/wiki/GuicePersistMultiModules&quot;&gt;The official Guice wiki has only some brief description&lt;/a&gt; and I can&amp;#8217;t find any complete example to implement it in an actual application. so, in this entry I&amp;#8217;ll give you a complete example about how to write a module which manages multiple persistence units.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_module_hierarchy&quot;&gt;Module hierarchy&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;To manage multiple PUs in a module, you should create &lt;code&gt;PrivateModule&lt;/code&gt; subclasses of the same number of your persistence units.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Let&amp;#8217;s say we have two persistence units that one is named &lt;code&gt;masterPU&lt;/code&gt; and another one named &lt;code&gt;slavePU&lt;/code&gt;. For example, we have the following &lt;code&gt;persistence.xml&lt;/code&gt; in an application:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&amp;gt;
&amp;lt;persistence version=&quot;2.1&quot; xmlns=&quot;http://xmlns.jcp.org/xml/ns/persistence&quot;
             xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
             xsi:schemaLocation=&quot;http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd&quot;&amp;gt;
    &amp;lt;persistence-unit name=&quot;masterPU&quot; transaction-type=&quot;RESOURCE_LOCAL&quot;&amp;gt;
...
    &amp;lt;/persistence-unit&amp;gt;
    &amp;lt;persistence-unit name=&quot;slavePU&quot; transaction-type=&quot;RESOURCE_LOCAL&quot;&amp;gt;
...
    &amp;lt;/persistence-unit&amp;gt;
&amp;lt;/persistence&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In this case, we are going to create and assemble classes as the following diagram:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/1788876a-6b06-4be0-a5d1-4cc3c2897b23&quot; alt=&quot;1788876a 6b06 4be0 a5d1 4cc3c2897b23&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;&lt;code&gt;MasterPu&lt;/code&gt; and &lt;code&gt;SlavePu&lt;/code&gt; are qualifier annotations that used for distinguish multiple bindings of JPA classes.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_writing_modules&quot;&gt;Writing modules&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;So, how do you write those modules? I&amp;#8217;ll show you some important parts of them.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_qualifier_annotations&quot;&gt;Qualifier annotations&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;First you need to create the two qualifier annotations something like this:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;import static java.lang.annotation.ElementType.*;

@javax.inject.Qualifier
@java.lang.annotation.Target({FIELD, PARAMETER, METHOD})
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
public @interface MasterPu {
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Don&amp;#8217;t forget about &lt;code&gt;SlavePu&lt;/code&gt; as well.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_jpapersistprivatemodule&quot;&gt;JpaPersistPrivateModule&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Now here&amp;#8217;s the most important part - this class installs &lt;code&gt;JpaPersistModule&lt;/code&gt; and rebinds and exposes JPA class bindings:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class JpaPersistPrivateModule extends PrivateModule {
    protected final String persistenceUnitName;
    protected final Properties props;
    protected final Class&amp;lt;? extends Annotation&amp;gt; qualifier;

    public JpaPersistPrivateModule(final String persistenceUnitName, final Properties props, final Class&amp;lt;? extends Annotation&amp;gt; qualifier) {
        this.persistenceUnitName = persistenceUnitName;
        this.props = props;
        this.qualifier = qualifier;
    }

    public JpaPersistPrivateModule(final String persistenceUnitName, final Class&amp;lt;? extends Annotation&amp;gt; qualifier) {
        this(persistenceUnitName, new Properties(), qualifier);
    }

    @Override
    protected void configure() {
        install(new JpaPersistModule(persistenceUnitName).properties(props));
        rebind(qualifier, EntityManagerFactory.class, EntityManager.class, PersistService.class, UnitOfWork.class);
        doConfigure();
    }

    private void rebind(Class&amp;lt;? extends Annotation&amp;gt; qualifier, Class&amp;lt;?&amp;gt;... classes) {
        for (Class&amp;lt;?&amp;gt; clazz : classes) {
            rebind(qualifier, clazz);
        }
    }

    private &amp;lt;T&amp;gt; void rebind(Class&amp;lt;? extends Annotation&amp;gt; qualifier, Class&amp;lt;T&amp;gt; clazz) {
        bind(clazz).annotatedWith(qualifier).toProvider(binder().getProvider(clazz));
        expose(clazz).annotatedWith(qualifier);
    }

    /**
     * bind your interfaces and classes as well as concrete ones that use JPA classes explicitly
     */
    protected void doConfigure() {
        // write your bindings in your subclasses
        // bindConcreteClassWithQualifier(MyTableService.class);
        // ...
    }

    /**
     * binds and exposes a concrete class with an annotation
     */
    protected &amp;lt;T&amp;gt; void bindConcreteClassWithQualifier(Class&amp;lt;T&amp;gt; clazz) {
        bind(clazz).annotatedWith(qualifier).to(clazz);
        expose(clazz).annotatedWith(qualifier);
    }

    /**
     * binds and exposes a concrete class without any annotation
     */
    protected void bindConcreteClass(Class&amp;lt;?&amp;gt; clazz) {
        bind(clazz);
        expose(clazz);
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;First, this class installs &lt;code&gt;JpaPersistModule&lt;/code&gt; and it creates bindings of JPA classes without any annotation but those bindings will not be exposed globally because we are in a &lt;code&gt;PrivateModule&lt;/code&gt;.  then, this class rebinds them with a qualifier annotation and exposes them with qualifier annotation. eventually, bindings of the four JPA classes will be created with a qualifier annotation.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_mymodule_masterpumodule_and_slavepumodule&quot;&gt;MyModule, MasterPuModule and SlavePuModule&lt;/h3&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        install(new MasterPuModule());
        install(new SlavePuModule());
    }

    private static class MasterPuModule extends JpaPersistPrivateModule {
        public MasterPuModule() {
            super(&quot;masterPU&quot;, MasterPu.class);
        }

        @Override
        protected void doConfigure() {
            bindConcreteClassWithQualifier(MyTableService.class);
        }
    }

    private static class SlavePuModule extends JpaPersistPrivateModule {
        public SlavePuModule() {
            super(&quot;slavePU&quot;, SlavePu.class);
        }

        @Override
        protected void doConfigure() {
            bindConcreteClassWithQualifier(MyTableService.class);
        }
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This class installs two &lt;code&gt;JpaPersistPrivateModule&lt;/code&gt; subclasses for persistence units and binds a service class named &lt;code&gt;MyTableService&lt;/code&gt; which requires injection of &lt;code&gt;EntityManager&lt;/code&gt;. this module creates two distinct annotated bindings for the class.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Note that if you need declarative transaction management by &lt;code&gt;@Transactional&lt;/code&gt; for your service classes, you should create bindings of them inside &lt;code&gt;doConfigure()&lt;/code&gt;. for example, if you creates such bindings in &lt;code&gt;MyModule#configure()&lt;/code&gt;, declarative transactions won&amp;#8217;t work.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_how_about_persistfilter&quot;&gt;How about PersistFilter?&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;If you need &lt;code&gt;PersistFilter&lt;/code&gt; for those two modules, you need to create a binding for each modules inside &lt;code&gt;doConfigure()&lt;/code&gt; as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Key&amp;lt;PersistFilter&amp;gt; key = Key.get(PersistFilter.class, qualifier);
bind(key).to(PersistFilter.class);
expose(key);&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Then, install all of modules inside your subclass of &lt;code&gt;ServletModule&lt;/code&gt;. after that, create filter mappings inside &lt;code&gt;configureServlets()&lt;/code&gt; as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;filter(&quot;/*&quot;).through(Key.get(PersistFilter.class, MasterPu.class));
filter(&quot;/*&quot;).through(Key.get(PersistFilter.class, SlavePu.class));&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;We have seen an example of a Guice module that manages two persistence units with &lt;code&gt;guice-persist&lt;/code&gt;. check &lt;a href=&quot;https://github.com/lbtc-xxx/guice-persist-two-pu&quot;&gt;my GitHub repository&lt;/a&gt; for the complete example project and testcases.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/in-container-jms-consumer-producer</id>
        <title type="html">In-container JMS consumer/producer example</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/in-container-jms-consumer-producer"/>
        <published>2016-05-14T14:06:12+00:00</published>
        <updated>2018-03-25T04:32:00+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="javaee" scheme="http://roller.apache.org/ns/tags/" />
        <category term="jms" scheme="http://roller.apache.org/ns/tags/" />
        <category term="wildfly" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In this entry, I&amp;#8217;ll show you a complete example of using JMS in a Java EE 7 compliant application container, through creating a webapp which consists of both a consumer and a producer. we&amp;#8217;re going to deploy it to a container (WildFly 10.0.0.Final) and see a webapp produces and consumes a message.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_launch_the_container&quot;&gt;Launch the container&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Launch WildFly server with the following parameter so the bundled message queue broker (ActiveMQ Artemis) will be launched:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;./standalone.sh -c standalone-full.xml&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;For IntelliJ IDEA, check how to launch WildFly with &lt;code&gt;-c standalone-full.xml&lt;/code&gt; from this SO:
&lt;a href=&quot;http://stackoverflow.com/questions/25849810/how-to-run-wildfly-with-standalone-full-xml-from-intellij-idea&quot; class=&quot;bare&quot;&gt;http://stackoverflow.com/questions/25849810/how-to-run-wildfly-with-standalone-full-xml-from-intellij-idea&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_define_a_queue&quot;&gt;Define a queue&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Launch &lt;code&gt;jboss-cli&lt;/code&gt; and define a queue with this command:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;jms-queue add --queue-address=testQueue --entries=queue/test,java:jboss/exported/jms/queue/test&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Check if it&amp;#8217;s successfully created:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[standalone@localhost:9990 /] /subsystem=messaging-activemq/server=default/jms-queue=testQueue:read-resource
{
    &quot;outcome&quot; =&amp;gt; &quot;success&quot;,
    &quot;result&quot; =&amp;gt; {
        &quot;durable&quot; =&amp;gt; true,
        &quot;entries&quot; =&amp;gt; [
            &quot;queue/test&quot;,
            &quot;java:jboss/exported/jms/queue/test&quot;
        ],
        &quot;legacy-entries&quot; =&amp;gt; undefined,
        &quot;selector&quot; =&amp;gt; undefined
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_create_the_webapp_which_contains_consumer_producer&quot;&gt;Create the webapp which contains consumer/producer&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Here we&amp;#8217;re going to create following three classes in the webapp:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;MyProducer&lt;/code&gt;: a Stateless Session Bean which produces a message to the queue&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;MyConsumer&lt;/code&gt;: a Message-Driven Bean which consumes any messages being sent to the queue&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;MyServlet&lt;/code&gt;: Receives HTTP GET request and kicks &lt;code&gt;MyProducer&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The whole project can be obtained from &lt;a href=&quot;https://github.com/lbtc-xxx/jms-example&quot;&gt;My GitHub repository&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_myproducer&quot;&gt;MyProducer&lt;/h3&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@Stateless
@LocalBean
public class MyProducer {

    @Resource(mappedName = &quot;java:/queue/test&quot;)
    Queue testQueue;
    @Inject
    JMSContext jmsContext;

    public void enqueue(final String text) {
        jmsContext.createProducer().send(testQueue, text);
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_myconsumer&quot;&gt;MyConsumer&lt;/h3&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@MessageDriven(name = &quot;MyMDB&quot;, activationConfig = {
        @ActivationConfigProperty(propertyName = &quot;destination&quot;, propertyValue = &quot;queue/test&quot;),
        @ActivationConfigProperty(propertyName = &quot;destinationType&quot;, propertyValue = &quot;javax.jms.Queue&quot;),
        @ActivationConfigProperty(propertyName = &quot;acknowledgeMode&quot;, propertyValue = &quot;Auto-acknowledge&quot;)})
public class MyConsumer implements MessageListener {

    private final static Logger LOGGER = Logger.getLogger(MyConsumer.class.toString());

    @Override
    public void onMessage(final Message msg) {
        if (msg instanceof TextMessage) {
            try {
                final String text = ((TextMessage) msg).getText();
                LOGGER.info(() -&amp;gt; &quot;Received: &quot; + text);
            } catch (final JMSException e) {
                throw new RuntimeException(e);
            }
        }
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_myservlet&quot;&gt;MyServlet&lt;/h3&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@WebServlet(urlPatterns = &quot;/&quot;)
public class MyServlet extends HttpServlet {

    @EJB
    MyProducer myProducer;

    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        final String text = &quot;Hello, JMS!&quot;;
        myProducer.enqueue(text);
        resp.getWriter().write(&quot;Published! check output of the consumer: &quot; + text + &quot;\n&quot;);
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Of course you don&amp;#8217;t need to put &lt;code&gt;MyConsumer&lt;/code&gt; to the webapp which contains &lt;code&gt;MyProducer&lt;/code&gt;. this is just an example, and in fact, just for asynchronous/background processing in a webapp, you better use more simple &lt;strong&gt;EJB Asynchronous methods&lt;/strong&gt; or &lt;strong&gt;ManagedExecutorService&lt;/strong&gt; instead of JMS. for real use-case, you may create a dedicated app for queue consumers and place your &lt;code&gt;MyConsumer&lt;/code&gt; equivalent into it.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_trigger_producing_and_consuming&quot;&gt;Trigger producing and consuming&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Deploy the app and submit HTTP GET request to it as follows.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ curl http://localhost:8080/jms-example/&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;If it worked successfully, you&amp;#8217;ll see following response from the Servlet:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Published! check output of the consumer: Hello, JMS!&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Then check console/output/log of your application container. if the consumer worked successfully, you can see the output something like following:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;13:55:18,168 INFO  [class jms.MyConsumer] (Thread-438 (ActiveMQ-client-global-threads-271921988)) Received: Hello, JMS!&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;As described above, thanks to JMS, we can develop a messaging app without tons of annoying, vendor-specific boilar plate code, in lean and simple semantics. there are no worries of maintaining logic of connection handling, polling loop and so forth in the application code.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;And note that there are no use of vendor-specific classes - it uses only standardized API which comes from &lt;code&gt;javaee-api&lt;/code&gt;. you may need to alter some portion of code when you deploy this example to other Java EE 7 compliant container such as GlassFish, WebLogic or WebSphere, but that should be few.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_references&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/wildfly/quickstart/tree/10.x/helloworld-jms&quot; class=&quot;bare&quot;&gt;https://github.com/wildfly/quickstart/tree/10.x/helloworld-jms&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/wildfly/quickstart/tree/10.x/helloworld-mdb&quot; class=&quot;bare&quot;&gt;https://github.com/wildfly/quickstart/tree/10.x/helloworld-mdb&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://stackoverflow.com/questions/28797023/configuring-injecting-a-jms-connection-factory-and-a-topic-in-wildfly&quot; class=&quot;bare&quot;&gt;http://stackoverflow.com/questions/28797023/configuring-injecting-a-jms-connection-factory-and-a-topic-in-wildfly&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/JMS2.0WebMessage/JMS2.0WebMessage.html&quot; class=&quot;bare&quot;&gt;http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/JMS2.0WebMessage/JMS2.0WebMessage.html&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/privatemodule-typeliteral-and-assistedinject-google</id>
        <title type="html">PrivateModule, TypeLiteral and AssistedInject - Google Guice techniques for complex scenarios</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/privatemodule-typeliteral-and-assistedinject-google"/>
        <published>2016-02-07T02:44:32+00:00</published>
        <updated>2016-02-11T01:19:14+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="di" scheme="http://roller.apache.org/ns/tags/" />
        <category term="guice" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In this entry I&amp;#8217;ll introduce you some Google Guice techniques that can be used for some complex class designing scenarios, I&amp;#8217;ve learned recently and found very helpful.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;I&amp;#8217;ve tested techniques that used in this entry works with Google Guice 3.0 and 4.0. &lt;a href=&quot;https://github.com/lbtc-xxx/guice-examples/tree/master/src/main/java&quot;&gt;example implementations&lt;/a&gt; and &lt;a href=&quot;https://github.com/lbtc-xxx/guice-examples/tree/master/src/test/java/test&quot;&gt;test cases&lt;/a&gt; can be obtained from &lt;a href=&quot;https://github.com/lbtc-xxx/guice-examples&quot;&gt;my GitHub repository&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_privatemodule&quot;&gt;PrivateModule&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Consider you have classes that something like following diagram:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/237fbbbb-c5d0-4315-aeef-ccc9e8b2605e&quot; alt=&quot;237fbbbb c5d0 4315 aeef ccc9e8b2605e&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;You have a service class named &lt;code&gt;MyService&lt;/code&gt; which depends on the interface named &lt;code&gt;MyStrategy&lt;/code&gt; (DOC, Depended On Component). the DOC has two implementations, the one &lt;code&gt;EnglishStrategy&lt;/code&gt; says &quot;Hello&quot;, when the method of it named &lt;code&gt;sayHello()&lt;/code&gt; is being called, and another one &lt;code&gt;JapaneseStrategy&lt;/code&gt; says &quot;Konnichiwa&quot;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;There are annotation classes &lt;code&gt;English&lt;/code&gt; and &lt;code&gt;Japanese&lt;/code&gt; to distinguish two strategy &lt;code&gt;MyService&lt;/code&gt; depends on. these two annotations are written as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;import static java.lang.annotation.ElementType.*;

@javax.inject.Qualifier
@java.lang.annotation.Target({FIELD, PARAMETER, METHOD})
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
public @interface English {
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;On that situation, you want Guice to produce and inject two &lt;code&gt;MyService&lt;/code&gt; instances for your client class. you would declare injection points as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;// (1) call for injection of MyService annotated as @English
@Inject
@English
MyService englishService;

// (2) call for injection of MyService annotated as @Japanese
@Inject
@Japanese
MyService japaneseService;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;But it doesn&amp;#8217;t work due to Guice failed to look &lt;code&gt;MyService&lt;/code&gt; binding annotated as &lt;code&gt;@English&lt;/code&gt; and &lt;code&gt;@Japanese&lt;/code&gt; up.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In such case, you can create two &lt;code&gt;PrivateModule&lt;/code&gt; and install them in your &lt;code&gt;Module&lt;/code&gt; implementation as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Override
protected void configure() {
    install(new PrivateModule() {
        @Override
        protected void configure() {
            // bind MyService annotated as English to MyService PRIVATELY
            bind(MyService.class).annotatedWith(English.class).to(MyService.class);

            // expose MyService annotated as English GLOBALLY. this fulfills injection point (1)
            expose(MyService.class).annotatedWith(English.class);

            // bind MyStrategy to EnglishStrategy PRIVATELY
            bind(MyStrategy.class).to(EnglishStrategy.class);
        }
    });
    install(new PrivateModule() {
        @Override
        protected void configure() {
            // bind MyService annotated as Japanese to MyService PRIVATELY
            bind(MyService.class).annotatedWith(Japanese.class).to(MyService.class);

            // expose MyService annotated as Japanese GLOBALLY. this fulfills injection point (2)
            expose(MyService.class).annotatedWith(Japanese.class);

            // bind MyStrategy to JapaneseStrategy PRIVATELY
            bind(MyStrategy.class).to(JapaneseStrategy.class);
        }
    });
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;These &lt;code&gt;PrivateModule&lt;/code&gt; create two bindings:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;olist arabic&quot;&gt;
&lt;ol class=&quot;arabic&quot;&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;MyService&lt;/code&gt; annotated with &lt;code&gt;English&lt;/code&gt; or &lt;code&gt;Japanese&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;MyStrategy&lt;/code&gt; without any annotation for &lt;code&gt;EnglishStrategy&lt;/code&gt; or &lt;code&gt;JapaneseStrategy&lt;/code&gt; privately&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;And, it &lt;strong&gt;exposes&lt;/strong&gt; only the binding 1. If the binding 2 exposes as well or created in global scope, Guice will complain that there are two bindings for &lt;code&gt;MyStrategy&lt;/code&gt; without any annotation. that&amp;#8217;s point what &lt;code&gt;PrivateModule&lt;/code&gt; helps.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_typeliteral&quot;&gt;TypeLiteral&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Consider you have following injection points that with generics type parameter:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Inject
List&amp;lt;String&amp;gt; stringList;
@Inject
List&amp;lt;Integer&amp;gt; integerList;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;To bind instances to these injection points, you need to use &lt;code&gt;TypeLiteral&lt;/code&gt; in your &lt;code&gt;Module&lt;/code&gt; implementation as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Override
protected void configure() {
    bind(new TypeLiteral&amp;lt;List&amp;lt;String&amp;gt;&amp;gt;() {
    }).toInstance(new ArrayList&amp;lt;String&amp;gt;() {{
        add(&quot;hello&quot;);
    }});

    bind(new TypeLiteral&amp;lt;List&amp;lt;Integer&amp;gt;&amp;gt;() {
    }).toInstance(new ArrayList&amp;lt;Integer&amp;gt;() {{
        add(123);
    }});
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;With this module, Guice resolves correct the two injection points with use of generics type parameter.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Also you can leave constructing an instance to Guice if you have an implementation class. for example, consider you have a generic interface as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public interface MyGenericService&amp;lt;T extends Number&amp;gt; {
    T get();
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Injection points:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Inject
MyGenericService&amp;lt;Integer&amp;gt; integerService;
@Inject
MyGenericService&amp;lt;Double&amp;gt; doubleService;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Two implementations:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public class MyIntegerService implements MyGenericService&amp;lt;Integer&amp;gt; {
    @Override
    public Integer get() {
        return 123;
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public class MyDoubleService implements MyGenericService&amp;lt;Double&amp;gt; {
    @Override
    public Double get() {
        return 0.5;
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;To create bindings to these injection points without creating instances in the module, you can write as follows in your module implementation:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;bind(new TypeLiteral&amp;lt;MyGenericService&amp;lt;Integer&amp;gt;&amp;gt;(){}).to(MyIntegerService.class);
bind(new TypeLiteral&amp;lt;MyGenericService&amp;lt;Double&amp;gt;&amp;gt;(){}).to(MyDoubleService.class);&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_assistedinject&quot;&gt;AssistedInject&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Consider you have classes that something like following diagram:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/703fa153-c547-4dd9-9145-70f36d55988e&quot; alt=&quot;703fa153 c547 4dd9 9145 70f36d55988e&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;You have a service class named &lt;code&gt;MyProduct&lt;/code&gt;, which requires a parameter &lt;code&gt;name&lt;/code&gt; for its constructor. the parameter &lt;code&gt;name&lt;/code&gt; varies in each injection, so we create the factory interface &lt;code&gt;MyFactory&lt;/code&gt; for it. also, &lt;code&gt;MyProduct&lt;/code&gt; depends on &lt;code&gt;MyCollaborator&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;You would create &lt;code&gt;MyProduct&lt;/code&gt; instance in your client as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Inject
MyFactory factory;
...
public void someMethodInClient() {
    final MyProduct product = factory.create(&quot;foo&quot;);
    ...
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;So, anyway, an implementation of &lt;code&gt;MyFactory&lt;/code&gt; is needed. it must be simple in this case but it brings another boilarplate code that should be avoided as possible. and imagine that if &lt;code&gt;MyProduct&lt;/code&gt; has a hundreds of DOCs? it will be longer as numbers of DOCs grows. manual construction procedure will be something like &lt;code&gt;new MyProduct(new MyCollaborator1(), new MyCollaborator2(), &amp;#8230;&amp;#8203;)&lt;/code&gt; . obviously, it should be avoided.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;With &lt;code&gt;AssistedInject&lt;/code&gt; , Guice will do it instead of you.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;First, create &lt;code&gt;MyFactory&lt;/code&gt; as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public interface MyFactory {
    MyProduct create(String name);
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Note that you don&amp;#8217;t need to create an implementation class yourself, just forget about it. next, put an additional dependency to your &lt;code&gt;pom.xml&lt;/code&gt;:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;com.google.inject.extensions&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;guice-assistedinject&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;4.0&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Put following procedure to your &lt;code&gt;Module&lt;/code&gt; implementation:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Override
protected void configure() {
    install(new FactoryModuleBuilder().build(MyFactory.class));
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Finally, declare an injection point in the &lt;code&gt;MyProduct&lt;/code&gt; class as follows. note that a constructor parameter &lt;code&gt;name&lt;/code&gt; is annotated as &lt;code&gt;@Assisted&lt;/code&gt;:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Inject
MyProduct(@Assisted final String name, final MyCollaborator collaborator) {
    this.name = name;
    this.collaborator = collaborator;
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;With that, Guice automatically creates &lt;code&gt;MyFactory&lt;/code&gt; implementation for you, and handles parameter &lt;code&gt;name&lt;/code&gt; nicely.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_references&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/google/guice/wiki/FrequentlyAskedQuestions&quot; class=&quot;bare&quot;&gt;https://github.com/google/guice/wiki/FrequentlyAskedQuestions&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/google/guice/wiki/AssistedInject&quot; class=&quot;bare&quot;&gt;https://github.com/google/guice/wiki/AssistedInject&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/jedit-conditional-line-deleting-with</id>
        <title type="html">jEdit conditional line deleting with regex</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/jedit-conditional-line-deleting-with"/>
        <published>2016-01-31T09:03:26+00:00</published>
        <updated>2016-01-31T09:03:26+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="jedit" scheme="http://roller.apache.org/ns/tags/" />
        <category term="regex" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_how_to_delete_lines_that_contains_a_keyword&quot;&gt;How to delete lines that contains a keyword?&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Open &lt;code&gt;Search And Replace&lt;/code&gt; dialog and turn &lt;code&gt;Regular expressions&lt;/code&gt; on then put &lt;code&gt;^.*KEYWORD.*$\n&lt;/code&gt; to &lt;code&gt;Search for&lt;/code&gt; box, leave &lt;code&gt;Replace with&lt;/code&gt; blank then hit &lt;code&gt;Replace All&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_how_to_delete_lines_that_not_contains_a_keyword&quot;&gt;How to delete lines that NOT contains a keyword?&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;With &lt;code&gt;^((?!KEYWORD).)*$\n&lt;/code&gt; do the same to the above. for detail check &lt;a href=&quot;http://stackoverflow.com/questions/406230/regular-expression-to-match-line-that-doesnt-contain-a-word&quot; class=&quot;bare&quot;&gt;http://stackoverflow.com/questions/406230/regular-expression-to-match-line-that-doesnt-contain-a-word&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/my-jedit-setup-on-os</id>
        <title type="html">My jEdit setup on OS X</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/my-jedit-setup-on-os"/>
        <published>2016-01-31T07:00:16+00:00</published>
        <updated>2016-02-06T00:57:11+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="jedit" scheme="http://roller.apache.org/ns/tags/" />
        <category term="osx" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_make_option_key_work&quot;&gt;Make Option key work&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Put a file contains following line to &lt;code&gt;$HOME/Library/jEdit/startup&lt;/code&gt; so shortcuts that used &lt;code&gt;Option&lt;/code&gt; work.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;Debug.ALT_KEY_PRESSED_DISABLED = false;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Check &lt;a href=&quot;http://www.nailedtothex.org/roller/kyle/entry/installing-and-configuring-jedit-5&quot; class=&quot;bare&quot;&gt;http://www.nailedtothex.org/roller/kyle/entry/installing-and-configuring-jedit-5&lt;/a&gt; for further information about setup jEdit on OS X.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_basic_configurations&quot;&gt;Basic configurations&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Just for my preferences:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Go to &lt;strong&gt;View&lt;/strong&gt; section&lt;/p&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;check &lt;strong&gt;Show full path of buffer in title bar&lt;/strong&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Go to &lt;strong&gt;Editing&lt;/strong&gt; section&lt;/p&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;set &lt;strong&gt;Word wrap&lt;/strong&gt; to &lt;strong&gt;soft&lt;/strong&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;set &lt;strong&gt;Wrap margin&lt;/strong&gt; to &lt;code&gt;100&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;check &lt;strong&gt;Soft (emulated with spaces) tabs&lt;/strong&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Go to &lt;strong&gt;Toolbar&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;uncheck &lt;strong&gt;Show tool bar&lt;/strong&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Go to &lt;strong&gt;Text Area&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;check &lt;strong&gt;Caret: thick&lt;/strong&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_customize_shortcut&quot;&gt;Customize shortcut&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;First, choose keymap &lt;code&gt;Mac OS X&lt;/code&gt;. Then customize maps that unusable by default because OS X takes precedence.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Incremental Search: &lt;code&gt;CMD+,&lt;/code&gt; launches application&amp;#8217;s preferences window. so I bind it to &lt;code&gt;Option+,&lt;/code&gt; instead.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Note: &lt;strong&gt;Draw multi-key shortcuts on screen menu bar&lt;/strong&gt; option makes some shortcut such as move to dockables unusable, I don&amp;#8217;t know why.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_basic_operations&quot;&gt;Basic operations&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;According to &lt;a href=&quot;http://comments.gmane.org/gmane.editors.jedit.user/6251&quot; class=&quot;bare&quot;&gt;http://comments.gmane.org/gmane.editors.jedit.user/6251&lt;/a&gt; , &lt;code&gt;C+c C+j&lt;/code&gt; : (Scroll to Current Line) can be used as &quot;Back To Text Area&quot; equivalent.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_macros&quot;&gt;Macros&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;From &lt;code&gt;Macros &amp;#8658; New Macro&lt;/code&gt;, you can create a BeanShell macros. For example, the macro below puts current date to the position of caret:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;textArea.setSelectedText(java.time.LocalDate.now().toString());&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_recommended_plugins&quot;&gt;Recommended plugins&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_project_viewer&quot;&gt;Project Viewer&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This plugin enables managing set of files in a unit named project. imagine the same name thing that implemented in some IDEs for Java development such as Eclipse or NetBeans.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;There are some plugin that requires it. For example, &lt;strong&gt;FastOpen&lt;/strong&gt; is a companion plugin for Project Viewer that enables open files fast with keyboard. I&amp;#8217;ve set &lt;strong&gt;Delay before searching&lt;/strong&gt; option to the smallest value (0.5sec).&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The documentation of this plugin can be obtained from &lt;a href=&quot;http://plugins.jedit.org/plugindoc/ProjectViewer/&quot; class=&quot;bare&quot;&gt;http://plugins.jedit.org/plugindoc/ProjectViewer/&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_console&quot;&gt;Console&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This plugin integrates console as a jEdit dockable.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Its advantages are commands that for invoking jEdit&amp;#8217;s functionalities. for example, &lt;code&gt;%edit foo.txt&lt;/code&gt; opens a file as a jEdit buffer. another useful one is redirecting output to a new jEdit buffer. for example, typing &lt;code&gt;echo hello, jEdit&lt;/code&gt; in the console and hitting &lt;code&gt;Ctrl+ENTER&lt;/code&gt; yields a new jEdit buffer with contents of &lt;code&gt;hello, jEdit&lt;/code&gt;. also there are many useful variable syntax. e.g. &lt;code&gt;${f}&lt;/code&gt; for the current buffer&amp;#8217;s path name. BeanShell console is available as well.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Also &lt;a href=&quot;http://plugins.jedit.org/plugindoc/SshConsole/&quot;&gt;SshConsole Plugin&lt;/a&gt; extends its functionality to support remote hosts can be connected with SSH.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;I recommend that check all three options in &lt;strong&gt;Console &amp;#8658; System Shell &amp;#8658; Events to chdir&lt;/strong&gt; at Plugin Options.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The documentation of this plugin can be obtained from &lt;a href=&quot;http://plugins.jedit.org/plugindoc/Console/&quot; class=&quot;bare&quot;&gt;http://plugins.jedit.org/plugindoc/Console/&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_whitespace&quot;&gt;WhiteSpace&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;As its name states it make whitespaces, tabs or control characters visible. I recommend you to set to show leading and trailing tabs / spaces by this plugin.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_texttools&quot;&gt;TextTools&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;It provides some useful text operations, such as &lt;strong&gt;Toggle Range Comment&lt;/strong&gt;. I recommend you to replace shortcuts for built-in ones by this plugin.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_jdiff_plugin&quot;&gt;jDiff Plugin&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;It shows difference between two files pretty nicely as IntelliJ.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_others&quot;&gt;Others&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Some worth considering plugins are:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;FTP&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;SQL&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;XML&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;MarkerSets&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/beanshell-recipies</id>
        <title type="html">BeanShell recipies</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/beanshell-recipies"/>
        <published>2016-01-24T07:00:35+00:00</published>
        <updated>2016-01-25T23:48:01+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="beanshell" scheme="http://roller.apache.org/ns/tags/" />
        <category term="jedit" scheme="http://roller.apache.org/ns/tags/" />
        <category term="maven" scheme="http://roller.apache.org/ns/tags/" />
        <category term="sql" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;BeanShell is a handy lightweight scripting language for Java. In this entry, I&amp;#8217;ll introduce you some useful snippets powered by BeanShell, and some recipies about it.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_setup_and_hello_world&quot;&gt;Setup and hello world&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Grab a copy of &lt;code&gt;bsh-2.0b4.jar&lt;/code&gt; from &lt;a href=&quot;http://www.beanshell.org&quot; class=&quot;bare&quot;&gt;http://www.beanshell.org&lt;/a&gt; and put following shell script named &lt;code&gt;bsh&lt;/code&gt; into your PATH:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;#!/bin/sh
BEANSHELL_JAR=$HOME/Downloads/bsh-2.0b4.jar # replace path to suit your environment
java -cp $BEANSHELL_JAR bsh.Interpreter $@&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Then fire up &lt;code&gt;bsh&lt;/code&gt; from your console then just put &lt;code&gt;print(&quot;hello, world!&quot;);&lt;/code&gt; to confirm it works.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;$ bsh
BeanShell 2.0b4 - by Pat Niemeyer (pat@pat.net)
bsh % print(&quot;hello, world!&quot;);
hello, world!&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Hit &lt;code&gt;Ctrl+D&lt;/code&gt; to exit interpreter.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;You can launch your BeanShell script in a file as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;$ echo &apos;print(&quot;hello, world!&quot;);&apos; &amp;gt; hello.bsh
$ bsh hello.bsh
hello, world!&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_stdin&quot;&gt;Stdin&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Text filtering script can be written as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
  String line = scanner.nextLine();
  System.out.println(line.toUpperCase());
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Save this script as &lt;code&gt;toUpperCase.bsh&lt;/code&gt; . The script can be executed as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;$ echo foo | bsh toUpperCase.bsh
FOO&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_command_line_arguments&quot;&gt;Command line arguments&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Command line arguments can be used as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;sb = new StringBuilder();
for (arg : bsh.args) {
    sb.append(arg);
}
print(sb);&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Save this script as &lt;code&gt;args.bsh&lt;/code&gt;. The script can be executed as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;$ bsh args.bsh foo bar
foobar&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_use_of_external_jar&quot;&gt;Use of external jar&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Any external jar can be added via &lt;a href=&quot;http://www.beanshell.org/manual/classpath.html&quot;&gt;addClassPath clause&lt;/a&gt; dynamically. For example, a SQL beautifier script powered by a Hibernate class can be written as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;addClassPath(&quot;/path/to/hibernate-core-4.3.7.Final.jar&quot;); // replace path to suit your environment
import org.hibernate.engine.jdbc.internal.BasicFormatterImpl;

scanner = new Scanner(System.in);
sb = new StringBuilder();
while (scanner.hasNextLine()) {
  sb.append(scanner.nextLine()).append(&apos;\n&apos;);
}

beautifized = new BasicFormatterImpl().format(sb.toString());
print(beautifized);&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Save this script as &lt;code&gt;sql-beautifier.bsh&lt;/code&gt; then execute following command:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;$ SQL=&quot;SELECT t0.content AS a2, t0.contenttype AS a3, t0.email AS a4 FROM roller_comment t0, weblogentry t1 WHERE ((t1.websiteid = &apos;f0588427-f2ca-4843-ac87-bbb31aa6013c&apos;) AND (t1.id = t0.entryid)) ORDER BY t0.posttime DESC LIMIT 31 OFFSET 0;&quot;
$ echo $SQL | bsh sql-beautifier.bsh&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This yields nicely formatted SQL:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;SELECT
    t0.content AS a2,
    t0.contenttype AS a3,
    t0.email AS a4
FROM
    roller_comment t0,
    weblogentry t1
WHERE
    (
        (
            t1.websiteid = &apos;f0588427-f2ca-4843-ac87-bbb31aa6013c&apos;
        )
        AND (
            t1.id = t0.entryid
        )
    )
ORDER BY
    t0.posttime DESC LIMIT 31 OFFSET 0;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_maven_plugin&quot;&gt;Maven plugin&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;If you have Maven installed, you can execute any BeanShell script without obtaining &lt;code&gt;bsh-2.0b4.jar&lt;/code&gt; by hand. Maven and the beanshell-maven-plugin takes care of it instead of you:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;$ mvn com.github.genthaler:beanshell-maven-plugin:1.0:run -Dbsh.file=&quot;hello.bsh&quot;
...
[INFO] --- beanshell-maven-plugin:1.0:run (default-cli) @ standalone-pom ---
[INFO] Executing Script
[INFO] file class java.lang.String
[INFO] script class java.lang.Object
[INFO] interpreting file hello.bsh
hello, world!&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Note that you don&amp;#8217;t need to create &lt;code&gt;pom.xml&lt;/code&gt; to execute a simple BeanShell script.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;For managing complex dependencies, you can leave that duty to Maven with &lt;code&gt;pom.xml&lt;/code&gt;:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&amp;gt;
&amp;lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;
         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&amp;gt;
    &amp;lt;modelVersion&amp;gt;4.0.0&amp;lt;/modelVersion&amp;gt;
    &amp;lt;groupId&amp;gt;sql-beautifier&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;sql-beautifier&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;1.0-SNAPSHOT&amp;lt;/version&amp;gt;
    &amp;lt;build&amp;gt;
        &amp;lt;plugins&amp;gt;
            &amp;lt;plugin&amp;gt;
                &amp;lt;groupId&amp;gt;com.github.genthaler&amp;lt;/groupId&amp;gt;
                &amp;lt;artifactId&amp;gt;beanshell-maven-plugin&amp;lt;/artifactId&amp;gt;
                &amp;lt;version&amp;gt;1.0&amp;lt;/version&amp;gt;
                &amp;lt;configuration&amp;gt;
                    &amp;lt;script&amp;gt;&amp;lt;![CDATA[
                    import java.nio.charset.Charset;
                    import org.apache.commons.io.FileUtils;
                    import org.hibernate.engine.jdbc.internal.BasicFormatterImpl;

                    file = new File(System.getProperty(&quot;sql&quot;));
                    sql = FileUtils.readFileToString(file, Charset.defaultCharset());
                    result = new BasicFormatterImpl().format(sql);

                    print(result);
         ]]&amp;gt;&amp;lt;/script&amp;gt;
                &amp;lt;/configuration&amp;gt;
                &amp;lt;dependencies&amp;gt;
                    &amp;lt;dependency&amp;gt;
                        &amp;lt;groupId&amp;gt;org.hibernate&amp;lt;/groupId&amp;gt;
                        &amp;lt;artifactId&amp;gt;hibernate-core&amp;lt;/artifactId&amp;gt;
                        &amp;lt;version&amp;gt;4.3.7.Final&amp;lt;/version&amp;gt;
                    &amp;lt;/dependency&amp;gt;
                    &amp;lt;dependency&amp;gt;
                        &amp;lt;groupId&amp;gt;commons-io&amp;lt;/groupId&amp;gt;
                        &amp;lt;artifactId&amp;gt;commons-io&amp;lt;/artifactId&amp;gt;
                        &amp;lt;version&amp;gt;2.4&amp;lt;/version&amp;gt;
                    &amp;lt;/dependency&amp;gt;
                &amp;lt;/dependencies&amp;gt;
            &amp;lt;/plugin&amp;gt;
        &amp;lt;/plugins&amp;gt;
    &amp;lt;/build&amp;gt;
&amp;lt;/project&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Save the SQL you want to beautify as &lt;code&gt;original.sql&lt;/code&gt; and executing following command yields similar result:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;$ mvn bsh:run -Dsql=original.sql&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_jedit_integration&quot;&gt;jEdit integration&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;&lt;a href=&quot;http://www.jedit.org&quot;&gt;jEdit&lt;/a&gt; has pretty nice integration with BeanShell. You can integrate that SQL beautifier as a jEdit macro. Put following snippet as &lt;code&gt;~/Library/jEdit/macros/FormatSQL.bsh&lt;/code&gt; (for OS X) or create it with &lt;code&gt;Macros &amp;#8594; New Macro&lt;/code&gt; from jEdit menu bar:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;addClassPath(&quot;/path/to/hibernate-core-4.3.7.Final.jar&quot;); // replace path to suit your environment
import org.hibernate.engine.jdbc.internal.BasicFormatterImpl;

sql = textArea.getSelectedText();
beautifized = new BasicFormatterImpl().format(sql);
textArea.setSelectedText(beautifized);&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Paste SQL to any jEdit buffer, and select SQL statement and execute the macro with &lt;code&gt;Macros &amp;#8594; FormatSQL&lt;/code&gt; to trigger formatting.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_references&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://shop.oreilly.com/product/0636920023463.do&quot;&gt;Learning Java, 4th Edition&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://www.beanshell.org&quot; class=&quot;bare&quot;&gt;http://www.beanshell.org&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://genthaler.github.io/beanshell-maven-plugin/&quot; class=&quot;bare&quot;&gt;http://genthaler.github.io/beanshell-maven-plugin/&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/beanshell/beanshell&quot; class=&quot;bare&quot;&gt;https://github.com/beanshell/beanshell&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://stackoverflow.com/questions/312552/looking-for-an-embeddable-sql-beautifier-or-reformatter&quot; class=&quot;bare&quot;&gt;http://stackoverflow.com/questions/312552/looking-for-an-embeddable-sql-beautifier-or-reformatter&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://www.jedit.org&quot; class=&quot;bare&quot;&gt;http://www.jedit.org&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/testing-guice-persist-nested-transactional</id>
        <title type="html">Testing guice-persist nested @Transactional behavior</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/testing-guice-persist-nested-transactional"/>
        <published>2015-12-23T04:41:47+00:00</published>
        <updated>2015-12-23T04:44:48+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="guice" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;There is no mention of nested use of &lt;code&gt;@Transactional&lt;/code&gt; in the &lt;a href=&quot;https://github.com/google/guice/wiki/Transactions&quot;&gt;Transactions page of official Guice Wiki&lt;/a&gt; so I&amp;#8217;ve done some testing about how transactions will be treated in nested use.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;As it turns out, Guice seems ignore any of nested &lt;code&gt;@Transactional&lt;/code&gt; and any of its &lt;code&gt;rollbackOn&lt;/code&gt; attributes. It&amp;#8217;s all up to the parent invoker.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;For testing, I created two classes as following UML diagram:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/b03b90cb-0b01-4601-9dac-755d79f2347e&quot; alt=&quot;b03b90cb 0b01 4601 9dac 755d79f2347e&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;&lt;code&gt;EnclosingService&lt;/code&gt; holds a reference to &lt;code&gt;EnclosedService&lt;/code&gt; and invokes a method of it from every method of &lt;code&gt;EnclosingService&lt;/code&gt;. Each name of methods state that what exception will be thrown from the method. For example, &lt;code&gt;EnclosedService#runtimeException()&lt;/code&gt; throws &lt;code&gt;RuntimeException&lt;/code&gt; while &lt;code&gt;EnclosedService#noException()&lt;/code&gt; won&amp;#8217;t throw any of Exception. &lt;code&gt;EnclosedService#ioExceptionWithRollbackOn()&lt;/code&gt; throws &lt;code&gt;IOException&lt;/code&gt; and annotated as &lt;code&gt;@Transactional(rollbackOn = IOException.class)&lt;/code&gt;. And names of methods of &lt;code&gt;EnclosingService&lt;/code&gt; states same but the part of after &lt;code&gt;_&lt;/code&gt; means that what method of &lt;code&gt;EnclosedService&lt;/code&gt; will be invoked.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;All of methods in both services save a Entity with &lt;code&gt;em.persist()&lt;/code&gt; then invoke &lt;code&gt;em.flush()&lt;/code&gt; so that every changes will be flushed immediately. i.e. &lt;code&gt;EnclosingService#noException_noException()&lt;/code&gt; saves two entities that one in the method itself and another one in the enclosing invocation of &lt;code&gt;EnclosedService#noException()&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Then I created &lt;a href=&quot;https://github.com/lbtc-xxx/guice-persist-nested-tx/blob/master/src/test/java/app/NestedTransactionalTest.java&quot;&gt;a test case&lt;/a&gt; which has 16 test methods that covers all of methods defined in &lt;code&gt;EnclosingService&lt;/code&gt; and found that any of &lt;code&gt;@Transactional&lt;/code&gt; annotation or &lt;code&gt;rollbackOn&lt;/code&gt; attribute in &lt;code&gt;EnclosedService&lt;/code&gt; are being ignored. I summarized the result in a table:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/0f595e00-fad6-4df1-b0d6-442024eca778&quot; alt=&quot;0f595e00 fad6 4df1 b0d6 442024eca778&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;I can see all of operations are atomic and any Exception thrown in methods of &lt;code&gt;EnclosedService&lt;/code&gt; doesn&amp;#8217;t affect the result if the transaction will be committed or rolled back. When Guice detects that it&amp;#8217;s a &lt;code&gt;RuntimeException&lt;/code&gt; or a checked exception that defined as &lt;code&gt;rollbackOn&lt;/code&gt; in &lt;strong&gt;the first method&lt;/strong&gt; which annotated as &lt;code&gt;@Transactional&lt;/code&gt; then rollback happen.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;All resources that used in this test &lt;a href=&quot;https://github.com/lbtc-xxx/guice-persist-nested-tx&quot;&gt;can be obtained from my GitHub repository&lt;/a&gt;. It used in-memory database of Apache Derby so that everyone can execute the testcase without any annoying preparation. Also EclipseLink 2.5.1, Guice 3.0 and log4jdbc are used so that I can see how transaction is going such as commit / rollback.&lt;/p&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/java-ee-%E3%83%96%E3%83%AD%E3%82%B0%E3%82%A8%E3%83%B3%E3%82%B8%E3%83%B3-apache-roller</id>
        <title type="html">Java EE ブログエンジン Apache Roller のご紹介</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/java-ee-%E3%83%96%E3%83%AD%E3%82%B0%E3%82%A8%E3%83%B3%E3%82%B8%E3%83%B3-apache-roller"/>
        <published>2015-12-02T23:00:00+00:00</published>
        <updated>2015-12-04T13:27:12+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="advent_calendar" scheme="http://roller.apache.org/ns/tags/" />
        <category term="javaee" scheme="http://roller.apache.org/ns/tags/" />
        <category term="roller" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;このエントリは &lt;a href=&quot;http://qiita.com/advent-calendar/2015/javaee&quot;&gt;Java EE Advent Calendar 2015&lt;/a&gt; の3日目（12月3日）の記事です．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;昨日は &lt;a href=&quot;https://twitter.com/empressia&quot;&gt;@empressia&lt;/a&gt; さんの &lt;a href=&quot;http://memory.empressia.jp/article/168997728.html&quot;&gt;「GlassFish上で動くWebアプリをGradleとNetBeansで開発するための準備」&lt;/a&gt;でした．
明日は &lt;a href=&quot;https://twitter.com/kencharos&quot;&gt;@kencharos&lt;/a&gt; さんの  &lt;a href=&quot;http://kencharos.hatenablog.com/entry/2015_adv_cal_4_jbatch&quot;&gt;「jBatch RI を Java SE でまともに(JPA,CDI,Transactionalつきで)動かす」&lt;/a&gt; です．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_自己紹介&quot;&gt;自己紹介&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;業務ではJPA, JAX-RSなどを使っているソフトウェアエンジニアです．趣味ではWildFly, JBatch, JSFなどを使っていろいろ作ったり，Java/Java EE関連OSSの不具合を見つけてパッチやPull Requestを送ったりしています．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;今回紹介する &lt;a href=&quot;https://roller.apache.org/&quot;&gt;Apache Roller&lt;/a&gt; のコミッタをやっているのですが，日本ではあまり知名度がないので，少しでも日本の方に興味を持ってもらえればと思い，紹介記事を書くことにしました．&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_apache_rollerとは&quot;&gt;Apache Rollerとは？&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;&lt;a href=&quot;https://roller.apache.org/&quot;&gt;Apache Roller&lt;/a&gt;は，Javaサーブレットコンテナ向けのオープンソースブログエンジンで，WordPressやMovable Typeとほぼ同じジャンルのソフトウェアです．元Sun Microsystemsのエンジニア &lt;a href=&quot;http://rollerweblogger.org/roller/&quot;&gt;David M. Johnsonさん&lt;/a&gt;によって2002年に作られ，blogs.sun.com（現 &lt;a href=&quot;https://blogs.oracle.com&quot;&gt;blogs.oracle.com&lt;/a&gt; ）などで利用されてきました．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;現在の最新バーションは，2015年3月にリリースされた5.1.2です．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_誰が使っているの&quot;&gt;誰が使っているの？&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Rollerはさまざまな組織や個人によって使われています．組織での使用例としては，Javaエンジニアにはおなじみの &lt;a href=&quot;https://blogs.oracle.com&quot;&gt;Oracle blogs&lt;/a&gt; や， &lt;a href=&quot;https://www.ibm.com/developerworks/community/blogs/roller-ui/homepage&quot;&gt;IBM developerworks blog&lt;/a&gt;， &lt;a href=&quot;https://blogs.apache.org/foundation/&quot;&gt;Apache Foundation&lt;/a&gt;のブログなどがあります．他にも世界中のさまざまな企業，官公庁などで使われています．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;個人では，Java EEを追っかけている人にはおなじみの &lt;a href=&quot;http://www.adam-bien.com/roller/abien/&quot;&gt;Adam Bienさん&lt;/a&gt; ，Javaの父 &lt;a href=&quot;http://nighthacks.com/roller/jag/&quot;&gt;James Goslingさん&lt;/a&gt;などが，Rollerを使ってブログを書いています． &lt;a href=&quot;http://roller.apache.org/project/whoweare.html&quot;&gt;コミッタ&lt;/a&gt;もそれぞれ自分でRollerのブログを持っています．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;その他多数のユーザについては &lt;a href=&quot;https://cwiki.apache.org/confluence/display/ROLLER/PoweredByRoller&quot;&gt;オフィシャルのWikiページ&lt;/a&gt;にまとめられています．&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_使われている技術&quot;&gt;使われている技術&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;DIコンテナとしてはGuiceが使われていて，パーシステンス層ではEclipseLink，ビュー・コントローラ層はStruts2 + JSP + Servlet，ブログのデザインなどはVelocityテンプレートで書けるようになっています．認証まわりではSpring Security，全文検索エンジンとしてはLuceneが使われています．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;ServletとJSPのコードが多く，今となってはちょっと時代遅れな感は否めませんが，ソースは全て公開されているので，Javaで書かれていてリアルに運用されているWebシステムのサンプルとして一つの参考になるかもしれません．&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_特徴&quot;&gt;特徴&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_マルチユーザー_マルチブログに対応&quot;&gt;マルチユーザー・マルチブログに対応&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;1つのインストレーションで複数のブログ，ユーザを作ることができます．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;各ユーザーには3種類の権限のうちいずれかを割り当てることができ，具体的には，エントリの下書きだけができるユーザ(Limited)，エントリの投稿などはできるがブログやシステムの設定変更はできないユーザ(Author)，全ての操作ができるユーザ(Admin)のうちいずれかをユーザごとに割り当てることができます．組織用ブログなどで，日常的にレビュープロセスを取り入れているようなケースで便利に使うことができます． &lt;a href=&quot;https://cwiki.apache.org/confluence/display/ROLLER/Roller+5.1+with+LDAP&quot;&gt;LDAP認証に対応している&lt;/a&gt;のも組織で使いやすいポイントです．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;個人で使う場合でも，複数のブログをかんたんに作れるので，たとえば技術系エントリはこのブログ，趣味の旅行の話題はまた別のブログ，といった感じで使い分けることができます．もちろん，それぞれのブログのデザインやテンプレートはべつべつに管理できます．&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_さまざまなdb_アプリケーションサーバに対応&quot;&gt;さまざまなDB・アプリケーションサーバに対応&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;DBスキーマ生成用スクリプトとして，MySQL，PostgreSQL，Oracle，DB2，SQL Server，Derby，HSQLDB用のものが用意されています．ほとんどのユーザおよび開発メンバが使っているのはMySQLなので，特に理由がなければMySQL 5.6.x以降をおすすめします（次のリリースからは5.6.xより前のサポートがなくなる予定なので）．個人的にはPostgreSQLを使っていて，このブログもPostgreSQLで動いています．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;いわゆるサーブレットコンテナ向けに作られているので，TomcatやJettyをはじめ，JBoss(WildFly)，GlassFishなどのJava EEコンテナにもデプロイできます．ほとんどのユーザはTomcatを使っているようですが，個人的にはWildFly（このブログ）やJBoss EWSにデプロイして使っています．&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_javaでプラグインが書ける&quot;&gt;Javaでプラグインが書ける&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;最近のブログサービスでは，冗長なHTMLだけではなくMarkdownや「はてな記法」のような簡潔なシンタックスを使ってエントリを書けるものが多くでてきています．Rollerがデフォルトでサポートしているのは標準的なHTMLだけですが，プラグインを使うことで，そういったシンタックスを使ってブログエントリを書けるようになります．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;個人的には， &lt;a href=&quot;https://github.com/lbtc-xxx/roller-asciidoctorj-plugin&quot;&gt;Asciidoctorjプラグイン&lt;/a&gt;というものを作り &lt;a href=&quot;http://www.methods.co.nz/asciidoc/&quot;&gt;AsciiDoc&lt;/a&gt; シンタックスを使って日常的にエントリを書いています（このエントリもそうです）．他にも &lt;a href=&quot;https://github.com/myabc/roller-markdown&quot;&gt;Markdown&lt;/a&gt; や &lt;a href=&quot;https://github.com/snoopdave/roller-jspwiki-plugin&quot;&gt;JSPWiki&lt;/a&gt; プラグインなど，いくつかのプラグインが公開されており，別途インストールすることで利用できるようになります．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;プラグインを書くのはとても簡単で，適用するプラグインはエントリごとにべつべつに設定できます．今後またなんらかの新たな記法が登場してそれを使いたくなったら，HTMLへの変換エンジンとRollerをつなぐ部分だけをプラグインとして書いてやれば，既存のエントリはそのままに新しい記法を使うことができるようになります．ブログエントリの記法の他にも，コメントの記法，コメント認証などもプラグインとして独自に追加することができるようになっています．&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_インストール&quot;&gt;インストール&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;いわゆるオンプレミス環境へのインストール方法については，英語になりますが &lt;a href=&quot;https://cwiki.apache.org/confluence/display/ROLLER/Roller+Install+Topics&quot;&gt;Wiki&lt;/a&gt; および &lt;a href=&quot;https://dist.apache.org/repos/dist/release/roller/roller-5.1/v5.1.1/docs/roller-install-guide-5.1.pdf&quot;&gt;オフィシャルのインストレーションガイド&lt;/a&gt; を参照してください．また &lt;a href=&quot;https://www.openshift.com&quot;&gt;OpenShift&lt;/a&gt; で運用することもできます（無料枠でも可能）．詳細は，こちらも英語になりますが， &lt;a href=&quot;http://web-gmazza.rhcloud.com/blog/entry/apache-roller-on-openshift&quot;&gt;このブログエントリ&lt;/a&gt;を参照してください．&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_メンテナンスなど&quot;&gt;メンテナンスなど&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;まずバックアップですが，個人的にはPostgreSQLデータベースとRollerのデータファイル用ディレクトリをssh経由でバックアップするためのAntスクリプトを書いて，定期的にcronで実行しています．スクリプトは &lt;a href=&quot;https://github.com/lbtc-xxx/rollerbackup&quot;&gt;GitHub&lt;/a&gt;で公開しています．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;他のブログエンジンからのデータ移行については，残念ながら確立されたやり方はまだ存在していませんが，WordPressのブログエクスポート形式であるWXR形式のファイルを取り込むためのツールを作っています．詳細は &lt;a href=&quot;https://github.com/lbtc-xxx/wxr2roller&quot;&gt;こちら&lt;/a&gt;をご確認ください．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;また，SVNからのソース取得，ビルド，プラグインのインストール，自家製パッチ適用などを自動化するためのAntスクリプトを &lt;a href=&quot;https://github.com/lbtc-xxx/rollersetup&quot;&gt;GitHub&lt;/a&gt; に置いてあります．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;その他，運用ノウハウなどは &lt;a href=&quot;http://web-gmazza.rhcloud.com/blog/entry/apache-roller-blogging&quot;&gt;このブログエントリ&lt;/a&gt; によくまとまっています．&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_最後に&quot;&gt;最後に&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;日本語情報は少なめですが，最新リリースでは，実用上は日本語依存の問題というのは特にありません．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;ただ，日本語ブログで使うと表示上の違和感があるところがいくつかあったり，メッセージの誤訳や不足，モバイル用テーマ・一部の利用者が少ないDBでのみ生じる細かいバグが残っています（詳細は &lt;a href=&quot;https://issues.apache.org/jira/browse/ROL-2083?jql=project%20%3D%20ROL&quot;&gt;JIRA&lt;/a&gt; を参照）．SVN上の最新版では，そのうちのいくつかは修正ずみですので，可能な方はぜひ &lt;a href=&quot;https://cwiki.apache.org/confluence/display/ROLLER/Roller+Source+Code&quot;&gt;開発中の最新版のソース&lt;/a&gt; をSVNからチェックアウトしてビルドしてみてください．&lt;code&gt;mvn clean package&lt;/code&gt; でWARファイルが生成されます． &lt;a href=&quot;https://github.com/lbtc-xxx/rollersetup&quot;&gt;前述のAntスクリプト&lt;/a&gt; も併用されると便利かもしれません．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;バグレポート・パッチはもちろん大歓迎です．なにか日本語まわりで質問などあれば，このエントリにコメントをつけていただいても結構です．Javaエンジニアで，自分のブログを持ちたいとお考えの方，ぜひRollerを試してみてください！&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_リファレンスなど&quot;&gt;リファレンスなど&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://roller.apache.org&quot;&gt;オフィシャルサイト&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://rollerweblogger.org/project/&quot;&gt;オフィシャルブログ&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://cwiki.apache.org/confluence/display/ROLLER/Roller+Mailing+Lists&quot;&gt;メーリングリスト&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://twitter.com/apache_roller&quot;&gt;Twitterアカウント&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://www.packtpub.com/web-development/apache-roller-40-–-beginners-guide&quot;&gt;Apache Roller 4.0 – Beginner&amp;#8217;s Guide&lt;/a&gt;: Rollerの入門書&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://www.slideshare.net/snoopdave/whats-new-in-roller5&quot;&gt;Whats New In Roller5&lt;/a&gt;: 原作者Davidさんのスライド&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://www.slideshare.net/mraible/introduction-to-apache-roller-presentation&quot;&gt;Introduction to Apache Roller&lt;/a&gt;: コミッタMattさんのスライド&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/gmazza/tightblog&quot;&gt;Tightblog&lt;/a&gt;: 元コミッタGlenさんによるRollerのFork．GuiceからSpringへの移行，テーブル構造の見直し，大規模なリファクタリングなどが行われています&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_宣伝_求人のご案内&quot;&gt;宣伝：求人のご案内&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;現在，私の勤務先 &lt;a href=&quot;http://www.l-is-b.com/&quot;&gt;株式会社 L is B&lt;/a&gt; ではエンジニア・デザイナーを募集しています．主に &lt;a href=&quot;https://direct4b.com&quot;&gt;direct&lt;/a&gt; というインスタントメッセージングサービスの開発と運用を行っている会社です．&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://www.wantedly.com/projects/33511&quot;&gt;ソリューションエンジニア急募｜ビジネスメッセンジャーとシステムを繋ぐ新提案&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://www.wantedly.com/projects/15265&quot;&gt;デザイナー｜ビジネスメッセンジャーを彩る全てのデザインをお任せします&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://www.wantedly.com/projects/33458&quot;&gt;テストエンジニア｜ビジネスメッセンジャーの品質管理を担うリーダー&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://www.wantedly.com/projects/23582&quot;&gt;最高のビジネスインスタントメッセンジャーを作るサーバーサイドエンジニア募集&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://www.wantedly.com/companies/feelon&quot;&gt;What&amp;#8217;s new from 株式会社　L is B - Wantedly&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://www.l-is-b.com/ja/recruit.html&quot;&gt;L is B corporation - 採用情報 -&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;会社所在地は東京（+徳島県に開発拠点があります）ですが，一部リモートワークも認められています．少しでも興味を持たれた方，ぜひ応募してみてください！&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/adding-indexes-to-tables-of</id>
        <title type="html">Adding indexes to tables of Apache James 3</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/adding-indexes-to-tables-of"/>
        <published>2015-11-15T08:06:38+00:00</published>
        <updated>2015-11-25T23:17:31+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="james" scheme="http://roller.apache.org/ns/tags/" />
        <category term="postgresql" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;I&amp;#8217;m using Apache James (3.0-beta5-SNAPSHOT) as the mail server for my domain. It&amp;#8217;s running with JPA backend on PostgreSQL.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Today I&amp;#8217;ve found that some slow queries are logged as the number of emails has been grown through the days. The slowest two are following:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;SELECT t0.property_id, t0.property_line_number, t0.property_local_name, t0.property_name_space, t0.property_value FROM public.JAMES_MAIL_PROPERTY t0 WHERE t0.mailbox_id = $1 AND t0.mail_uid = $2 ORDER BY t0.property_line_number ASC&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;SELECT t0.userflag_id, t0.userflag_name FROM public.JAMES_MAIL_USERFLAG t0 WHERE t0.mailbox_id = $1 AND t0.mail_uid = $2 ORDER BY t0.userflag_id ASC&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;These queries are used sequential scan. It&amp;#8217;s terrible for thousands of rows so I&amp;#8217;ve created a couple of indexes to avoid sequential scan as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;create index on james_mail_property (mailbox_id, mail_uid);&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;create index on james_mail_userflag (mailbox_id, mail_uid);&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;They seems work expectedly as I&amp;#8217;ve confirmed that now these queries are using index scan instead.&lt;/p&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/notes-about-using-upsert-on</id>
        <title type="html">Notes about using UPSERT on RDBMS</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/notes-about-using-upsert-on"/>
        <published>2015-11-07T03:15:07+00:00</published>
        <updated>2015-11-13T22:27:02+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="mysql" scheme="http://roller.apache.org/ns/tags/" />
        <category term="postgresql" scheme="http://roller.apache.org/ns/tags/" />
        <category term="ses" scheme="http://roller.apache.org/ns/tags/" />
        <category term="sql" scheme="http://roller.apache.org/ns/tags/" />
        <category term="sqs" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Recently I&amp;#8217;ve investigated some ways to implement &lt;code&gt;UPSERT&lt;/code&gt; which gets the following job done without problems of race conditions:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;INSERT a row if there&amp;#8217;s no duplicate one with same ID&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;UPDATE a row otherwise&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Also another slightly differ requirement:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;INSERT a row if there&amp;#8217;s no duplicate one with same ID&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Do nothing otherwise&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Application needs to know whether the query has inserted a row because one is not exist&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The above two requirements are needed to implement an application that works with an Amazon SQS which is configured as the destination of Amazon SES notification.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_table_to_use_for_experimentation&quot;&gt;Table to use for experimentation&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;CREATE TABLE mytable (id INTEGER PRIMARY KEY, cnt INTEGER);&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_solution_for_mysql_5_6_x&quot;&gt;Solution for MySQL (5.6.x)&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;There&amp;#8217;s an easy solution that uses a MySQL specific clause &lt;code&gt;INSERT INTO &amp;#8230;&amp;#8203; ON DUPLICATE KEY UPDATE &amp;#8230;&amp;#8203;&lt;/code&gt;. For detail check &lt;a href=&quot;http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html&quot; class=&quot;bare&quot;&gt;http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;With the &lt;code&gt;mytable&lt;/code&gt;, I&amp;#8217;ve done some experimentation (on MySQL 5.6.27) as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;olist arabic&quot;&gt;
&lt;ol class=&quot;arabic&quot;&gt;
&lt;li&gt;
&lt;p&gt;Launch two instances of &lt;code&gt;mysql&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Execute &lt;code&gt;begin;&lt;/code&gt; on both so let a transaction begin for each instances&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Execute &lt;code&gt;INSERT INTO mytable (id, cnt) VALUES (1, 1) ON DUPLICATE KEY UPDATE cnt=cnt+1;&lt;/code&gt; on both. Note that the following execution will be blocked due to the preceding transaction is about to insert a row which has same ID&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Execute &lt;code&gt;commit;&lt;/code&gt; on the instance which executes the statement first&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Execute &lt;code&gt;commit;&lt;/code&gt; on the another instance which has been blocked&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Then execute &lt;code&gt;select * from mytable;&lt;/code&gt; you will see the desired result:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;+----+------+
| id | cnt  |
+----+------+
|  1 |    2 |
+----+------+
1 row in set (0.00 sec)&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;If you don&amp;#8217;t want to update any values if duplicated one already exists, Use following SQL instead:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;INSERT INTO mytable (id, cnt) VALUES (1, 1) ON DUPLICATE KEY UPDATE id=id;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Also note that if you&amp;#8217;re using JDBC to communicate with MySQL, You need to add &lt;code&gt;useAffectedRows=true&lt;/code&gt; parameter to the JDBC URL so that &lt;code&gt;executeUpdate()&lt;/code&gt; method will return the number of &lt;strong&gt;affected rows&lt;/strong&gt; instead of &lt;strong&gt;found rows&lt;/strong&gt;. For detail check &lt;a href=&quot;https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html&quot; class=&quot;bare&quot;&gt;https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_another_solution&quot;&gt;Another solution&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;I found an interesting attempt that seems to work with generic SQL:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;&lt;a href=&quot;http://www.xaprb.com/blog/2005/09/25/insert-if-not-exists-queries-in-mysql/&quot; class=&quot;bare&quot;&gt;http://www.xaprb.com/blog/2005/09/25/insert-if-not-exists-queries-in-mysql/&lt;/a&gt;
&lt;a href=&quot;http://stackoverflow.com/a/17067131/3591946&quot; class=&quot;bare&quot;&gt;http://stackoverflow.com/a/17067131/3591946&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;And I&amp;#8217;ve confirmed it works as I expected. I&amp;#8217;ve done the following experiment on MySQL 5.6.x:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;olist arabic&quot;&gt;
&lt;ol class=&quot;arabic&quot;&gt;
&lt;li&gt;
&lt;p&gt;Launch two instances of &lt;code&gt;mysql&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Execute &lt;code&gt;begin;&lt;/code&gt; on both so let a transaction begin for each instances&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Execute &lt;code&gt;INSERT INTO mytable (id, cnt) SELECT 1, 0 FROM (select 0 as i) mutex LEFT JOIN mytable ON id = 1 WHERE i = 0 AND id IS NULL;&lt;/code&gt;. Note that the following execution will be blocked as well&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Execute &lt;code&gt;UPDATE mytable SET cnt = cnt + 1 WHERE id = 1;&lt;/code&gt; on the instance which executes the statement first, if incrementation is needed&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Execute &lt;code&gt;commit;&lt;/code&gt; on the instance which executes the statement first&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Execute &lt;code&gt;UPDATE mytable SET cnt = cnt + 1 WHERE id = 1;&lt;/code&gt; on the instance which executes the statement second as well&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Execute &lt;code&gt;commit;&lt;/code&gt; on the another instance&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Note that I&amp;#8217;ve tried the experimentation for PostgreSQL 9.3.4 as well but doesn&amp;#8217;t work. It blocks the following query but produces &lt;code&gt;ERROR:  duplicate key value violates unique constraint &quot;mytable_pkey&quot;&lt;/code&gt; after issuing commit of the preceding transaction.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;I have no idea why it doesn&amp;#8217;t work for PostgreSQL (To be honest, I don&amp;#8217;t exactly know why it does work for MySQL). If you know why, Let me know via posting a comment to this entry that would be greatly appreciated.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;UPSERT functionality will be in the PostgreSQL 9.5 release (citation from &lt;a href=&quot;https://wiki.postgresql.org/wiki/SQL_MERGE&quot; class=&quot;bare&quot;&gt;https://wiki.postgresql.org/wiki/SQL_MERGE&lt;/a&gt;).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/excluding-particular-junit-test-cases</id>
        <title type="html">Excluding particular JUnit test cases that marked as slow in the time of execution</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/excluding-particular-junit-test-cases"/>
        <published>2015-11-01T06:43:16+00:00</published>
        <updated>2015-11-04T22:57:54+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="maven" scheme="http://roller.apache.org/ns/tags/" />
        <category term="test" scheme="http://roller.apache.org/ns/tags/" />
        <category term="unit" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Sometimes we need to create some slow test cases that involve some external resources such as databases, or external API servers. They are necessary to ensure that your application can integrate with such external resources while vast majority of test cases should stick with fast-running plain unit testing.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In such case, We usually wants to exclude such slow test cases from the ones that are frequently executed in local development environment so that we can get timely response from the tests. In this posting, I introduce you a solution that avoids maintenance of any hand-made listing of test cases.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_creating_a_suite_that_scans_and_runs_all_of_test_cases_exist_in_classpath&quot;&gt;Creating a suite that scans and runs all of test cases exist in classpath&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;First, assume we have a simple production class named &lt;code&gt;Hello&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public class Hello {
    public String greetings(String name) {
        return name != null ? &quot;hello, &quot; + name : &quot;hi, what&apos;s your name?&quot;;
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;We also have a couple of test cases against the preceding class:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public class HelloTest1 {
    @Test
    public void test() {
        System.out.println(&quot;Running &quot; + getClass().getSimpleName());
        Assert.assertEquals(&quot;hello, kyle&quot;, new Hello().greetings(&quot;kyle&quot;));
    }
}

public class HelloTest2 {
    @Test
    public void test() {
        System.out.println(&quot;Running &quot; + getClass().getSimpleName());
        Assert.assertEquals(&quot;hi, what&apos;s your name?&quot;, new Hello().greetings(null));
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Next, We&amp;#8217;d like to introduce a test suite that automatically includes the preceding two test cases. Put a following dependency to your &lt;code&gt;pom.xml&lt;/code&gt;:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;io.takari.junit&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;takari-cpsuite&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;1.2.7&amp;lt;/version&amp;gt;
    &amp;lt;scope&amp;gt;test&amp;lt;/scope&amp;gt;
&amp;lt;/dependency&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;And create a test suite that named &lt;code&gt;AllTests&lt;/code&gt; as follows. You can run this suite from your IDE or executing &lt;code&gt;mvn -Dtest=AllTests test&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@RunWith(ClasspathSuite.class)
public class AllTests {
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_involving_a_slow_test_case_and_exclude_it&quot;&gt;Involving a slow test case and exclude it&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;First, Create a marker interface which indicates that this test is slow:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public interface SlowTest {
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Next create a slow test case which annotated with &lt;code&gt;@Category(SlowTest.class)&lt;/code&gt; that we would like to avoid execute it frequently:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Category(SlowTest.class)
public class HelloSlowTest {
    @Test
    public void test() throws Exception {
        System.out.println(&quot;Running &quot; + getClass().getSimpleName());
        Thread.sleep(3000);
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Finally create a test suite that automatically excludes the test cases annotated as slow but executes rest of the test cases:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@RunWith(Categories.class)
@ExcludeCategory(SlowTest.class)
@SuiteClasses(AllTests.class)
public class AllExceptSlowTests {
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;You can run it on a daily basis instead of selecting root of your entire project and execute tests from your IDE or Maven without any hand maintenance of the listings of tests. For example, &lt;code&gt;mvn -Dtest=AllExceptSlowTests test&lt;/code&gt; produces following output in very short-term execution time:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;...
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Picked up _JAVA_OPTIONS: -Dfile.encoding=UTF-8
Running category.suite.AllExceptSlowTests
Running HelloTest1
Running HelloTest2
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.084 sec
...&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The complete resources can be obtained from &lt;a href=&quot;https://github.com/lbtc-xxx/junit-category&quot; class=&quot;bare&quot;&gt;https://github.com/lbtc-xxx/junit-category&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/swingirc-a-simple-irc-client</id>
        <title type="html">SwingIrc: A simple IRC client</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/swingirc-a-simple-irc-client"/>
        <published>2015-11-01T04:42:12+00:00</published>
        <updated>2015-11-01T04:42:13+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="irc" scheme="http://roller.apache.org/ns/tags/" />
        <category term="swing" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;About 6 years ago I&amp;#8217;ve made a simple IRC client that uses Swing. I&amp;#8217;ve digged source code of the app from my old PC by chance so I&amp;#8217;ve Mavenized it and put it to GitHub. To be hornest, it&amp;#8217;s a toy app but may someone like a student can refer it as an example of Java based GUI application.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/lbtc-xxx/swingirc&quot; class=&quot;bare&quot;&gt;https://github.com/lbtc-xxx/swingirc&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_how_to_launch&quot;&gt;How To Launch&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Refer &lt;a href=&quot;https://github.com/lbtc-xxx/swingirc&quot;&gt;README.md in the repository&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_how_to_use&quot;&gt;How To Use&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;olist arabic&quot;&gt;
&lt;ol class=&quot;arabic&quot;&gt;
&lt;li&gt;
&lt;p&gt;Put &lt;code&gt;name&lt;/code&gt;, &lt;code&gt;hostname&lt;/code&gt; and &lt;code&gt;port&lt;/code&gt; to the dialog and hit &lt;code&gt;connect&lt;/code&gt;&lt;/p&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/e3b99510-4351-4e7f-bcbb-3bea23ff5f75&quot; alt=&quot;e3b99510 4351 4e7f bcbb 3bea23ff5f75&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Click &lt;code&gt;File&lt;/code&gt; then select &lt;code&gt;Join&lt;/code&gt;&lt;/p&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/c3a05b27-567c-48b8-a098-602a9abb83bc&quot; alt=&quot;c3a05b27 567c 48b8 a098 602a9abb83bc&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Enter name of a channel to the dialog and hit &lt;code&gt;OK&lt;/code&gt;&lt;/p&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/a4eee820-b228-49c5-8714-b97d95154078&quot; alt=&quot;a4eee820 b228 49c5 8714 b97d95154078&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Chat with other users&lt;/p&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/1ac868a8-7c3d-49e8-98f4-f88d384573aa&quot; alt=&quot;1ac868a8 7c3d 49e8 98f4 f88d384573aa&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_future_plans&quot;&gt;Future plans&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Rewrite entire the app with JavaFX&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Implement more features&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Involve automated GUI testing&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/using-jpql-in-clause-with</id>
        <title type="html">Using JPQL IN clause with composite key</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/using-jpql-in-clause-with"/>
        <published>2015-10-25T11:16:44+00:00</published>
        <updated>2015-10-31T00:20:18+00:00</updated> 
        <category term="JPA" label="JPA" />
        <category term="eclipselink" scheme="http://roller.apache.org/ns/tags/" />
        <category term="hibernate" scheme="http://roller.apache.org/ns/tags/" />
        <category term="jpa" scheme="http://roller.apache.org/ns/tags/" />
        <category term="jpql" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Assume we have an entity named &lt;code&gt;Employee&lt;/code&gt;:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Entity
public class Employee implements Serializable {
    @Id
    @GeneratedValue
    private Long id;
    @Embedded
    private EmployeeName employeeName;

    // accessor omitted&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;And &lt;code&gt;EmployeeName&lt;/code&gt;:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Embeddable
public class EmployeeName implements Serializable {
    private String firstName;
    private String lastName;

    // accessor omitted&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Using preceding entity, We want to execute following JPQL:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;SELECT e FROM Employee e WHERE e.employeeName IN :employeeNames&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Will it work? It works for Hibernate 4.3.11.Final but unfortunately not for EclipseLink 2.6.1.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Hibernate generates following SQL for the JPQL and the parameter of a &lt;code&gt;List&lt;/code&gt; contains two elements:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;Hibernate: select employee0_.id as id1_0_, employee0_.firstName as firstNam2_0_, employee0_.lastName as lastName3_0_ from Employee employee0_ where employee0_.firstName=? and employee0_.lastName=? or employee0_.firstName=? and employee0_.lastName=?
[Employee{id=1, employeeName=EmployeeName{firstName=&apos;Scott&apos;, lastName=&apos;Vogel&apos;}}, Employee{id=2, employeeName=EmployeeName{firstName=&apos;Nick&apos;, lastName=&apos;Jett&apos;}}]&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;EclipseLink failed to generate correct SQL for the JPQL. In such case, you need to create a JPQL by hand or Criteria API that uses each column separately (&lt;code&gt;lastName&lt;/code&gt; and &lt;code&gt;firstName&lt;/code&gt;). EclipseLink produces following Exception:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;Exception in thread &quot;main&quot; javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.1.v20150916-55dc7c3): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLDataException: An attempt was made to get a data value of type &apos;BIGINT&apos; from a data value of type &apos;entity.EmployeeName&apos;.
Error Code: 20000
Call: SELECT ID, FIRSTNAME, LASTNAME FROM EMPLOYEE WHERE (ID IN (?,?))
	bind =&amp;gt; [EmployeeName{firstName=&apos;Scott&apos;, lastName=&apos;Vogel&apos;}, EmployeeName{firstName=&apos;Nick&apos;, lastName=&apos;Jett&apos;}]
Query: ReadAllQuery(referenceClass=Employee sql=&quot;SELECT ID, FIRSTNAME, LASTNAME FROM EMPLOYEE WHERE (ID IN ?)&quot;)
	at org.eclipse.persistence.internal.jpa.QueryImpl.getDetailedException(QueryImpl.java:382)
	at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:260)
	at org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:473)
	at main.Main.main(Main.java:45)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:497)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.1.v20150916-55dc7c3): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLDataException: An attempt was made to get a data value of type &apos;BIGINT&apos; from a data value of type &apos;entity.EmployeeName&apos;.
Error Code: 20000
Call: SELECT ID, FIRSTNAME, LASTNAME FROM EMPLOYEE WHERE (ID IN (?,?))
	bind =&amp;gt; [EmployeeName{firstName=&apos;Scott&apos;, lastName=&apos;Vogel&apos;}, EmployeeName{firstName=&apos;Nick&apos;, lastName=&apos;Jett&apos;}]
Query: ReadAllQuery(referenceClass=Employee sql=&quot;SELECT ID, FIRSTNAME, LASTNAME FROM EMPLOYEE WHERE (ID IN ?)&quot;)
	at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:340)
	at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:684)
	at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:560)
	at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:2055)
	at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:570)
	at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:258)
	at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:242)
	at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
	at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeSelectCall(DatasourceCallQueryMechanism.java:299)
	at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.selectAllRows(DatasourceCallQueryMechanism.java:694)
	at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRowsFromTable(ExpressionQueryMechanism.java:2740)
	at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRows(ExpressionQueryMechanism.java:2693)
	at org.eclipse.persistence.queries.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:559)
	at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1175)
	at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:904)
	at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1134)
	at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:460)
	at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1222)
	at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2896)
	at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1857)
	at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1839)
	at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1804)
	at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:258)
	... 7 more&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Complete source code that has been used in the test can be obtained from &lt;a href=&quot;https://github.com/lbtc-xxx/jpa-composite-in&quot; class=&quot;bare&quot;&gt;https://github.com/lbtc-xxx/jpa-composite-in&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/how-to-bind-lookup-a</id>
        <title type="html">How to bind / lookup DataSource via JNDI without container</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/how-to-bind-lookup-a"/>
        <published>2015-10-25T01:58:28+00:00</published>
        <updated>2015-10-25T03:22:28+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="derby" scheme="http://roller.apache.org/ns/tags/" />
        <category term="eclipselink" scheme="http://roller.apache.org/ns/tags/" />
        <category term="jdbc" scheme="http://roller.apache.org/ns/tags/" />
        <category term="jndi" scheme="http://roller.apache.org/ns/tags/" />
        <category term="jpa" scheme="http://roller.apache.org/ns/tags/" />
        <category term="test" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;While I prefer deploying JPA based apps to a Java EE container and test it via Arquillian as integration testing, some occasions won&amp;#8217;t allow it and need arises that using a Servlet container or Java SE environment.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;To supply information that required to connect the database (e.g. JDBC URL or credentials), it&amp;#8217;s preferable to use JNDI rather than using &lt;code&gt;DriverManager&lt;/code&gt; or &lt;code&gt;javax.persistence.jdbc.*&lt;/code&gt; properties in &lt;code&gt;persistence.xml&lt;/code&gt; because using JNDI eliminates the need of managing such information in the application codebase, also it enables to use the container managed connection pool which is more flexible and scalable over another.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In such case, hard-coded JNDI name of a DataSource may be a problem in the time of testing because JNDI lookup doesn&amp;#8217;t work without container as is. So we may need some considering of involve pluggable mechanism of acquiring &lt;code&gt;java.sql.Connection&lt;/code&gt; instance or creating &lt;code&gt;persistence.xml&lt;/code&gt; for unit testing.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;These solutions are not much difficult to implement, but it&amp;#8217;s preferable if JNDI lookup does work without container as well because it will decrease amount of testing specific code. In this posting, I&amp;#8217;ll give you a complete example of looking up a DataSource without container using bare &lt;code&gt;InitialContext&lt;/code&gt; and the &lt;code&gt;non-jta-datasource&lt;/code&gt; persistence descriptor definition.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_environment&quot;&gt;Environment&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;tomcat-catalina&lt;/code&gt; artifact of Apache Tomcat 8.0.28: Enables binding a resource to JNDI context in Java SE environment&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Apache Commons DBCP 1.4: Supplies &lt;code&gt;BasicDataSource&lt;/code&gt; class so make the example in database independent manner&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Apache Derby 10.12.1.1&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;EclipseLink 2.6.1&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Oracle JDK8u60&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_dependencies&quot;&gt;Dependencies&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;dependencies&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.eclipse.persistence&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;eclipselink&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;2.6.1&amp;lt;/version&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;commons-dbcp&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;commons-dbcp&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;1.4&amp;lt;/version&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.apache.derby&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;derby&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;10.12.1.1&amp;lt;/version&amp;gt;
        &amp;lt;scope&amp;gt;runtime&amp;lt;/scope&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.apache.tomcat&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;tomcat-catalina&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;8.0.28&amp;lt;/version&amp;gt;
        &amp;lt;scope&amp;gt;runtime&amp;lt;/scope&amp;gt;
    &amp;lt;/dependency&amp;gt;
&amp;lt;/dependencies&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_persistence_xml&quot;&gt;persistence.xml&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Note that the &lt;code&gt;non-jta-data-source&lt;/code&gt; is used with JNDI name of DataSource.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&amp;gt;
&amp;lt;persistence version=&quot;2.1&quot; xmlns=&quot;http://xmlns.jcp.org/xml/ns/persistence&quot;
             xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
             xsi:schemaLocation=&quot;http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd&quot;&amp;gt;
    &amp;lt;persistence-unit name=&quot;myPU&quot; transaction-type=&quot;RESOURCE_LOCAL&quot;&amp;gt;
        &amp;lt;provider&amp;gt;org.eclipse.persistence.jpa.PersistenceProvider&amp;lt;/provider&amp;gt;
        &amp;lt;non-jta-data-source&amp;gt;java:comp/env/jdbc/database&amp;lt;/non-jta-data-source&amp;gt;
        &amp;lt;class&amp;gt;entity.Employee&amp;lt;/class&amp;gt;
        &amp;lt;shared-cache-mode&amp;gt;NONE&amp;lt;/shared-cache-mode&amp;gt;
        &amp;lt;properties&amp;gt;
            &amp;lt;property name=&quot;javax.persistence.schema-generation.database.action&quot; value=&quot;create&quot;/&amp;gt;
            &amp;lt;property name=&quot;eclipselink.logging.level&quot; value=&quot;FINE&quot;/&amp;gt;
            &amp;lt;property name=&quot;eclipselink.logging.parameters&quot; value=&quot;true&quot;/&amp;gt;
        &amp;lt;/properties&amp;gt;
    &amp;lt;/persistence-unit&amp;gt;
&amp;lt;/persistence&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_employee_java&quot;&gt;Employee.java&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This is a simple JPA entity class that will be used in testing.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Entity
public class Employee implements Serializable {
    @Id
    private Long id;
    private String firstName;
    private String lastName;

    // accessors omitted&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_main_java&quot;&gt;Main.java&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This binds a DataSource of Embedded in-memory Apache Derby database to &lt;code&gt;java:comp/env/jdbc/database&lt;/code&gt;, then lookup it via &lt;code&gt;InitialContext&lt;/code&gt; and &lt;code&gt;EntityManagerFactory&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public class Main {
    private static final String JNDI = &quot;java:comp/env/jdbc/database&quot;;

    public static void main(String[] args) throws Exception {
        bind();
        lookup();
        final EntityManagerFactory emf = Persistence.createEntityManagerFactory(&quot;myPU&quot;);
        populate(emf);
        query(emf);
    }

    private static void bind() throws NamingException {
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, &quot;org.apache.naming.java.javaURLContextFactory&quot;);
        System.setProperty(Context.URL_PKG_PREFIXES, &quot;org.apache.naming&quot;);

        final BasicDataSource ds = new BasicDataSource();
        ds.setUrl(&quot;jdbc:derby:memory:myDB;create=true&quot;);

        final Context context = new InitialContext();
        try {
            context.createSubcontext(&quot;java:&quot;);
            context.createSubcontext(&quot;java:comp&quot;);
            context.createSubcontext(&quot;java:comp/env&quot;);
            context.createSubcontext(&quot;java:comp/env/jdbc&quot;);
            context.bind(JNDI, ds);
        } finally {
            context.close();
        }
    }

    private static void lookup() throws NamingException, SQLException {
        final Context context = new InitialContext();
        try {
            final DataSource ds = (DataSource) context.lookup(JNDI);
            try (final Connection cn = ds.getConnection();
                 final Statement st = cn.createStatement();
                 final ResultSet rs = st.executeQuery(&quot;SELECT CURRENT_TIMESTAMP FROM SYSIBM.SYSDUMMY1&quot;)) {
                while (rs.next()) {
                    System.out.println(rs.getTimestamp(1));
                }
            }
        } finally {
            context.close();
        }
    }

    private static void populate(final EntityManagerFactory emf) {
        final EntityManager em = emf.createEntityManager();
        try {
            final EntityTransaction tx = em.getTransaction();
            tx.begin();
            final Employee emp = new Employee();
            emp.setId(1l);
            emp.setFirstName(&quot;Jane&quot;);
            emp.setLastName(&quot;Doe&quot;);
            em.persist(emp);
            tx.commit();
        } finally {
            em.close();
        }
    }

    private static void query(final EntityManagerFactory emf) {
        final EntityManager em = emf.createEntityManager();
        try {
            System.out.println(em.find(Employee.class, 1l));
        } finally {
            em.close();
        }
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_log&quot;&gt;Log&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;You can see the &lt;code&gt;lookup()&lt;/code&gt; method dumped &lt;code&gt;CURRENT_TIMESTAMP&lt;/code&gt; and EclipseLink successfully acquired a DataSource as follows.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;2015-10-25 10:33:24.235
[EL Fine]: server: 2015-10-25 10:33:24.478--Thread(Thread[main,5,main])--Configured server platform: org.eclipse.persistence.platform.server.NoServerPlatform
[EL Config]: metadata: 2015-10-25 10:33:24.633--ServerSession(1323434987)--Thread(Thread[main,5,main])--The access type for the persistent class [class entity.Employee] is set to [FIELD].
[EL Config]: metadata: 2015-10-25 10:33:24.654--ServerSession(1323434987)--Thread(Thread[main,5,main])--The alias name for the entity class [class entity.Employee] is being defaulted to: Employee.
[EL Config]: metadata: 2015-10-25 10:33:24.656--ServerSession(1323434987)--Thread(Thread[main,5,main])--The table name for entity [class entity.Employee] is being defaulted to: EMPLOYEE.
[EL Config]: metadata: 2015-10-25 10:33:24.666--ServerSession(1323434987)--Thread(Thread[main,5,main])--The column name for element [firstName] is being defaulted to: FIRSTNAME.
[EL Config]: metadata: 2015-10-25 10:33:24.668--ServerSession(1323434987)--Thread(Thread[main,5,main])--The column name for element [lastName] is being defaulted to: LASTNAME.
[EL Config]: metadata: 2015-10-25 10:33:24.668--ServerSession(1323434987)--Thread(Thread[main,5,main])--The column name for element [id] is being defaulted to: ID.
[EL Info]: 2015-10-25 10:33:24.7--ServerSession(1323434987)--Thread(Thread[main,5,main])--EclipseLink, version: Eclipse Persistence Services - 2.6.1.v20150916-55dc7c3
[EL Fine]: connection: 2015-10-25 10:33:24.706--Thread(Thread[main,5,main])--Detected database platform: org.eclipse.persistence.platform.database.JavaDBPlatform
[EL Config]: connection: 2015-10-25 10:33:24.714--ServerSession(1323434987)--Connection(1872973138)--Thread(Thread[main,5,main])--connecting(DatabaseLogin(
	platform=&amp;gt;JavaDBPlatform
	user name=&amp;gt; &quot;&quot;
	connector=&amp;gt;JNDIConnector datasource name=&amp;gt;java:comp/env/jdbc/database
))
[EL Config]: connection: 2015-10-25 10:33:24.715--ServerSession(1323434987)--Connection(1465346452)--Thread(Thread[main,5,main])--Connected: jdbc:derby:memory:myDB
	User: APP
	Database: Apache Derby  Version: 10.12.1.1 - (1704137)
	Driver: Apache Derby Embedded JDBC Driver  Version: 10.12.1.1 - (1704137)
[EL Config]: connection: 2015-10-25 10:33:24.715--ServerSession(1323434987)--Connection(1634387050)--Thread(Thread[main,5,main])--connecting(DatabaseLogin(
	platform=&amp;gt;JavaDBPlatform
	user name=&amp;gt; &quot;&quot;
	connector=&amp;gt;JNDIConnector datasource name=&amp;gt;java:comp/env/jdbc/database
))
[EL Config]: connection: 2015-10-25 10:33:24.716--ServerSession(1323434987)--Connection(1740223770)--Thread(Thread[main,5,main])--Connected: jdbc:derby:memory:myDB
	User: APP
	Database: Apache Derby  Version: 10.12.1.1 - (1704137)
	Driver: Apache Derby Embedded JDBC Driver  Version: 10.12.1.1 - (1704137)
[EL Info]: connection: 2015-10-25 10:33:24.747--ServerSession(1323434987)--Thread(Thread[main,5,main])--/file:/Users/kyle/src/jndi-se/target/classes/_myPU login successful
[EL Fine]: sql: 2015-10-25 10:33:24.784--ServerSession(1323434987)--Connection(762809053)--Thread(Thread[main,5,main])--CREATE TABLE EMPLOYEE (ID BIGINT NOT NULL, FIRSTNAME VARCHAR(255), LASTNAME VARCHAR(255), PRIMARY KEY (ID))
[EL Fine]: sql: 2015-10-25 10:33:24.85--ClientSession(1027495011)--Connection(1688470144)--Thread(Thread[main,5,main])--INSERT INTO EMPLOYEE (ID, FIRSTNAME, LASTNAME) VALUES (?, ?, ?)
	bind =&amp;gt; [1, Jane, Doe]
[EL Fine]: sql: 2015-10-25 10:33:24.877--ServerSession(1323434987)--Connection(640808588)--Thread(Thread[main,5,main])--SELECT ID, FIRSTNAME, LASTNAME FROM EMPLOYEE WHERE (ID = ?)
	bind =&amp;gt; [1]
Employee{id=1, firstName=&apos;Jane&apos;, lastName=&apos;Doe&apos;}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The complete source code can be obtained from &lt;a href=&quot;https://github.com/lbtc-xxx/jndi-se&quot;&gt;my GitHub repository&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_references&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://blogs.oracle.com/randystuph/entry/injecting_jndi_datasources_for_junit&quot; class=&quot;bare&quot;&gt;https://blogs.oracle.com/randystuph/entry/injecting_jndi_datasources_for_junit&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://stackoverflow.com/questions/14961815/cannot-instantiate-class-org-apache-naming-java-javaurlcontextfactory&quot; class=&quot;bare&quot;&gt;http://stackoverflow.com/questions/14961815/cannot-instantiate-class-org-apache-naming-java-javaurlcontextfactory&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/working-example-of-eclipselink-static</id>
        <title type="html">Working example of EclipseLink static weaving</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/working-example-of-eclipselink-static"/>
        <published>2015-10-23T18:37:42+00:00</published>
        <updated>2016-01-24T07:13:50+00:00</updated> 
        <category term="JPA" label="JPA" />
        <category term="derby" scheme="http://roller.apache.org/ns/tags/" />
        <category term="eclipselink" scheme="http://roller.apache.org/ns/tags/" />
        <category term="jpa" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;These days I&amp;#8217;m using EclipseLink at work. It runs on Servlet containers, unfortunately not Java EE containers at there so I have experienced some difference between them. A significant one is class weaving. The dynamic weaving is enabled by default in Java EE containers but not for Java SE environment. Weaving is a prerequisite of using some important functions such as Lazy Loading but it doesn&amp;#8217;t work for default Java SE environment. In Java SE environment, EclipseLink requires a special prerequisite that set an agent in the time of launching JVM, or use static weaving to enable Lazy Loading.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Static weaving offers some performance benefit over Dynamic weaving because it doesn&amp;#8217;t require runtime weaving step. I think it&amp;#8217;s preferable so I tried it over another.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_environment&quot;&gt;Environment&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;EclipseLink 2.6.1&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Apache Derby 10.12.1.1&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Oracle JDK8u60&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_projects&quot;&gt;Projects&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_eclipselink_entity&quot;&gt;eclipselink-entity&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This project contains three simple entity classes. &lt;code&gt;Dept&lt;/code&gt; has many &lt;code&gt;Employee&lt;/code&gt;, and &lt;code&gt;Employee&lt;/code&gt; has one &lt;code&gt;Phone&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect3&quot;&gt;
&lt;h4 id=&quot;_dept&quot;&gt;Dept&lt;/h4&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Entity
public class Dept implements Serializable {
    @Id
    private Long id;
    private String deptName;
    @OneToMany(mappedBy = &quot;dept&quot;)
    private List&amp;lt;Employee&amp;gt; employees;

    // accessors omitted&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect3&quot;&gt;
&lt;h4 id=&quot;_employee&quot;&gt;Employee&lt;/h4&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Entity
public class Employee implements Serializable {
    @Id
    private Long id;
    @ManyToOne(fetch = FetchType.EAGER) // default
    @JoinColumn(nullable = false)
    private Dept dept;
    private String firstName;
    private String lastName;
    @OneToOne(mappedBy = &quot;employee&quot;, fetch = FetchType.LAZY) // overridden by LAZY
    private Phone phone;

    // accessors omitted&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Note that the relation &lt;code&gt;Employee.dept&lt;/code&gt; is set to &lt;code&gt;EAGER&lt;/code&gt;, and &lt;code&gt;Employee.phone&lt;/code&gt; is set to &lt;code&gt;LAZY&lt;/code&gt; as FetchType.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect3&quot;&gt;
&lt;h4 id=&quot;_phone&quot;&gt;Phone&lt;/h4&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Entity
public class Phone implements Serializable {
    @Id
    @OneToOne
    @JoinColumn(nullable = false)
    private Employee employee;
    private String phoneNumber;

    // accessors omitted&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect3&quot;&gt;
&lt;h4 id=&quot;_persistence_xml&quot;&gt;persistence.xml&lt;/h4&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The persistence descriptor requires a property called &lt;code&gt;eclipselink.weaving&lt;/code&gt; with the value &lt;code&gt;static&lt;/code&gt; to enable static weaving.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&amp;gt;
&amp;lt;persistence version=&quot;2.1&quot; xmlns=&quot;http://xmlns.jcp.org/xml/ns/persistence&quot;
             xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
             xsi:schemaLocation=&quot;http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd&quot;&amp;gt;
    &amp;lt;persistence-unit name=&quot;myPU&quot; transaction-type=&quot;RESOURCE_LOCAL&quot;&amp;gt;
        &amp;lt;provider&amp;gt;org.eclipse.persistence.jpa.PersistenceProvider&amp;lt;/provider&amp;gt;
        &amp;lt;exclude-unlisted-classes&amp;gt;false&amp;lt;/exclude-unlisted-classes&amp;gt;
        &amp;lt;shared-cache-mode&amp;gt;NONE&amp;lt;/shared-cache-mode&amp;gt;
        &amp;lt;properties&amp;gt;
            &amp;lt;property name=&quot;javax.persistence.jdbc.driver&quot; value=&quot;org.apache.derby.jdbc.EmbeddedDriver&quot;/&amp;gt;
            &amp;lt;property name=&quot;javax.persistence.jdbc.url&quot; value=&quot;jdbc:derby:memory:myDB;create=true&quot;/&amp;gt;
            &amp;lt;property name=&quot;javax.persistence.jdbc.user&quot; value=&quot;app&quot;/&amp;gt;
            &amp;lt;property name=&quot;javax.persistence.jdbc.password&quot; value=&quot;app&quot;/&amp;gt;
            &amp;lt;property name=&quot;javax.persistence.schema-generation.database.action&quot; value=&quot;drop-and-create&quot;/&amp;gt;
            &amp;lt;property name=&quot;eclipselink.weaving&quot; value=&quot;static&quot;/&amp;gt;
            &amp;lt;property name=&quot;eclipselink.logging.level&quot; value=&quot;FINE&quot;/&amp;gt;
            &amp;lt;property name=&quot;eclipselink.logging.parameters&quot; value=&quot;true&quot;/&amp;gt;
        &amp;lt;/properties&amp;gt;
    &amp;lt;/persistence-unit&amp;gt;
&amp;lt;/persistence&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect3&quot;&gt;
&lt;h4 id=&quot;_pom_xml&quot;&gt;pom.xml&lt;/h4&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The static weaving will be done by a convenient Maven plugin. Just put following &lt;code&gt;plugin&lt;/code&gt; definition in your &lt;code&gt;pom.xml&lt;/code&gt; and execute &lt;code&gt;mvn clean install&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;build&amp;gt;
    &amp;lt;plugins&amp;gt;
        &amp;lt;plugin&amp;gt;
            &amp;lt;groupId&amp;gt;de.empulse.eclipselink&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;staticweave-maven-plugin&amp;lt;/artifactId&amp;gt;
            &amp;lt;version&amp;gt;1.0.0&amp;lt;/version&amp;gt;
            &amp;lt;executions&amp;gt;
                &amp;lt;execution&amp;gt;
                    &amp;lt;phase&amp;gt;process-classes&amp;lt;/phase&amp;gt;
                    &amp;lt;goals&amp;gt;
                        &amp;lt;goal&amp;gt;weave&amp;lt;/goal&amp;gt;
                    &amp;lt;/goals&amp;gt;
                    &amp;lt;configuration&amp;gt;
                        &amp;lt;persistenceXMLLocation&amp;gt;META-INF/persistence.xml&amp;lt;/persistenceXMLLocation&amp;gt;
                        &amp;lt;logLevel&amp;gt;FINE&amp;lt;/logLevel&amp;gt;
                    &amp;lt;/configuration&amp;gt;
                &amp;lt;/execution&amp;gt;
            &amp;lt;/executions&amp;gt;
            &amp;lt;dependencies&amp;gt;
                &amp;lt;dependency&amp;gt;
                    &amp;lt;groupId&amp;gt;org.eclipse.persistence&amp;lt;/groupId&amp;gt;
                    &amp;lt;artifactId&amp;gt;org.eclipse.persistence.jpa&amp;lt;/artifactId&amp;gt;
                    &amp;lt;version&amp;gt;${eclipselink.version}&amp;lt;/version&amp;gt;
                &amp;lt;/dependency&amp;gt;
            &amp;lt;/dependencies&amp;gt;
        &amp;lt;/plugin&amp;gt;
    &amp;lt;/plugins&amp;gt;
&amp;lt;/build&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_eclipselink_example&quot;&gt;eclipselink-example&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This project is a client of the preceding &lt;code&gt;eclipselink-entity&lt;/code&gt; project. It has a &lt;code&gt;Main&lt;/code&gt; class which simply populates some records then fetches them.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public class Main {
    public static void main(String[] args) {
        EntityManagerFactory emf = null;
        try {
            emf = Persistence.createEntityManagerFactory(&quot;myPU&quot;);
            EntityManager em = null;

            // Populating data
            try {
                em = emf.createEntityManager();
                final EntityTransaction tx = em.getTransaction();
                tx.begin();

                Dept dept = new Dept();
                dept.setId(1l);
                dept.setDeptName(&quot;Engineering&quot;);
                dept.setEmployees(new ArrayList&amp;lt;&amp;gt;());
                em.persist(dept);

                Employee emp = new Employee();
                emp.setId(1l);
                emp.setFirstName(&quot;Jane&quot;);
                emp.setLastName(&quot;Doe&quot;);
                dept.getEmployees().add(emp);
                emp.setDept(dept);
                em.persist(emp);

                Phone phone = new Phone();
                phone.setPhoneNumber(&quot;000-1111-2222&quot;);
                phone.setEmployee(emp);
                emp.setPhone(phone);
                em.persist(phone);

                tx.commit();
            } finally { if (em != null) { em.close(); } }

            System.out.println(&quot;&amp;lt;&amp;lt;&amp;lt; Populating done &amp;gt;&amp;gt;&amp;gt;&quot;);

            try {
                em = emf.createEntityManager();
                final Employee emp = em.find(Employee.class, 1l);

                System.out.println(emp.getFirstName() + &quot; &quot; + emp.getLastName());

                // EAGER
                System.out.println(emp.getDept().getDeptName());
                // LAZY
                System.out.println(emp.getPhone().getPhoneNumber());
            } finally { if (em != null) { em.close(); } }
        } finally { if (emf != null) { emf.close(); } }
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Here you can see the &lt;code&gt;Phone&lt;/code&gt; entity has lazily fetched while &lt;code&gt;Dept&lt;/code&gt; entity was eagerly fetched:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;&amp;lt;&amp;lt; Populating done &amp;gt;&amp;gt;&amp;gt;
[EL Fine]: sql: 2015-10-24 03:18:23.389--ServerSession(1216590855)--Connection(1488298739)--Thread(Thread[main,5,main])--SELECT ID, FIRSTNAME, LASTNAME, DEPT_ID FROM EMPLOYEE WHERE (ID = ?)
	bind =&amp;gt; [1]
[EL Fine]: sql: 2015-10-24 03:18:23.408--ServerSession(1216590855)--Connection(1488298739)--Thread(Thread[main,5,main])--SELECT ID, DEPTNAME FROM DEPT WHERE (ID = ?)
	bind =&amp;gt; [1]
Jane Doe
Engineering
[EL Fine]: sql: 2015-10-24 03:18:23.413--ServerSession(1216590855)--Connection(1488298739)--Thread(Thread[main,5,main])--SELECT PHONENUMBER, EMPLOYEE_ID FROM PHONE WHERE (EMPLOYEE_ID = ?)
	bind =&amp;gt; [1]
000-1111-2222&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This example uses in-memory Apache Derby so you don&amp;#8217;t need to set up any databases to execute this example. complete projects can be obtained from following GitHub repositories:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/lbtc-xxx/eclipselink-entity&quot; class=&quot;bare&quot;&gt;https://github.com/lbtc-xxx/eclipselink-entity&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/lbtc-xxx/eclipselink-example&quot; class=&quot;bare&quot;&gt;https://github.com/lbtc-xxx/eclipselink-example&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Also here&amp;#8217;s &lt;code&gt;build.gradle&lt;/code&gt; example: &lt;a href=&quot;https://github.com/lbtc-xxx/eclipselink-entity/blob/master/build.gradle&quot; class=&quot;bare&quot;&gt;https://github.com/lbtc-xxx/eclipselink-entity/blob/master/build.gradle&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_references&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://www.eclipse.org/eclipselink/documentation/2.4/concepts/app_dev007.htm&quot; class=&quot;bare&quot;&gt;http://www.eclipse.org/eclipselink/documentation/2.4/concepts/app_dev007.htm&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Advanced_JPA_Development/Performance/Weaving/Static_Weaving&quot; class=&quot;bare&quot;&gt;https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Advanced_JPA_Development/Performance/Weaving/Static_Weaving&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/using-dbunit-from-ant</id>
        <title type="html">Using DBUnit from Ant</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/using-dbunit-from-ant"/>
        <published>2015-09-23T03:02:44+00:00</published>
        <updated>2016-04-03T04:48:48+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="ant" scheme="http://roller.apache.org/ns/tags/" />
        <category term="dbunit" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;It&amp;#8217;s a common usecase that using DBUnit from JUnit testcases but sometimes I need to use DBUnit in a standalone application manner to achive tasks such as exporting the data from a database to a XML file for creating test data from an existing table. In such case, I feel using DBUnit Ant task is better rather than launching it from Maven plugin or write a standalone Java application uses DBUnit API. in this entry, I introduce you a complete working example of an Ant script that uses DBUnit Ant task.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_environment&quot;&gt;Environment&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;dbunit-2.5.1.jar (Not available on the download page on SourceForge. &lt;a href=&quot;http://mvnrepository.com/artifact/org.dbunit/dbunit/2.5.1&quot;&gt;Obtain it from Maven Repository instead&lt;/a&gt;)&lt;/p&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;With dependencies: &lt;a href=&quot;http://mvnrepository.com/artifact/org.slf4j/slf4j-api&quot;&gt;slf4j-api-1.7.12.jar&lt;/a&gt;, &lt;a href=&quot;http://mvnrepository.com/artifact/org.slf4j/slf4j-jdk14&quot;&gt;slf4j-jdk14-1.7.12.jar&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;postgresql-9.4-1203.jdbc42.jar&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Apache Ant&amp;#8482; version 1.9.6&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;PostgreSQL 9.3.5&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Oracle JDK8u40&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Complete JAR file list in my &lt;code&gt;~/.ant/lib&lt;/code&gt;:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;$ ls -l ~/.ant/lib
total 1236
-rw-rw-r--. 1 kyle kyle 560755 Sep 23 10:56 dbunit-2.5.1.jar
-rw-rw-r--. 1 kyle kyle 660126 Sep 23 10:54 postgresql-9.4-1203.jdbc42.jar
-rw-rw-r--. 1 kyle kyle  32127 Sep 23 11:15 slf4j-api-1.7.12.jar
-rw-rw-r--. 1 kyle kyle   7892 Sep 23 11:16 slf4j-jdk14-1.7.12.jar
$&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_exporting_example&quot;&gt;Exporting example&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_build_xml&quot;&gt;build.xml&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This script exports the result of a SQL to a flat XML file. The format can be specified in &lt;code&gt;dbunit.format&lt;/code&gt; property that has set to &lt;code&gt;flat&lt;/code&gt; as default. You can add additional &lt;code&gt;query&lt;/code&gt; or &lt;code&gt;table&lt;/code&gt; elements inside the &lt;code&gt;dbunit&lt;/code&gt; element to include multiple dataset in single XML file. JDBC connection information such as credentials or URL is expected to be stored as a separate file named &lt;code&gt;dbunit.properties&lt;/code&gt; that is placed under the same directory to this file.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;project name=&quot;dbunit-export&quot; basedir=&quot;.&quot;&amp;gt;
    &amp;lt;taskdef name=&quot;dbunit&quot; classname=&quot;org.dbunit.ant.DbUnitTask&quot;/&amp;gt;

    &amp;lt;loadproperties srcFile=&quot;dbunit.properties&quot;/&amp;gt;

    &amp;lt;fail unless=&quot;dbunit.driver&quot;/&amp;gt;
    &amp;lt;fail unless=&quot;dbunit.url&quot;/&amp;gt;
    &amp;lt;fail unless=&quot;dbunit.userid&quot;/&amp;gt;
    &amp;lt;fail unless=&quot;dbunit.password&quot;/&amp;gt;
    &amp;lt;fail unless=&quot;dbunit.datatypeFactory&quot;/&amp;gt;

    &amp;lt;property name=&quot;dbunit.format&quot; value=&quot;flat&quot;/&amp;gt; &amp;lt;!-- Possible values are &quot;flat&quot;, &quot;xml&quot;, &quot;csv&quot;, &quot;dtd&quot;, &quot;xls&quot;. Defaults to &quot;flat&quot; --&amp;gt;

    &amp;lt;target name=&quot;export&quot;&amp;gt;
        &amp;lt;fail unless=&quot;dbunit.sql&quot;/&amp;gt;
        &amp;lt;fail unless=&quot;dbunit.dest&quot;/&amp;gt;
        &amp;lt;fail unless=&quot;dbunit.format&quot;/&amp;gt;
        &amp;lt;fail unless=&quot;dbunit.query&quot;/&amp;gt;

        &amp;lt;dbunit driver=&quot;${dbunit.driver}&quot; url=&quot;${dbunit.url}&quot; userid=&quot;${dbunit.userid}&quot; password=&quot;${dbunit.password}&quot;&amp;gt;
            &amp;lt;dbconfig&amp;gt;
                &amp;lt;property name=&quot;datatypeFactory&quot; value=&quot;${dbunit.datatypeFactory}&quot; /&amp;gt;
            &amp;lt;/dbconfig&amp;gt;
            &amp;lt;export dest=&quot;${dbunit.dest}&quot;&amp;gt;
                &amp;lt;query name=&quot;${dbunit.query}&quot; sql=&quot;${dbunit.sql}&quot;/&amp;gt;
            &amp;lt;/export&amp;gt;
        &amp;lt;/dbunit&amp;gt;
    &amp;lt;/target&amp;gt;
&amp;lt;/project&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_dbunit_properties&quot;&gt;dbunit.properties&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Set each properties to suit your environment. &lt;a href=&quot;http://dbunit.sourceforge.net/apidocs/org/dbunit/dataset/datatype/DefaultDataTypeFactory.html&quot;&gt;See this page&lt;/a&gt; to check what datatypeFactory are available.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;dbunit.driver=org.postgresql.Driver
dbunit.url=jdbc:postgresql://localhost:5432/mydb
dbunit.userid=someone
dbunit.password=somepass
dbunit.datatypeFactory=org.dbunit.ext.postgresql.PostgresqlDataTypeFactory&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_how_to_run&quot;&gt;How to run&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The following command exports a XML file from a SQL.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;$ ant export &quot;-Ddbunit.sql=select * from job_instance where jobinstanceid &amp;gt;= 399341 order by jobinstanceid&quot; -Ddbunit.query=job_instance -Ddbunit.dest=job_instance.xml
Buildfile: /home/kyle/dbunit-ant-example/build.xml

export:
   [dbunit] Executing export:
   [dbunit]       in format: flat to datafile: /home/kyle/dbunit-ant-example/job_instance.xml
Successfully wrote file &apos;/home/kyle/dbunit-ant-example/job_instance.xml&apos;

BUILD SUCCESSFUL
Total time: 0 seconds&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This produces a flat XML dataset named &lt;code&gt;job_instance.xml&lt;/code&gt; something like:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;?xml version=&apos;1.0&apos; encoding=&apos;UTF-8&apos;?&amp;gt;
&amp;lt;dataset&amp;gt;
  &amp;lt;job_instance jobinstanceid=&quot;399341&quot; jobname=&quot;somejob1&quot; applicationname=&quot;someapp&quot;/&amp;gt;
  &amp;lt;job_instance jobinstanceid=&quot;399342&quot; jobname=&quot;somejob2&quot; applicationname=&quot;someapp&quot;/&amp;gt;
  &amp;lt;job_instance jobinstanceid=&quot;399343&quot; jobname=&quot;somejob3&quot; applicationname=&quot;someapp&quot;/&amp;gt;
...
  &amp;lt;job_instance jobinstanceid=&quot;400004&quot; jobname=&quot;somejob4&quot; applicationname=&quot;someapp&quot;/&amp;gt;
&amp;lt;/dataset&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_exporting_importing_an_entire_database&quot;&gt;Exporting / importing an entire database&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;project name=&quot;mydbunit&quot; basedir=&quot;.&quot;&amp;gt;
    &amp;lt;taskdef name=&quot;dbunit&quot; classname=&quot;org.dbunit.ant.DbUnitTask&quot;/&amp;gt;

    &amp;lt;loadproperties srcFile=&quot;dbunit.properties&quot;/&amp;gt;

    &amp;lt;fail unless=&quot;dbunit.driver&quot;/&amp;gt;
    &amp;lt;fail unless=&quot;dbunit.url&quot;/&amp;gt;
    &amp;lt;fail unless=&quot;dbunit.userid&quot;/&amp;gt;
    &amp;lt;fail unless=&quot;dbunit.password&quot;/&amp;gt;
    &amp;lt;fail unless=&quot;dbunit.datatypeFactory&quot;/&amp;gt;

    &amp;lt;property name=&quot;dbunit.format&quot; value=&quot;flat&quot;/&amp;gt; &amp;lt;!-- Possible values are &quot;flat&quot;, &quot;xml&quot;, &quot;csv&quot;, &quot;dtd&quot;, &quot;xls&quot;. Defaults to &quot;flat&quot; --&amp;gt;

    &amp;lt;target name=&quot;export&quot;&amp;gt;
        &amp;lt;fail unless=&quot;dbunit.dest&quot;/&amp;gt;
        &amp;lt;fail unless=&quot;dbunit.format&quot;/&amp;gt;

        &amp;lt;dbunit driver=&quot;${dbunit.driver}&quot; url=&quot;${dbunit.url}&quot; userid=&quot;${dbunit.userid}&quot; password=&quot;${dbunit.password}&quot;&amp;gt;
            &amp;lt;dbconfig&amp;gt;
                &amp;lt;property name=&quot;datatypeFactory&quot; value=&quot;${dbunit.datatypeFactory}&quot; /&amp;gt;
                &amp;lt;!-- &amp;lt;property name=&quot;escapePattern&quot; value=&quot;`?`&quot; /&amp;gt; --&amp;gt;
            &amp;lt;/dbconfig&amp;gt;
            &amp;lt;export dest=&quot;${dbunit.dest}&quot; ordered=&quot;true&quot;/&amp;gt;
        &amp;lt;/dbunit&amp;gt;
    &amp;lt;/target&amp;gt;

    &amp;lt;target name=&quot;import&quot;&amp;gt;
        &amp;lt;fail unless=&quot;dbunit.src&quot;/&amp;gt;
        &amp;lt;fail unless=&quot;dbunit.format&quot;/&amp;gt;

        &amp;lt;dbunit driver=&quot;${dbunit.driver}&quot; url=&quot;${dbunit.url}&quot; userid=&quot;${dbunit.userid}&quot; password=&quot;${dbunit.password}&quot;&amp;gt;
            &amp;lt;dbconfig&amp;gt;
                &amp;lt;property name=&quot;datatypeFactory&quot; value=&quot;${dbunit.datatypeFactory}&quot; /&amp;gt;
                &amp;lt;!-- &amp;lt;property name=&quot;escapePattern&quot; value=&quot;`?`&quot; /&amp;gt; --&amp;gt;
            &amp;lt;/dbconfig&amp;gt;
            &amp;lt;operation type=&quot;CLEAN_INSERT&quot; src=&quot;${dbunit.src}&quot; ordered=&quot;true&quot;/&amp;gt;
        &amp;lt;/dbunit&amp;gt;
    &amp;lt;/target&amp;gt;

&amp;lt;/project&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;To export:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ ant export -Ddbunit.dest=mydb.xml&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;To import:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;listingblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ ant import -Ddbunit.src=mydb.xml&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Note that you need &lt;a href=&quot;http://mvnrepository.com/artifact/commons-collections/commons-collections&quot;&gt;commons-collections3&lt;/a&gt; jar file in your classpath.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_other_tasks&quot;&gt;Other tasks&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;There are more operations that can be achieved through Ant tasks available such as:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Data comparison&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;INSERT or UPDATE based on the file&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_references&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;http://dbunit.sourceforge.net/anttask.html&quot; class=&quot;bare&quot;&gt;http://dbunit.sourceforge.net/anttask.html&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/using-rabbitmq-with-java</id>
        <title type="html">Using RabbitMQ with Java</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/using-rabbitmq-with-java"/>
        <published>2015-08-05T08:04:54+00:00</published>
        <updated>2015-08-05T08:15:02+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="rabbitmq" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;RabbitMQ is an open source message broker software made with Erlang. RabbitMQ is sponsored by Pivotal Software, Inc. in this entry, we&amp;#8217;ll see how to launch it, publish or receive simple messages with Java client on OS X.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_installation&quot;&gt;Installation&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;I&amp;#8217;m using OS X 10.9.5. download &lt;code&gt;rabbitmq-server-mac-standalone-3.5.4.tar.gz&lt;/code&gt; for Macs then extract it on somewhere.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_start_the_server&quot;&gt;Start the server&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The server can be launched via execute &lt;code&gt;sbin/rabbitmq-server&lt;/code&gt; as follows.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;$ ./rabbitmq-server

              RabbitMQ 3.5.4. Copyright (C) 2007-2015 Pivotal Software, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: ./../var/log/rabbitmq/rabbit@kyle-no-MacBook.log
  ######  ##        ./../var/log/rabbitmq/rabbit@kyle-no-MacBook-sasl.log
  ##########
              Starting broker... completed with 0 plugins.&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;To shutdown, hit &lt;code&gt;Ctrl+C&lt;/code&gt; then press &lt;code&gt;a&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Next, we&amp;#8217;ll look how to interact with the server from Java client.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_dependencies&quot;&gt;Dependencies&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;RabbitMQ supplies the client library for Java in Maven Central. just put following dependency to your &lt;code&gt;pom.xml&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;dependency&amp;gt;
	&amp;lt;groupId&amp;gt;com.rabbitmq&amp;lt;/groupId&amp;gt;
	&amp;lt;artifactId&amp;gt;amqp-client&amp;lt;/artifactId&amp;gt;
	&amp;lt;version&amp;gt;3.5.4&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_java_examples_in_official_tutorial&quot;&gt;Java examples in official tutorial&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;There is a complete Hello World example of a publisher in &lt;a href=&quot;https://www.rabbitmq.com/tutorials/tutorial-one-java.html&quot; class=&quot;bare&quot;&gt;https://www.rabbitmq.com/tutorials/tutorial-one-java.html&lt;/a&gt; . just copy and paste it to your workspace and execute it after launch the server.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Complete a consumer example is here: &lt;a href=&quot;https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/java/Recv.java&quot; class=&quot;bare&quot;&gt;https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/java/Recv.java&lt;/a&gt; . just execute it after execution of publisher is done.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The whole project can be obtained from &lt;a href=&quot;https://github.com/lbtc-xxx/rabbitmq-hello&quot;&gt;my GitHub repository&lt;/a&gt;, nothing interesting here though.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_remarks&quot;&gt;Remarks&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;It&amp;#8217;s very easy to use, I haven&amp;#8217;t experienced any pitfall at all.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;I wanted to interact with the server using JMS, but the JMS client needs a commercial license to download and unfortunately I don&amp;#8217;t have one.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;&lt;a href=&quot;http://rabbitmq.1065348.n5.nabble.com/RabbitMQ-broker-with-JMS-Client-td31418.html&quot; class=&quot;bare&quot;&gt;http://rabbitmq.1065348.n5.nabble.com/RabbitMQ-broker-with-JMS-Client-td31418.html&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_references&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://www.rabbitmq.com/getstarted.html&quot; class=&quot;bare&quot;&gt;https://www.rabbitmq.com/getstarted.html&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/lean-example-of-tomcat-82</id>
        <title type="html">Lean example of Tomcat 8 + Guice 4 + Jersey 2.19</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/lean-example-of-tomcat-82"/>
        <published>2015-08-05T05:36:09+00:00</published>
        <updated>2015-08-05T05:36:09+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="guice" scheme="http://roller.apache.org/ns/tags/" />
        <category term="jersey" scheme="http://roller.apache.org/ns/tags/" />
        <category term="tomcat" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Jersey is the RI of JAX-RS. in this entry, I introduce you how to use Jersey 2.19 with Guice 4 on Tomcat 8. it looks like there are some issues exist as follows but thanks to &lt;a href=&quot;https://github.com/Squarespace/jersey2-guice&quot; class=&quot;bare&quot;&gt;https://github.com/Squarespace/jersey2-guice&lt;/a&gt; , I&amp;#8217;ve succeeded to use them anyway.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://java.net/jira/browse/JERSEY-1950&quot; class=&quot;bare&quot;&gt;https://java.net/jira/browse/JERSEY-1950&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://java.net/jira/browse/HK2-121&quot; class=&quot;bare&quot;&gt;https://java.net/jira/browse/HK2-121&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The entire project which based on Maven can be obtained from &lt;a href=&quot;https://github.com/lbtc-xxx/guice-jersey-tomcat&quot;&gt;My GitHub repository&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_dependencies&quot;&gt;Dependencies&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;dependencyManagement&amp;gt;
    &amp;lt;dependencies&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.glassfish.jersey&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;jersey-bom&amp;lt;/artifactId&amp;gt;
            &amp;lt;version&amp;gt;2.19&amp;lt;/version&amp;gt;
            &amp;lt;type&amp;gt;pom&amp;lt;/type&amp;gt;
            &amp;lt;scope&amp;gt;import&amp;lt;/scope&amp;gt;
        &amp;lt;/dependency&amp;gt;
    &amp;lt;/dependencies&amp;gt;
&amp;lt;/dependencyManagement&amp;gt;

&amp;lt;dependencies&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;javax.servlet&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;javax.servlet-api&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;3.1.0&amp;lt;/version&amp;gt;
        &amp;lt;scope&amp;gt;provided&amp;lt;/scope&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.glassfish.jersey.containers&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;jersey-container-servlet&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;com.google.inject&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;guice&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;4.0&amp;lt;/version&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;com.google.inject.extensions&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;guice-servlet&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;4.0&amp;lt;/version&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;com.squarespace.jersey2-guice&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;jersey2-guice&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;0.10&amp;lt;/version&amp;gt;
    &amp;lt;/dependency&amp;gt;
&amp;lt;/dependencies&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_web_xml&quot;&gt;web.xml&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;web-app xmlns=&quot;http://xmlns.jcp.org/xml/ns/javaee&quot;
         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd&quot;
         version=&quot;3.1&quot;&amp;gt;

    &amp;lt;servlet&amp;gt;
        &amp;lt;servlet-name&amp;gt;Jersey Web Application&amp;lt;/servlet-name&amp;gt;
        &amp;lt;servlet-class&amp;gt;org.glassfish.jersey.servlet.ServletContainer&amp;lt;/servlet-class&amp;gt;
        &amp;lt;init-param&amp;gt;
            &amp;lt;param-name&amp;gt;jersey.config.server.provider.packages&amp;lt;/param-name&amp;gt;
            &amp;lt;param-value&amp;gt;guice.tomcat.jersey&amp;lt;/param-value&amp;gt;
        &amp;lt;/init-param&amp;gt;
        &amp;lt;load-on-startup&amp;gt;1&amp;lt;/load-on-startup&amp;gt;
    &amp;lt;/servlet&amp;gt;

    &amp;lt;servlet-mapping&amp;gt;
        &amp;lt;servlet-name&amp;gt;Jersey Web Application&amp;lt;/servlet-name&amp;gt;
        &amp;lt;url-pattern&amp;gt;/webapi/*&amp;lt;/url-pattern&amp;gt;
    &amp;lt;/servlet-mapping&amp;gt;

    &amp;lt;listener&amp;gt;
        &amp;lt;listener-class&amp;gt;guice.tomcat.MyJerseyGuiceServletContextListener&amp;lt;/listener-class&amp;gt;
    &amp;lt;/listener&amp;gt;

    &amp;lt;filter&amp;gt;
        &amp;lt;filter-name&amp;gt;guiceFilter&amp;lt;/filter-name&amp;gt;
        &amp;lt;filter-class&amp;gt;com.google.inject.servlet.GuiceFilter&amp;lt;/filter-class&amp;gt;
    &amp;lt;/filter&amp;gt;

    &amp;lt;filter-mapping&amp;gt;
        &amp;lt;filter-name&amp;gt;guiceFilter&amp;lt;/filter-name&amp;gt;
        &amp;lt;url-pattern&amp;gt;/*&amp;lt;/url-pattern&amp;gt;
    &amp;lt;/filter-mapping&amp;gt;

&amp;lt;/web-app&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_myjerseyguiceservletcontextlistener_java&quot;&gt;MyJerseyGuiceServletContextListener.java&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;In this example, we use the servlet context listener named &lt;code&gt;JerseyGuiceServletContextListener&lt;/code&gt; which comes from &lt;code&gt;jersey2-guice&lt;/code&gt; artifact as parent class.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public class MyJerseyGuiceServletContextListener extends JerseyGuiceServletContextListener {
    @Override
    protected List&amp;lt;? extends Module&amp;gt; modules() {
        return Collections.singletonList(new ServletModule() {
            @Override
            protected void configureServlets() {
                bind(MyService.class).to(MyServiceImpl.class);
            }
        });
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_service_class&quot;&gt;Service class&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;We use very simple pair of an interface and implementation that creates a simple greeting message, which used in  &lt;a href=&quot;/roller/kyle/entry/lean-example-of-tomcat-8&quot;&gt;a past entry&lt;/a&gt; so omitted for simplicity.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_myresource_java&quot;&gt;MyResource.java&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This is an simple implementation of JAX-RS resource class. placed under &lt;code&gt;guice.tomcat.jersey&lt;/code&gt; package. the preceding service class named &lt;code&gt;MyService&lt;/code&gt; will be injected by &lt;code&gt;@javax.inject.Inject&lt;/code&gt; annotation.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Path(&quot;myresource&quot;)
public class MyResource {

    @Inject
    private MyService myService;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getIt() {
        return myService.hello(&quot;Jersey&quot;);
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_test_run&quot;&gt;Test run&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;$ curl http://localhost:8080/webapi/myresource
Hello, Jersey&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/lean-example-of-tomcat-81</id>
        <title type="html">Lean example of Tomcat 8 + Guice 4 + EclipseLink 2.6.0</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/lean-example-of-tomcat-81"/>
        <published>2015-08-04T10:26:46+00:00</published>
        <updated>2015-08-04T10:27:28+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="eclipselink" scheme="http://roller.apache.org/ns/tags/" />
        <category term="guice" scheme="http://roller.apache.org/ns/tags/" />
        <category term="jpa" scheme="http://roller.apache.org/ns/tags/" />
        <category term="tomcat" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;I wrote a Lean example of Tomcat 8 + Guice 4 in &lt;a href=&quot;/roller/kyle/entry/lean-example-of-tomcat-8&quot;&gt;previous entry&lt;/a&gt;. this time, I&amp;#8217;ll try JPA(EclipseLink) integration with automatic transaction management.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The entire project which based on Maven can be obtained from &lt;a href=&quot;https://github.com/lbtc-xxx/guice-jpa-tomcat&quot;&gt;My GitHub repository&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;For database connection, we&amp;#8217;ll use a DataSource which is defined on Tomcat server. to define a Embedded Derby DataSource, &lt;a href=&quot;/roller/kyle/entry/defining-embedded-derby-as-a&quot;&gt;This entry&lt;/a&gt; would help.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_dependencies&quot;&gt;Dependencies&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;dependencies&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;javax.servlet&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;javax.servlet-api&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;3.1.0&amp;lt;/version&amp;gt;
        &amp;lt;scope&amp;gt;provided&amp;lt;/scope&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.eclipse.persistence&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;eclipselink&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;2.6.0&amp;lt;/version&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;com.google.inject&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;guice&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;4.0&amp;lt;/version&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;com.google.inject.extensions&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;guice-servlet&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;4.0&amp;lt;/version&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;com.google.inject.extensions&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;guice-persist&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;4.0&amp;lt;/version&amp;gt;
    &amp;lt;/dependency&amp;gt;
&amp;lt;/dependencies&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_web_xml&quot;&gt;web.xml&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;No changes against previous entry except addition of &lt;code&gt;resource-ref&lt;/code&gt; element.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;web-app xmlns=&quot;http://xmlns.jcp.org/xml/ns/javaee&quot;
         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd&quot;
         version=&quot;3.1&quot;&amp;gt;

    &amp;lt;!-- taken from https://github.com/google/guice/wiki/Servlets --&amp;gt;

    &amp;lt;listener&amp;gt;
        &amp;lt;listener-class&amp;gt;guice.tomcat.MyGuiceServletConfig&amp;lt;/listener-class&amp;gt;
    &amp;lt;/listener&amp;gt;

    &amp;lt;filter&amp;gt;
        &amp;lt;filter-name&amp;gt;guiceFilter&amp;lt;/filter-name&amp;gt;
        &amp;lt;filter-class&amp;gt;com.google.inject.servlet.GuiceFilter&amp;lt;/filter-class&amp;gt;
    &amp;lt;/filter&amp;gt;

    &amp;lt;filter-mapping&amp;gt;
        &amp;lt;filter-name&amp;gt;guiceFilter&amp;lt;/filter-name&amp;gt;
        &amp;lt;url-pattern&amp;gt;/*&amp;lt;/url-pattern&amp;gt;
    &amp;lt;/filter-mapping&amp;gt;

    &amp;lt;resource-ref&amp;gt;
        &amp;lt;res-ref-name&amp;gt;jdbc/derby&amp;lt;/res-ref-name&amp;gt;
        &amp;lt;res-type&amp;gt;javax.sql.DataSource&amp;lt;/res-type&amp;gt;
        &amp;lt;res-auth&amp;gt;Container&amp;lt;/res-auth&amp;gt;
    &amp;lt;/resource-ref&amp;gt;

&amp;lt;/web-app&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_meta_inf_persistence_xml&quot;&gt;META-INF/persistence.xml&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;If you don&amp;#8217;t want to use a DataSource on Tomcat, specify the connection information in &lt;code&gt;javax.persistence.jdbc.*&lt;/code&gt; properties instead of &lt;code&gt;non-jta-data-source&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&amp;gt;
&amp;lt;persistence version=&quot;2.1&quot; xmlns=&quot;http://xmlns.jcp.org/xml/ns/persistence&quot;
             xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
             xsi:schemaLocation=&quot;http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd&quot;&amp;gt;
    &amp;lt;persistence-unit name=&quot;myJpaUnit&quot; transaction-type=&quot;RESOURCE_LOCAL&quot;&amp;gt;
        &amp;lt;provider&amp;gt;org.eclipse.persistence.jpa.PersistenceProvider&amp;lt;/provider&amp;gt;
        &amp;lt;non-jta-data-source&amp;gt;java:comp/env/jdbc/derby&amp;lt;/non-jta-data-source&amp;gt;
        &amp;lt;class&amp;gt;guice.tomcat.MyEntity&amp;lt;/class&amp;gt;
        &amp;lt;properties&amp;gt;
            &amp;lt;property name=&quot;eclipselink.ddl-generation&quot; value=&quot;drop-and-create-tables&quot;/&amp;gt;
            &amp;lt;property name=&quot;eclipselink.logging.level&quot; value=&quot;FINE&quot;/&amp;gt;
            &amp;lt;property name=&quot;eclipselink.logging.level.sql&quot; value=&quot;FINE&quot;/&amp;gt;
        &amp;lt;/properties&amp;gt;
    &amp;lt;/persistence-unit&amp;gt;
&amp;lt;/persistence&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_myguiceservletconfig_java&quot;&gt;MyGuiceServletConfig.java&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The last two statements will take care of JPA integration.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public class MyGuiceServletConfig extends GuiceServletContextListener {
    @Override
    protected Injector getInjector() {
        return Guice.createInjector(new ServletModule() {
            @Override
            protected void configureServlets() {
                serve(&quot;/*&quot;).with(MyServlet.class);
                bind(MyService.class).to(MyServiceImpl.class);

                install(new JpaPersistModule(&quot;myJpaUnit&quot;));
                filter(&quot;/*&quot;).through(PersistFilter.class);
            }
        });
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_myentity_java&quot;&gt;MyEntity.java&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This is a very simple JPA entity which keeps only generated &lt;code&gt;id&lt;/code&gt; and &lt;code&gt;ts&lt;/code&gt; (a timestamp).&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@Entity
@NamedQuery(name = &quot;MyEntity.findAll&quot;, query = &quot;SELECT e FROM MyEntity e ORDER BY e.id DESC&quot;)
public class MyEntity implements Serializable {

    @Id
    @GeneratedValue
    private Long id;
    @Column(nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date ts;

... accessors are omitted&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_service_class&quot;&gt;Service class&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_myservice_java&quot;&gt;MyService.java&lt;/h3&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public interface MyService {
    void save(MyEntity e);
    List&amp;lt;MyEntity&amp;gt; findAll();
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_myserviceimpl_java&quot;&gt;MyServiceImpl.java&lt;/h3&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Note that you need to annotate a method with &lt;code&gt;@com.google.inject.persist.Transactional&lt;/code&gt; if you need a transaction on it.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public class MyServiceImpl implements MyService {

    // Transactions doesn&apos;t start if EntityManager is directly injected via @Inject.
    // I have no idea why...

    // According to https://github.com/google/guice/wiki/JPA,
    // &quot;Note that if you make MyService a @Singleton, then you should inject Provider&amp;lt;EntityManager&amp;gt; instead.&quot;
    @Inject
    private Provider&amp;lt;EntityManager&amp;gt; emp;

    @Override
    // @javax.transaction.Transactional is not supported yet. https://github.com/google/guice/issues/797
    @com.google.inject.persist.Transactional
    public void save(MyEntity e) {
        EntityManager em = emp.get();
        em.persist(e);
    }

    @Override
    public List&amp;lt;MyEntity&amp;gt; findAll() {
        return emp.get().createNamedQuery(&quot;MyEntity.findAll&quot;, MyEntity.class).getResultList();
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_myservlet_java&quot;&gt;MyServlet.java&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;This servlet saves a &lt;code&gt;MyEntity&lt;/code&gt; with current timestamp, then fetches all of rows and returns them to the client on every request.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@javax.inject.Singleton
public class MyServlet extends HttpServlet {

    @javax.inject.Inject
    private MyService myService;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        MyEntity myEntity = new MyEntity();
        myEntity.setTs(new Date());
        myService.save(myEntity);

        PrintWriter writer = resp.getWriter();
        writer.write(&quot;&amp;lt;html&amp;gt;&amp;lt;body&amp;gt;&amp;lt;ul&amp;gt;&quot;);
        for(MyEntity e : myService.findAll()){
            writer.write(&quot;&amp;lt;li&amp;gt;&quot;);
            writer.write(e.toString());
            writer.write(&quot;&amp;lt;/li&amp;gt;&quot;);
        }
        writer.write(&quot;&amp;lt;/ul&amp;gt;&amp;lt;/body&amp;gt;&amp;lt;/html&amp;gt;&quot;);

    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_test_run&quot;&gt;Test run&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;A row will be saved on every request as follows:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;imageblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;img src=&quot;/roller/kyle/mediaresource/4d678c4b-c55c-41e0-ba5d-65d2832409fb&quot; alt=&quot;4d678c4b c55c 41e0 ba5d 65d2832409fb&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_references&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/google/guice/wiki/JPA&quot; class=&quot;bare&quot;&gt;https://github.com/google/guice/wiki/JPA&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://gist.github.com/halyph/2990769&quot; class=&quot;bare&quot;&gt;https://gist.github.com/halyph/2990769&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
    <entry>
        <id>https://nozaki.me/roller/kyle/entry/lean-example-of-tomcat-8</id>
        <title type="html">Lean example of Tomcat 8 + Guice 4</title>
        <author><name>Kohei Nozaki</name></author>
        <link rel="alternate" type="text/html" href="https://nozaki.me/roller/kyle/entry/lean-example-of-tomcat-8"/>
        <published>2015-08-03T09:56:46+00:00</published>
        <updated>2015-08-03T09:56:46+00:00</updated> 
        <category term="Technology" label="Technology" />
        <category term="guice" scheme="http://roller.apache.org/ns/tags/" />
        <category term="tomcat" scheme="http://roller.apache.org/ns/tags/" />
        <content type="html">&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;I prefer Java EE stack usually, but I need to learn a Tomcat based stack for some reasons these days. in this entry, I introduce you a very simple example of Tomcat 8 + Guice 4 app which uses &lt;code&gt;GuiceFilter&lt;/code&gt; and &lt;code&gt;GuiceServletContextListener&lt;/code&gt; so that bring Guice to a Servlet based web application.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;The entire project which based on Maven can be obtained from &lt;a href=&quot;https://github.com/lbtc-xxx/guice-tomcat&quot;&gt;My GitHub repository&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_dependencies&quot;&gt;Dependencies&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;javax.servlet&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;javax.servlet-api&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;3.1.0&amp;lt;/version&amp;gt;
    &amp;lt;scope&amp;gt;provided&amp;lt;/scope&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;com.google.inject&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;guice&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;4.0&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;com.google.inject.extensions&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;guice-servlet&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;4.0&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_web_xml&quot;&gt;web.xml&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;&amp;lt;web-app xmlns=&quot;http://xmlns.jcp.org/xml/ns/javaee&quot;
         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd&quot;
         version=&quot;3.1&quot;&amp;gt;

    &amp;lt;listener&amp;gt;
        &amp;lt;listener-class&amp;gt;guice.tomcat.MyGuiceServletConfig&amp;lt;/listener-class&amp;gt;
    &amp;lt;/listener&amp;gt;

    &amp;lt;filter&amp;gt;
        &amp;lt;filter-name&amp;gt;guiceFilter&amp;lt;/filter-name&amp;gt;
        &amp;lt;filter-class&amp;gt;com.google.inject.servlet.GuiceFilter&amp;lt;/filter-class&amp;gt;
    &amp;lt;/filter&amp;gt;

    &amp;lt;filter-mapping&amp;gt;
        &amp;lt;filter-name&amp;gt;guiceFilter&amp;lt;/filter-name&amp;gt;
        &amp;lt;url-pattern&amp;gt;/*&amp;lt;/url-pattern&amp;gt;
    &amp;lt;/filter-mapping&amp;gt;

&amp;lt;/web-app&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_myguiceservletconfig_java&quot;&gt;MyGuiceServletConfig.java&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;We need to declare servlet mappings and the mappings between interfaces and implementations here.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public class MyGuiceServletConfig extends GuiceServletContextListener {
    @Override
    protected Injector getInjector() {
        return Guice.createInjector(new ServletModule() {
            @Override
            protected void configureServlets() {
                serve(&quot;/*&quot;).with(MyServlet.class);
                bind(MyService.class).to(MyServiceImpl.class);
            }
        });
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_service_class&quot;&gt;Service class&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;We use a pair of a very simple implementation of a service class. it simply creates a greetings which uses an argument.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_myservice_java&quot;&gt;MyService.java&lt;/h3&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public interface MyService {
    String hello(String name);
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect2&quot;&gt;
&lt;h3 id=&quot;_myserviceimpl_java&quot;&gt;MyServiceImpl.java&lt;/h3&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;public class MyServiceImpl implements MyService {
    @Override
    public String hello(String name) {
        return &quot;Hello, &quot; + name;
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_myservlet_java&quot;&gt;MyServlet.java&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;Note that we use &lt;code&gt;@javax.inject.Singleton&lt;/code&gt; and &lt;code&gt;@javax.inject.Inject&lt;/code&gt; annotations, that are standardized JSR API.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;@javax.inject.Singleton
public class MyServlet extends HttpServlet {

    @javax.inject.Inject
    private MyService myService;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write(myService.hello(&quot;Guice&quot;));
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_test_run&quot;&gt;Test run&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;paragraph&quot;&gt;
&lt;p&gt;After deployment, send a request to check the response:&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;literalblock&quot;&gt;
&lt;div class=&quot;content&quot;&gt;
&lt;pre&gt;$ curl http://localhost:8080
Hello, Guice&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_other_things_functions_need_to_be_studied&quot;&gt;Other things/functions need to be studied&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Transaction management&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;CDI Producer equivalent&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;AOP&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Automatic implementation scanning/binding&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;sect1&quot;&gt;
&lt;h2 id=&quot;_references&quot;&gt;References&lt;/h2&gt;
&lt;div class=&quot;sectionbody&quot;&gt;
&lt;div class=&quot;ulist&quot;&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/google/guice/wiki/Servlets&quot; class=&quot;bare&quot;&gt;https://github.com/google/guice/wiki/Servlets&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/google/guice/wiki/ServletModule&quot; class=&quot;bare&quot;&gt;https://github.com/google/guice/wiki/ServletModule&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</content>
    </entry>
</feed>

