Kohei Nozaki's blog 

In-container JMS consumer/producer example


Posted on Saturday May 14, 2016 at 11:06PM in Technology


In this entry, I’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’re going to deploy it to a container (WildFly 10.0.0.Final) and see a webapp produces and consumes a message.

Launch the container

Launch WildFly server with the following parameter so the bundled message queue broker (ActiveMQ Artemis) will be launched:

./standalone.sh -c standalone-full.xml

For IntelliJ IDEA, check how to launch WildFly with -c standalone-full.xml from this SO: http://stackoverflow.com/questions/25849810/how-to-run-wildfly-with-standalone-full-xml-from-intellij-idea

Define a queue

Launch jboss-cli and define a queue with this command:

jms-queue add --queue-address=testQueue --entries=queue/test,java:jboss/exported/jms/queue/test

Check if it’s successfully created:

[standalone@localhost:9990 /] /subsystem=messaging-activemq/server=default/jms-queue=testQueue:read-resource
{
    "outcome" => "success",
    "result" => {
        "durable" => true,
        "entries" => [
            "queue/test",
            "java:jboss/exported/jms/queue/test"
        ],
        "legacy-entries" => undefined,
        "selector" => undefined
    }
}

Create the webapp which contains consumer/producer

Here we’re going to create following three classes in the webapp:

  • MyProducer: a Stateless Session Bean which produces a message to the queue

  • MyConsumer: a Message-Driven Bean which consumes any messages being sent to the queue

  • MyServlet: Receives HTTP GET request and kicks MyProducer

The whole project can be obtained from My GitHub repository.

MyProducer

@Stateless
@LocalBean
public class MyProducer {

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

    public void enqueue(final String text) {
        jmsContext.createProducer().send(testQueue, text);
    }
}

MyConsumer

@MessageDriven(name = "MyMDB", activationConfig = {
        @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/test"),
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
        @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge")})
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(() -> "Received: " + text);
            } catch (final JMSException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

MyServlet

@WebServlet(urlPatterns = "/")
public class MyServlet extends HttpServlet {

    @EJB
    MyProducer myProducer;

    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        final String text = "Hello, JMS!";
        myProducer.enqueue(text);
        resp.getWriter().write("Published! check output of the consumer: " + text + "\n");
    }
}

Of course you don’t need to put MyConsumer to the webapp which contains MyProducer. this is just an example, and in fact, just for asynchronous/background processing in a webapp, you better use more simple EJB Asynchronous methods or ManagedExecutorService instead of JMS. for real use-case, you may create a dedicated app for queue consumers and place your MyConsumer equivalent into it.

Trigger producing and consuming

Deploy the app and submit HTTP GET request to it as follows.

$ curl http://localhost:8080/jms-example/

If it worked successfully, you’ll see following response from the Servlet:

Published! check output of the consumer: Hello, JMS!

Then check console/output/log of your application container. if the consumer worked successfully, you can see the output something like following:

13:55:18,168 INFO  [class jms.MyConsumer] (Thread-438 (ActiveMQ-client-global-threads-271921988)) Received: Hello, JMS!

Conclusion

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.

And note that there are no use of vendor-specific classes - it uses only standardized API which comes from javaee-api. 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 a few.


PrivateModule, TypeLiteral and AssistedInject - Google Guice techniques for complex scenarios


Posted on Sunday Feb 07, 2016 at 11:44AM in Technology


In this entry I’ll introduce you some Google Guice techniques that can be used for some complex class designing scenarios, I’ve learned recently and found very helpful.

I’ve tested techniques that used in this entry works with Google Guice 3.0 and 4.0. example implementations and test cases can be obtained from my GitHub repository.

PrivateModule

Consider you have classes that something like following diagram:

237fbbbb c5d0 4315 aeef ccc9e8b2605e

You have a service class named MyService which depends on the interface named MyStrategy (DOC, Depended On Component). the DOC has two implementations, the one EnglishStrategy says "Hello", when the method of it named sayHello() is being called, and another one JapaneseStrategy says "Konnichiwa".

There are annotation classes English and Japanese to distinguish two strategy MyService depends on. these two annotations are written as follows:

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 {
}

On that situation, you want Guice to produce and inject two MyService instances for your client class. you would declare injection points as follows:

// (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;

But it doesn’t work due to Guice failed to look MyService binding annotated as @English and @Japanese up.

In such case, you can create two PrivateModule and install them in your Module implementation as follows:

@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);
        }
    });
}

