Adam Bien's Weblog

Classpath conflicts, 50MB WARs, Scaling, Kafka, Threading and JSF, Or Questions for 17th Airhacks Q&A

Questions for the 17th airhacks.tv at August, 3rd 2015 at 6.PM. CET: http://www.ustream.tv/channel/adambien (no reqistration required, no obligations, just ask questions and watch :-)):

  1. Blog posts are not best practices, or Annotation less JPA discussion.
  2. How to deal with classpath conflicts on an application server (e.g. GlassFish)?
  3. Which application server to choose?
  4. How to scale up an application server? To cluster or not to cluster, stale caches and not single singletons...
  5. What about Apache Kafka?
  6. How to choose a database?
  7. Threading in Java and Java EE and what about akka.io?
  8. Is a 50MB WAR worth migration to a Java EE server?
  9. Is it a good idea to combine @EntityListener and WebSockets to implement notifications?
  10. How to structure JSF code?
  11. How to begin with Java EE and JSF?

This list is a digest of the questions gathered at github's gist.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting


NEW dates, new workshop: Java EE 7 Workshops: Bootstrap, Effective, Architectures, JavaScript Bootstrap and HTML 5 December, 7th-11th
Online workshop: Java EE 7 Bootstrap

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

JAX-RS, DI, Maven and GlassFish Or The 10 Most Popular Videos Of "bienadam" Youtube Channel

  1. "A Little REST with JAX-RS 2.0 and Java EE 7"

    Views: 16839 Likes: 101
  2. "Lightweight Java EE"

    Views: 12588 Likes: 86
  3. "Structuring Java EE 7 Applications"

    Views: 11740 Likes: 64
  4. "How To Tackle JavaEE"

    Views: 10098 Likes: 75
  5. "Project LightFish--Java EE Telemetry For GlassFish"

    Views: 9515 Likes: 18
  6. "Creating Java EE 6 Projects With Maven 3"

    Views: 8639 Likes: 28
  7. "Hello JavaEE 7 with JAX-RS 2.0 + JSON"

    Views: 8359 Likes: 43
  8. "Hello JAX-RS"

    Views: 8046 Likes: 41
  9. "Dependency Injection, Inversion of Control and Convention over Configuration ...with JavaFX 8"

    Views: 7155 Likes: 20
  10. "Dependency Injection ...and there is no magic"

    Views: 6905 Likes: 54

See also other screencasts at: tv.adam-bien.com or subscribe to youtube.com/c/bienadam.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting


NEW dates, new workshop: Java EE 7 Workshops: Bootstrap, Effective, Architectures, JavaScript Bootstrap and HTML 5 December, 7th-11th
Online workshop: Java EE 7 Bootstrap

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

JPA: XML overrides Annotations

Java EE APIs operate in the "Convention over Configuration" or "Configuration by Exception" mode:

  1. APIs ship with suitable defaults
  2. Defaults can be overridden / supplemented via annotations
  3. Annotations can be overridden / supplemented via XML descriptors
  4. XML descriptors can be overridden via dedicated extension points, hooks (not available for all APIs)

JPA entities in particular can be deployed with minimalistic set (@Entity / @ID) of annotations first and overridden on demand:

"XML metadata may be used as an alternative to these annotations, or to override or augment annotations (...)"
[Chapter 11, Page 421, JSR-388: Java Persistence 2.1]

In JPA, supplementing, or even replacing annotations with orm.xml eases realization of following use cases:

  1. Product development: generic mappings can be partially adjusted during installation without recompiling the code
  2. Data migrations: entities are read from one persistence unit fully relying on annotations and writing to a persistence unit augmented by orm.xml
  3. Integration of external libraries / third party code: JavaBeans without existing source code can be augmented with orm.xml and turned into entities
  4. Separated read / write databases: a dedicated EntityManager is used for reading, another for writing. The database instances used behind the EntityManager may require mapping adjustments

However: premature configuration is the root of (all) evil. Most of the Java EE projects come without any configuration or XML and they fully rely on conventions "salted" with only a few annotations.


NEW dates, new workshop: Java EE 7 Workshops: Bootstrap, Effective, Architectures, JavaScript Bootstrap and HTML 5 December, 7th-11th
Online workshop: Java EE 7 Bootstrap

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

