10 May 2016

JPA links (updated)

Reference implementation.

Official documentation:

Others:
Providers often have good JPA documentation as well. Might include extensions (and JDO stuff) though:

Specific topics:
Background:

    9 May 2016

    JPA: Composite Primary Key with Foreign Keys



     
    Entity for the ProductSales Table:
    package com.example.model;
    
    import javax.persistence.*;
    
    @Entity
    @IdClass(ProductSalesPK.class)
    public class ProductSales {
    
     @Column(name = "QUANTITY")
     private int quantity_sold;
    
     @Id
     @ManyToOne
     @JoinColumn(name = "sales_id")
     private Sales sales;
    
     @Id
     @ManyToOne
     @JoinColumn(name = "product_id")
     private Product product;
    
     public ProductSales() {
     }
    
     public ProductSales(Sales sales, Product product, int quantity_sold) {
      this.sales = sales;
      this.product = product;
      this.quantity_sold = quantity_sold;
     }
    
     public Product getProduct() {
      return product;
     }
    
     public Sales getSales() {
      return sales;
     }
    
     public void setProduct(Product product) {
      this.product = product;
     }
    
     public void setSales(Sales sales) {
      this.sales = sales;
     }
    
     public int getQuantity_sold() {
      return quantity_sold;
     }
    
     public void setQuantity_sold(int quantity_sold) {
      this.quantity_sold = quantity_sold;
     }
    
    }
    
    ProductSalesPK Id class:

    package com.example.model;
    
    import java.util.Objects;
    
    public class ProductSalesPK {
        private int sales;
        private String product;
    
     public ProductSalesPK(int sales_id, String product_id) {
      this.sales = sales_id;
      this.product = product_id;
     }
    
     @Override
     public int hashCode() {
      int hash = 5;
      hash = 83 * hash + this.sales;
      hash = 83 * hash + Objects.hashCode(this.product);
      return hash;
     }
    
     @Override
     public boolean equals(Object obj) {
      if (obj == null) {
       return false;
      }
      if (getClass() != obj.getClass()) {
       return false;
      }
      final ProductSalesPK other = (ProductSalesPK) obj;
      if (this.sales != other.sales) {
       return false;
      }
      if (!Objects.equals(this.product, other.product)) {
       return false;
      }
      return true;
     } 
     
    }
    

    5 May 2016

    Callable ManagedTaskListener

      class Japavapa implements Callable, ManagedTask, ManagedTaskListener {
    
        String word;
        LocalTime submit;
    
        public Japavapa(String word) {
          this.word = word;
        }
    
        public String toString() {
          return ":P " + word;
        }
    
        @Override
        public String call() throws Exception {
          Random rand = new Random();
          Thread.currentThread().sleep(rand.nextInt(1000));
          Matcher match = Pattern.compile("([AEIOUYaeiouy]+)").matcher(word);
          return match.find() ? match.replaceAll(match.group(1) + "p" + match.group(1)) : word;
        }
    
        @Override
        public ManagedTaskListener getManagedTaskListener() {
          return this;
        }
    
        @Override
        public Map<String, String> getExecutionProperties() {
          return null;
        }
    
        @Override
        public void taskSubmitted(Future<?> future, ManagedExecutorService executor, Object task) {
          submit = LocalTime.now();
          logger.info("SUBMIT " + task
            + " AT " + submit 
            + " ON " + executor);
        }
    
        @Override
        public void taskAborted(Future<?> future, ManagedExecutorService executor, Object task, Throwable exception) {
          logger.info("ABORTED " + task
            + " AFTER " + Duration.between(submit, LocalTime.now()).toMillis()
            + "ms ON " + Thread.currentThread().getName());
        }
    
        @Override
        public void taskDone(Future<?> future, ManagedExecutorService executor, Object task, Throwable exception) {
          logger.info("DONE " + task
            + " AFTER " + Duration.between(submit, LocalTime.now()).toMillis() + "ms");
        }
    
        @Override
        public void taskStarting(Future<?> future, ManagedExecutorService executor, Object task) {
          logger.info("STARTING " + task
            + " AFTER " + Duration.between(submit, LocalTime.now()).toMillis()
            + "ms ON " + Thread.currentThread().getName());
        }
    
      }
    

    30 April 2016

    Java SE version history (updated)

    Version Name JSR Release Major new features
    9 2016 JSR 294: modular JDK (Jigsaw)
    8 337 3/2014 JSR 335: lambda expressions
    Collections Stream Framework
    JSR 310: Date and Time API
    Compact profiles
    JSR 308: annotations outside declarations (on usage)
    7 Dolphin 336 7/2011 language (project coin): switch on strings, multi catch, try with autoclosing resources, empty generics (diamond operator), binary literal, underscores in numbers NIO.2 file handling
    Fork/Join concurrency
    JAX-WS 2.2 (SOAP 1.2, WS-I 2.0, metro 2.0)
    Detailed overview
    6 Mustang 270 12/2006 JSR 223: scripting language support
    JSR 224: JAX-WS2.0 (metro 1.x)
    JSR 221: JDBC 4 (driver autoloading))
    Perfomance enhancements in synchronisation and garbage collection
    5 Tiger 176 9/2004 language (JSR 201): Enumerations, autoboxing, enhanced for loop, static import, vararg
    JSR 175: Annotations
    JSR 14: Generics
    java.util.concurrent
    java.util.Scanner
    RMI automatic stub generation
    1.4 Merlin 59 2/2002 language: assert
    regular expressions
    JSR 51: NIO
    JSR 47: java.util.logging
    JSR 54: JDBC 3 (metadata API, autogenerated keys, transaction savepoints, multiple || resultsets/statement)
    security and cryptography
    1.3 Kestrel 5/2000 HotSpot JVM
    RMI/CORBA support
    JNDI
    1.2 Playground 12/1998 Collections
    Swing
    JIT compiler
    Browser plugin
    JDBC 2.1 (datasources, distributed transactions, connection pooling,RowSet, ResultSet backscrolling and updating )
    1.1 2/1997 AWT events reorganisation
    inner classes
    JavaBeans
    JDBC
    RMI
    reflection
    1.0 1/1996
    Here's an overview of Java EE versions

    27 April 2016

    NetBeans hints (edit)

    Your first NetBeans project
    1. On the start page click the Learn & Discover tab
    2. Under Demo's and Tutorials select Java SE applications
    3. Start the Java Quick Start Tutorial 
    NetBeans 7.4 Developer Guide
    If you're searching how to do someting in netbeans just type it in the ... search box, it will not only search in your project,  but also in the online help.
    Keyboard shortcuts
    • view, search & change shortcuts: tools => options => keymap
      • You can set the keymap to a profile from another IDE (Eclipse, IntelliJ...) here as well.
    • help => keyboard shortcuts card. The pdf that is shown, lives in
      netbeansInstallDir
      /nb/shortcuts.pdf. 
    • Some additional useful shortcuts:
      • Go to
        • to definition: CTRL click
          • to implementation: CTRL ALT click
      • Edit
        • Code completion
          • autocomplete popup (+ javadoc): CTRL SPACE
          • javadoc inline popup: CTRL SHIFT SPACE
            • ALT F1 to see in browse
            • Netbeans bundles plenty of javadoc you can browse supplied javadoc for your project libraries from help>Javadoc references
          • complete to recently typed word: CTRL k
        • Add semicolon at end of line:  CTRL ;
        • Add new line below + go there: SHIFT ENTER
      • View
        • fold/unfold code: CTRL –/+
        • members/herarchy of current selection: CTRL/ALT SHIFT F12
        • zoom: ALT + mousewheel up/down 
        • editor only: CTRL SHIFT ENTER (>= 7.4)
    Running code
    • After you ran a program, and corrected some errors Rerun using the >> buttons.

    • The lighter double arrows below allow you to rerun with different parameters. You can change the arguments you run with in the Ant properties window.
     
    • Similar options are available for (individual) tests.
      • You can also launch an individual test by  positioning the cursor in the method and selecting "Run focused test" from the right click menu. 


    Samples
    Netbeans comes with plenty of sample projects for you to explore

    HTTP Monitor

    The server side monitor is enabled by default for Tomcat and can be enabled in the properties of GlassFish. You may have to undeploy/redeploy your webapp for the monitor to show up.
    When the server receives an HTTP request, NetBeans will show a window with all request details. It extracts all parameters and stuff for you, but does not show the raw bodies of POST requests. It does not show responses either.
    There is also a client monitor. If you use the internal browser (or the NetBeans Chrome plugin) you can use Window > Web > Network Monitor (NetBeans >= 7.4). It does not show all client side traffic but is targeted at in-page initiated traffic (AJAX, websockets) and failed requests.

    19 April 2016

    Java EE Patterns (edit)


    • Numbers on the arrows indicate a possible call sequence in a request. (thanks for the hint Nishant) 
    • patterns
      • Front Controller: initial point of contact for handling all related requests. The Front Controller centralizes control logic that might otherwise be duplicated, and manages the key request handling activities.
      • Transfer Object: carries multiple data elements across a tier
      • Transfer Object Assembler:  builds an application model as a composite Transfer Object. The Transfer Object Assembler aggregates multiple Transfer Objects from various business components and services, and returns it to the client. 
      • Persistent Domain Object: Rich domain object, ie. having rich behavior/bus.logic and persistent 
      • Web Service Broker: exposes and brokers one or more services using XML and web protocols.
        • The Web Service Broker can be generalised to a Protocol Broker.
      •  Service Facade: encapsulates business-tier components and exposes a coarse-grained service to remote clients. Clients access a Service Fa├žade instead of accessing business components directly. 
      •  Service: Fine-grained, reusable logic in an EJB with local access only, product of decomposition
      • Data Access Object: abstracts and encapsulates all access to the persistent store. The Data Access Object manages the connection with the data source to obtain and store data. 
      • Asynchronous Resource Integrator: Invocation of a Service from a Message-Driven Bean (invoked by a messaging system via JMS)
      • Payload extractor: factor out the (reusable) type checking and error handling for a MDB message into a reusable interceptor; poison messages moved by the interceptor to a “dead letter queue” via a stateless EJB using the JMS API
      •  Resource Binder: put a custom resource into JNDI using a @Singleton with @Startup and the JNDI API (Context.(re)bind()).

    17 April 2016

    Dozer DTO assembler (edit)

    Dozer is a nice little object mapper. It moves data from one object to another.

    Dozer can be used as a generic Data Transfer Object assembler. You specify your mappings in an XML file. By default it copies data to properties with the same names, unless you add specific field mappings.

     <mapping>
       <class-a>z.Original</class-a>
       <class-b>a.Kloon</class-b>
          <field>
             <a>identity</a>
             <b>uid</b>
          </field>
     </mapping>
    
    
    Next you call dozer in your code to move your data:
    public Kloon getDto (Original o) {
      return dozerMapper.map(o, Kloon.class);
    }
    Dozer can reverse map from class-b to class-a as well. There is an annotation based mapping mechanism which works well for simple cases.