These PrivateModule create two bindings:

  1. MyService annotated with English or Japanese.

  2. MyStrategy without any annotation for EnglishStrategy or JapaneseStrategy privately

And, it exposes 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 MyStrategy without any annotation. that’s point what PrivateModule helps.

TypeLiteral

Consider you have following injection points that with generics type parameter:

@Inject
List<String> stringList;
@Inject
List<Integer> integerList;

To bind instances to these injection points, you need to use TypeLiteral in your Module implementation as follows:

@Override
protected void configure() {
    bind(new TypeLiteral<List<String>>() {
    }).toInstance(new ArrayList<String>() {{
        add("hello");
    }});

    bind(new TypeLiteral<List<Integer>>() {
    }).toInstance(new ArrayList<Integer>() {{
        add(123);
    }});
}

With this module, Guice resolves correct the two injection points with use of generics type parameter.

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:

public interface MyGenericService<T extends Number> {
    T get();
}

Injection points:

@Inject
MyGenericService<Integer> integerService;
@Inject
MyGenericService<Double> doubleService;

Two implementations:

public class MyIntegerService implements MyGenericService<Integer> {
    @Override
    public Integer get() {
        return 123;
    }
}
public class MyDoubleService implements MyGenericService<Double> {
    @Override
    public Double get() {
        return 0.5;
    }
}

To create bindings to these injection points without creating instances in the module, you can write as follows in your module implementation:

bind(new TypeLiteral<MyGenericService<Integer>>(){}).to(MyIntegerService.class);
bind(new TypeLiteral<MyGenericService<Double>>(){}).to(MyDoubleService.class);

AssistedInject

Consider you have classes that something like following diagram:

703fa153 c547 4dd9 9145 70f36d55988e

You have a service class named MyProduct, which requires a parameter name for its constructor. the parameter name varies in each injection, so we create the factory interface MyFactory for it. also, MyProduct depends on MyCollaborator.

You would create MyProduct instance in your client as follows:

@Inject
MyFactory factory;
...
public void someMethodInClient() {
    final MyProduct product = factory.create("foo");
    ...
}

So, anyway, an implementation of MyFactory 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 MyProduct has a hundreds of DOCs? it will be longer as numbers of DOCs grows. manual construction procedure will be something like new MyProduct(new MyCollaborator1(), new MyCollaborator2(), …​) . obviously, it should be avoided.

With AssistedInject , Guice will do it instead of you.

First, create MyFactory as follows:

public interface MyFactory {
    MyProduct create(String name);
}

Note that you don’t need to create an implementation class yourself, just forget about it. next, put an additional dependency to your pom.xml:

<dependency>
    <groupId>com.google.inject.extensions</groupId>
    <artifactId>guice-assistedinject</artifactId>
    <version>4.0</version>
</dependency>

Put following procedure to your Module implementation:

@Override
protected void configure() {
    install(new FactoryModuleBuilder().build(MyFactory.class));
}

Finally, declare an injection point in the MyProduct class as follows. note that a constructor parameter name is annotated as @Assisted:

@Inject
MyProduct(@Assisted final String name, final MyCollaborator collaborator) {
    this.name = name;
    this.collaborator = collaborator;
}

With that, Guice automatically creates MyFactory implementation for you, and handles parameter name nicely.


jEdit conditional line deleting with regex


Posted on Sunday Jan 31, 2016 at 06:03PM in Technology


How to delete lines that contains a keyword?