Java EE 7 + Thin WARs + Docker = Great Productivity

Java EE application servers separate the stable infrastructure from application code. Running Java EE applications (WildFly in the following screencast) on docker containers can significantly speed-up your build and start times. You only have to build what varies and not the whole infrastructure.

In the following screencast I'm running docker and the IDE on the same machine. In practice the server and development environments are separated what should result in even more dramatic results:

Thank you for watching, feedback is highly welcome!

See also other screencasts at:http://www.youtube.com/user/bienadam.

See you at Java EE Workshops at Munich Airport, Terminal 2 and particularly at Java EE 7 Microservices.


NEW dates, new workshop: Java EE 7 Workshops: Bootstrap, Effective, Architectures, JavaScript Bootstrap and HTML 5 December, 7th-11th
Online workshop: Java EE 7 Bootstrap

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

The Inevitability of Microservices With Java EE--An Interview At Devoxx.pl

Either you are lucky and you don't need them, or they just occur. A 7 mins interview about microservices at devoxx.pl:

Big thanks to lucy for the nice interview and great questions!

See you at Java EE Workshops at Munich Airport, Terminal 2 and particularly at Java EE 7 Microservices.


NEW dates, new workshop: Java EE 7 Workshops: Bootstrap, Effective, Architectures, JavaScript Bootstrap and HTML 5 December, 7th-11th
Online workshop: Java EE 7 Bootstrap

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

Persisting An Annotation-Less POJO With JPA

To persist an annotation-less POJO with JPA:


public class Workshop {

    private long id;
    private String name;

    public Workshop() {
    }

    public Workshop(long id, String name) {
        this.id = id;
        this.name = name;
    }
}


you will have to provide the lacking metadata in a XML descriptor instead of annotations:

<?xml version="1.0" encoding="UTF-8" ?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
                 version="2.0">
    <entity class="com.airhacks.jpa.orm.Workshop">
        <table name="T_WORKSHOP"/>
        <attributes>
            <id name="id">
                <generated-value strategy="AUTO"/>
            </id>
            <basic name="name">
                <column name="w_name" length="100"/>
            </basic>
        </attributes>
    </entity>
</entity-mappings>

The persistence.xml file has to point to the location of the orm.xml:


<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
                http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="it" transaction-type="RESOURCE_LOCAL">

        <mapping-file>META-INF/orm.xml</mapping-file>

        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="javax.persistence.jdbc.url"
                      value="jdbc:derby:./airhacksDB;create=true"/>
            <property name="javax.persistence.jdbc.driver"
                      value="org.apache.derby.jdbc.EmbeddedDriver"/>
            <property name="javax.persistence.schema-generation.database.action"
                      value="drop-and-create"/>
        </properties>
    </persistence-unit>
</persistence>

Now an annotation-less POJO can be stored using JPA:


import com.airhacks.rulz.em.EntityManagerProvider;
import org.junit.Rule;
import org.junit.Test;

public class WorkshopIT {

    @Rule
    public EntityManagerProvider provider = EntityManagerProvider.persistenceUnit("it");

    @Test
    public void crud() {
        provider.tx().begin();
        provider.em().merge(new Workshop());
        provider.tx().commit();
    }

}

The idea for this post came from 16th airhacks.tv Q&A. Big thanks to Eddy Young for asking this question.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting


NEW dates, new workshop: Java EE 7 Workshops: Bootstrap, Effective, Architectures, JavaScript Bootstrap and HTML 5 December, 7th-11th
Online workshop: Java EE 7 Bootstrap

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

A Built-In Java HttpServer

The com.sun.net.httpserver package was introduced with JDK 1.6 and enables the implementation of embedded HTTP servers:


import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

//...

String payload = "duke";
HttpServer server = HttpServer.create(new InetSocketAddress(4250), 0);
HttpContext context = server.createContext("/java");
context.setHandler((he) -> {
	he.sendResponseHeaders(200, payload.getBytes().length);
	final OutputStream output = he.getResponseBody();
	output.write(payload.getBytes());
	output.flush();
	he.close();
});
server.start();

Test: curl -i http://localhost:4250/java returns:


HTTP/1.1 200 OK
Date: Thu, 09 Jul 2015 02:48:37 GMT
Content-length: 4