Open Search And Replace dialog and turn Regular expressions on then put ^.*KEYWORD.*$\n to Search for box, leave Replace with blank then hit Replace All.

How to delete lines that NOT contains a keyword?

With ^((?!KEYWORD).)*$\n do the same to the above. for detail check http://stackoverflow.com/questions/406230/regular-expression-to-match-line-that-doesnt-contain-a-word


My jEdit setup on OS X


Posted on Sunday Jan 31, 2016 at 04:00PM in Technology


Make Option key work

Put a file contains following line to $HOME/Library/jEdit/startup so shortcuts that used Option work.

Debug.ALT_KEY_PRESSED_DISABLED = false;

Check http://www.nailedtothex.org/roller/kyle/entry/installing-and-configuring-jedit-5 for further information about setup jEdit on OS X.

Basic configurations

Just for my preferences:

  • Go to View section

    • check Show full path of buffer in title bar

  • Go to Editing section

    • set Word wrap to soft

    • set Wrap margin to 100

    • check Soft (emulated with spaces) tabs

  • Go to Toolbar

    • uncheck Show tool bar

  • Go to Text Area

    • check Caret: thick

Customize shortcut

First, choose keymap Mac OS X. Then customize maps that unusable by default because OS X takes precedence.

  • Incremental Search: CMD+, launches application’s preferences window. so I bind it to Option+, instead.

Note: Draw multi-key shortcuts on screen menu bar option makes some shortcut such as move to dockables unusable, I don’t know why.

Basic operations

Macros

From Macros ⇒ New Macro, you can create a BeanShell macros. For example, the macro below puts current date to the position of caret:

textArea.setSelectedText(java.time.LocalDate.now().toString());

Project Viewer

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.

There are some plugin that requires it. For example, FastOpen is a companion plugin for Project Viewer that enables open files fast with keyboard. I’ve set Delay before searching option to the smallest value (0.5sec).

The documentation of this plugin can be obtained from http://plugins.jedit.org/plugindoc/ProjectViewer/

Console

This plugin integrates console as a jEdit dockable.

Its advantages are commands that for invoking jEdit’s functionalities. for example, %edit foo.txt opens a file as a jEdit buffer. another useful one is redirecting output to a new jEdit buffer. for example, typing echo hello, jEdit in the console and hitting Ctrl+ENTER yields a new jEdit buffer with contents of hello, jEdit. also there are many useful variable syntax. e.g. ${f} for the current buffer’s path name. BeanShell console is available as well.

Also SshConsole Plugin extends its functionality to support remote hosts can be connected with SSH.

I recommend that check all three options in Console ⇒ System Shell ⇒ Events to chdir at Plugin Options.

The documentation of this plugin can be obtained from http://plugins.jedit.org/plugindoc/Console/

WhiteSpace

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.

TextTools

It provides some useful text operations, such as Toggle Range Comment. I recommend you to replace shortcuts for built-in ones by this plugin.

jDiff Plugin

It shows difference between two files pretty nicely as IntelliJ.

Others

Some worth considering plugins are:

  • FTP

  • SQL

  • XML

  • MarkerSets


BeanShell recipies


Posted on Sunday Jan 24, 2016 at 04:00PM in Technology


BeanShell is a handy lightweight scripting language for Java. In this entry, I’ll introduce you some useful snippets powered by BeanShell, and some recipies about it.

Setup and hello world

Grab a copy of bsh-2.0b4.jar from http://www.beanshell.org and put following shell script named bsh into your PATH:

#!/bin/sh
BEANSHELL_JAR=$HOME/Downloads/bsh-2.0b4.jar # replace path to suit your environment
java -cp $BEANSHELL_JAR bsh.Interpreter $@

Then fire up bsh from your console then just put print("hello, world!"); to confirm it works.

$ bsh
BeanShell 2.0b4 - by Pat Niemeyer (pat@pat.net)
bsh % print("hello, world!");
hello, world!

Hit Ctrl+D to exit interpreter.

You can launch your BeanShell script in a file as follows:

$ echo 'print("hello, world!");' > hello.bsh
$ bsh hello.bsh
hello, world!

Stdin

Text filtering script can be written as follows:

Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
  String line = scanner.nextLine();
  System.out.println(line.toUpperCase());
}

Save this script as toUpperCase.bsh . The script can be executed as follows:

$ echo foo | bsh toUpperCase.bsh
FOO

Command line arguments

Command line arguments can be used as follows:

sb = new StringBuilder();
for (arg : bsh.args) {
    sb.append(arg);
}
print(sb);

Save this script as args.bsh. The script can be executed as follows:

$ bsh args.bsh foo bar
foobar

Use of external jar

Any external jar can be added via addClassPath clause dynamically. For example, a SQL beautifier script powered by a Hibernate class can be written as follows:

addClassPath("/path/to/hibernate-core-4.3.7.Final.jar"); // 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('\n');
}

beautifized = new BasicFormatterImpl().format(sb.toString());
print(beautifized);

Save this script as sql-beautifier.bsh then execute following command:

$ SQL="SELECT t0.content AS a2, t0.contenttype AS a3, t0.email AS a4 FROM roller_comment t0, weblogentry t1 WHERE ((t1.websiteid = 'f0588427-f2ca-4843-ac87-bbb31aa6013c') AND (t1.id = t0.entryid)) ORDER BY t0.posttime DESC LIMIT 31 OFFSET 0;"
$ echo $SQL | bsh sql-beautifier.bsh

This yields nicely formatted SQL:

SELECT
    t0.content AS a2,
    t0.contenttype AS a3,
    t0.email AS a4
FROM
    roller_comment t0,
    weblogentry t1
WHERE
    (
        (
            t1.websiteid = 'f0588427-f2ca-4843-ac87-bbb31aa6013c'
        )
        AND (
            t1.id = t0.entryid
        )
    )
ORDER BY
    t0.posttime DESC LIMIT 31 OFFSET 0;

Maven plugin

If you have Maven installed, you can execute any BeanShell script without obtaining bsh-2.0b4.jar by hand. Maven and the beanshell-maven-plugin takes care of it instead of you:

$ mvn com.github.genthaler:beanshell-maven-plugin:1.0:run -Dbsh.file="hello.bsh"
...
[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!

Note that you don’t need to create pom.xml to execute a simple BeanShell script.

For managing complex dependencies, you can leave that duty to Maven with pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>sql-beautifier</groupId>
    <artifactId>sql-beautifier</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>com.github.genthaler</groupId>
                <artifactId>beanshell-maven-plugin</artifactId>
                <version>1.0</version>
                <configuration>
                    <script><![CDATA[
                    import java.nio.charset.Charset;
                    import org.apache.commons.io.FileUtils;
                    import org.hibernate.engine.jdbc.internal.BasicFormatterImpl;

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

                    print(result);
         ]]></script>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.hibernate</groupId>
                        <artifactId>hibernate-core</artifactId>
                        <version>4.3.7.Final</version>
                    </dependency>
                    <dependency>
                        <groupId>commons-io</groupId>
                        <artifactId>commons-io</artifactId>
                        <version>2.4</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

Save the SQL you want to beautify as original.sql and executing following command yields similar result:

$ mvn bsh:run -Dsql=original.sql

jEdit integration

jEdit has pretty nice integration with BeanShell. You can integrate that SQL beautifier as a jEdit macro. Put following snippet as ~/Library/jEdit/macros/FormatSQL.bsh (for OS X) or create it with Macros → New Macro from jEdit menu bar:

addClassPath("/path/to/hibernate-core-4.3.7.Final.jar"); // replace path to suit your environment
import org.hibernate.engine.jdbc.internal.BasicFormatterImpl;

sql = textArea.getSelectedText();
beautifized = new BasicFormatterImpl().format(sql);
textArea.setSelectedText(beautifized);

Paste SQL to any jEdit buffer, and select SQL statement and execute the macro with Macros → FormatSQL to trigger formatting.