duke%    

Warning: The packages com.sun.* are not part of the supported, public interface and may even disappear in upcoming Java releases.


NEW dates, new workshop: Java EE 7 Workshops: Bootstrap, Effective, Architectures, JavaScript Bootstrap and HTML 5 December, 7th-11th
Online workshop: Java EE 7 Bootstrap

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

Spring and Java EE 7, MVVM, Crosscutting BCE, C#, Jenkins or 20+ Answers at 16th Airhacks.tv

Answering the 20+ questions during the 16th airhacks.tv:

Special thanks to the ~90 live attendees and the questions from twitter. Any questions left?

Ask now: https://gist.github.com/AdamBien/a0fedea018c96f43f33a and see you at August, 3rd at 6 pm CET.

See also other screencasts at: http://tv.adam-bien.com or subscribe to http://www.youtube.com/user/bienadam.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting


NEW dates, new workshop: Java EE 7 Workshops: Bootstrap, Effective, Architectures, JavaScript Bootstrap and HTML 5 December, 7th-11th
Online workshop: Java EE 7 Bootstrap

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

More Questions Than Ever: The 16th Airhacks Live Questions And Answers

Questions for the 16th airhacks.tv at July, 6th 2015 at 6.PM. CET: http://www.ustream.tv/channel/adambien (no reqistrations, no obligations, just ask questions and watch :-)):

  1. Do you see JavaScript frameworks in your work yet? Do you see MVVM becoming popular? [Michael K.]

  2. You mentioned in an earlier video the BCE package structure. For business-cases, this is really straight forward and a good structure.

    But there are many concerns, which does not really fit in this structure (sort of cross-concern), and because of this I have the question: Where to put the following concerns/classes:

    ResourceLocator (für REST-SubResources) bzw. AbstractResources

    (for functionality, which every resource needs (like @Context definitions))

    DateUtil? / MailService?

    AbstractEntity

    ApplicationConfiguration/JaxRSConfig

    REST-Adapter/Interceptoren/Filter/Mapper

    Tracing mit LoggerExposer?

    ValidationController / Validation-Annotations (which do not belong

    to a concrete domain-object, but is rather used for any validation) [Ulrich C.]

  3. Is it ok to use DTO in a REST-method for request/response-payload?

    I would argue, that the DTO for the REST-method would separate the domain from a technical interface (REST). In addition, there is the possibility to version the interface (DTO) independently from the domain objects. Furthermore, there are some properties, which needs to be send via REST-interface, which are not needed in the domain objects. [Ulrich C.]

  4. I’m 21 years old , and i’m at 3rd year studying Computer Science. At the moment i’m creating some apps in Java and more specially in Android , i like the server side applications too.

    What i have seen so far is that Java is very powerful but we must always look at future.

    By that i mean C# with mono-project.com you can write the truly write once run everywhere that Java tried to offer.

    So i’m asking the Java guru if i should change to C# ?

    Also one more question , for next month’s Q&A : How annotations are useful ? Explain few of them.

    Thanks in advance and sorry for your time. [Giorgos]

  5. I have long been a fan of JDO and welcomed JPA. Using annotations it is very easy to persist objects. However, there are very few examples to be found about how to persist third-party objects (assuming said objects provide getters and setters that will not change). I am thinking that using a wrapper around the objects would be one way to go, but I would like to hear how you would approach this. An example would be great, too. [Eddy]

  6. Which cdi annotations are available in jsp? I want to use conversations coped to design wizard form. TY @8indaas

  7. Where would you put interceptors ?

    By definition they are “cross-cutting”.

    In the project I am currently doing I have the boundary, control and entity packages for each business “component”. Because of the cross-cutting nature of interceptors I created a fourth package currently named “interceptors”. I know ! That’s technical like “ejb” and “jsf” ! I thought about putting it in a control package. But the control package of which business component ? Just choosing at random a component seems contrary to the “cross-cutting” nature of interceptors. It would also introduce unwanted dependencies at the component
    level. Your insight on this would be much appreciated.

    Ronald

  8. could you please show how to Unit-test a boundary utilizing other @Stateless and @Inject (CDI) objects? What exactly do i need to test it fastly without having Arquillian in place?A simple example would be very helpful. Karsten

  9. Is there a way to have dynamic finders in JPA like Grails or Rails? Any plans to include this feature on the new MVC framework? Antonio

  10. What’s your reaction to this post from Juergen Hoeller: https://spring.io/blog/2015/06/04/happy-second-birthday-java-ee-7-how-is-it-going-in-production Remko

  11. This one might be a little off topic but I figured its worth a try asking. How do you go about setting up a datasource in wildfly that talks to a mysql server via ssl. I have the mysql server’s cert as well as a client key/cert combo. Brett

  12. I have question related to cooperation with JavaScript in one war. I would like to make a simple app using AngularJS but the structure of this project not directly match to the maven project so I found that I can use yeoman-maven-plugin and everything started work fine but then maven build takes too much time. I think that my approach is a little bit too much complicated :) So can you tell me how you do this, I will be grateful. Sebastian

  13. I have one more question. How to test two microservices where one communicates with the second.via REST. Exactly I wonder which interfaces should I mocked. Right now (we don’t have exactly microesrvices :)) I test both applications separately. Is it enough? Someone can for example change interface - I know that this is a strange reason but can happen :) Sebastian

  14. Question 1 : is it possible build web application MVC1 ( ozark ) with JAVAEE7 ? is it enough matured currently for large scale web application ?

    Question 2 : in JPA based app. I am facing some problem in

    em.mergeI().—————— transaction related problem.

    to overcome this problem i am use em.createNativeQuery (“update into”).

    please give comments : is it recommend write way ?

    Question 3 : what is the best practice primary key generation for large scale financial application ? (for jpa)

    a) auto-increment / not auto-increment ?

    b) table / sequence strategy ?

    Question 4 : how to do audit in JPA ? masumcse1

  15. Could you suggest how to organize CI process with jenkins and docker. I have a set of the java ee apps and for each of them I configured docker. So, I want to use jenkins to run integration tests and then rebuild image and rerun container for each application.

    As I understood the most straightforward way is to use separate VM for CI with preinstalled docker and jenkins on localhost. So, Jenkins tracks changes, updates source, then runs IT via maven and then reruns containers on localhost.

    But docker has official image for jenkins and I remember that you use it. If you run jenkins in docker container, how do you organize access to parent host for running IT, rerunning containers with apps? Or do you use docker in docker approach? Here is an example https://github.com/jpetazzo/dind Or maybe another way …. I’m really confused :) Andrii

  16. Can you provide an example of how to send text to cell phone from web application? Some sites provide an authorization code to cell phone as part of authentication. Patrick

  17. When using bce and jsf where do you place your backing beans? team4rk

Any questions left? Write a comment, edit: https://gist.github.com/AdamBien/ee8565840092cc7f39ab or ask live: https://twitter.com/AdamBien.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting


NEW dates, new workshop: Java EE 7 Workshops: Bootstrap, Effective, Architectures, JavaScript Bootstrap and HTML 5 December, 7th-11th
Online workshop: Java EE 7 Bootstrap

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

From javax.json.JsonObject To byte[] And Back

Enjoy self-explanatory, Java EE 7 code :-):


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonWriter;

//...
   JsonObject deserialize(byte[] content) throws IOException {
        try (ByteArrayInputStream bais = new ByteArrayInputStream(content);
             JsonReader reader = Json.createReader(bais)) {
            return reader.readObject();
        }
    }

  byte[] serialize(JsonObject object) throws IOException {
        try (ByteArrayOutputStream oos = new ByteArrayOutputStream(); 
		     JsonWriter writer = Json.createWriter(oos)) {
            writer.writeObject(object);
            writer.close();
            oos.flush();
            return oos.toByteArray();
        }
    }


//...

    @Test
    public void reserialize() throws IOException {
        JsonObject expected = Json.createObjectBuilder().
                add("name", "duke").
                build();
        byte[] serialized = serialize(expected);
        JsonObject actual = deserialize(serialized);
        assertNotSame(actual, expected);
        assertThat(actual, is(expected));
    }

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting


NEW dates, new workshop: Java EE 7 Workshops: Bootstrap, Effective, Architectures, JavaScript Bootstrap and HTML 5 December, 7th-11th
Online workshop: Java EE 7 Bootstrap

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

realworldpatterns.com
...the last 150 posts
...the last 10 comments
License