## page was renamed from JEE
= JEE =
Java Platform, Enterprise Edition

== JEE 7 Tutorial ==
https://docs.oracle.com/javaee/7/tutorial/index.html

Key features: https://blogs.oracle.com/arungupta/entry/java_ee_7_key_features

Reference implementation: https://glassfish.java.net/getstarted.html

Java EE7 APIs: https://docs.oracle.com/javaee/7/tutorial/overview007.htm

=== Install Glassfish 4.1 ===
https://glassfish.java.net/download.html

http://download.java.net/glassfish/4.1.1/release/glassfish-4.1.1.zip

JDK 8 u20 or above is recommended for GlassFish 4.1. 

 * cd /tmp
 * wget http://download.oracle.com/otn-pub/java/jdk/8u25-b17/jdk-8u25-linux-x64.tar.gz
 * wget http://dlc.sun.com.edgesuite.net/glassfish/4.1/release/glassfish-4.1.zip
 * unzip glassfish-4.1.zip
 * tar xvzf jdk-8u25-linux-x64.tar.gz
 * mv jdk1.8.0_25/ /usr/java
 * mv glassfish4/ /opt/appsrv/
 * cd /usr/java/jdk1.8.0_25
 * chmod 555 * -R
 * /usr/java/jdk1.8.0_25/bin/java -version
 * cd /opt/appsrv/glassfish4/bin
 * JAVA_HOME=/usr/java/jdk1.8.0_25 AS_JAVA=/usr/java/jdk1.8.0_25 asadmin start-domain
 * http://localhost:4848/
 * asadmin change-admin-password
 * asadmin enable-secure-admin
 * asadmin stop-domain
 * asadmin start-domain


=== Install Glassfish 4.1 on FreeBSD 10.3 ===
 * pkg install glassfish-4.1
 * Add glassfish_enable="YES" in /etc/rc.conf.
 * pkg install elinks
 * elinks http://localhost:8080
 * cd /usr/local/glassfish-4.1/bin
 * ./asadmin change-admin-password
{{{
Enter admin user name [default: admin]>
Enter the admin password>    #is empty !!!!
Enter the new admin password>
Enter the new admin password again>
Command change-admin-password executed successfully.
}}}
 * ./asadmin enable-secure-admin
{{{
Enter admin user name>  admin
Enter admin password for user "admin">
You must restart all running servers for the change in secure admin to take effect.
Command enable-secure-admin executed successfully.
}}}
 * /usr/local/etc/rc.d/glassfish restart
 * pkg install mariadb101-server-10.1.14 # mariadb
 * vi /etc/rc.conf # mysql_enable="YES"
 * cd /usr/local/etc/rc.d
 * ./mysql-server start
 * mysql_secure_installation # set mysql root pass ...
{{{
mysql -u root -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 10.1.14-MariaDB FreeBSD Ports

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> create database mysqljdbc;
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]> create user 'mysqljdbc'@'%' identified by '12345678';
Query OK, 0 rows affected (0.01 sec)

MariaDB [(none)]> GRANT ALL PRIVILEGES ON mysqljdbc.* TO 'mysqljdbc'@'%';
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> exit
Bye

}}}
 * cd /usr/local/glassfish-4.1/glassfish/domains/domain1/lib
 * wget http://central.maven.org/maven2/org/mariadb/jdbc/mariadb-java-client/1.5.2/mariadb-java-client-1.5.2.jar
 * jms resources, destination resources 
 * JNDI name: jms/Queuex
 * physical destination name: Queuex
 * JMS connection factory
 * type: javax.jms.ConnectionFactory
 * JNDI name: jms/ConnectionFactory
 * JDBC connection pool 
 * Pool name: MariaDBPool 	
 * resource type: javax.sql.DataSource 	
 * Datasource class name: org.mariadb.jdbc.MariaDbDataSource
 * Connection Validation: Required 
 * Validation method meta-data 
 * user mysqljdbc
 * userName mysqljdbc
 * databaseName mysqljdbc
 * PortNumber 3306
 * Password 12345678
 * ServerName localhost 
 * LoginTimeout 0
 * JDBC resource 
 * jndi name: jdbc/mysql 			
 * connection pool: MariaDBPool

== Docker Ubuntu image install ==
 * docker pull ubuntu
 * docker create --name containerx -p 1022:22 -p 1848:4848 -p 1080:8080 ubuntu 
 * docker start containerx
 * docker exec -t -i containerx 
 * apt-get update
 * apt-get install tzdata-java openjdk-7-jdk wget unzip
 * java
 * java -version
 * apt-get install 
 * cd /tmp
 * wget http://dlc.sun.com.edgesuite.net/glassfish/4.1/release/glassfish-4.1.zip
 * unzip glassfish-4.1.zip
 * mkdir -p /opt/appsrv
 * mv glassfish4/ /opt/appsrv/
 * cd /opt/appsrv/glassfish4/
 * bin/asadmin start-domain
 * bin/asadmin change-admin-password
 * bin/asadmin enable-secure-admin
 * bin/asadmin stop-domain
 * bin/asadmin start-domain
 * exit

https://github.com/sebsto/docker-glassfish4/blob/master/Dockerfile

== JEE6 EJB 3.1 sample for Glassfish 3.1.2.2 and JBoss 7.1.1 (EJB + JPA + Web Service + MDB + Schedule) ==
'''Structure:'''
{{{
.
|-- pom.xml
|-- src
|   `-- main
|       |-- java
|       |   `-- org
|       |       `-- allowed
|       |           `-- bitarus
|       |               |-- MessageEntity.java
|       |               |-- ScheduleRemote.java
|       |               |-- ScheduleWS.java
|       |               |-- Scheduler.java
|       |               `-- TestMDB.java
|       `-- resources
|           `-- META-INF
|               |-- ejb-jar.xml
|               `-- persistence.xml
}}}

'''pom.xml'''
{{{#!highlight xml
<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>org.allowed.bitarus</groupId>
  <artifactId>ejbjee6</artifactId>
  <version>0.0.1</version>
  <packaging>ejb</packaging> 
  <dependencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>6.0</version>
        <scope>provided</scope>
    </dependency>    
  </dependencies>
</project>
<!--
mkdir -p src/main/java/org/allowed/bitarus
touch src/main/java/org/allowed/bitarus/Scheduler.java
touch src/main/java/org/allowed/bitarus/ScheduleRemote.java
touch src/main/java/org/allowed/bitarus/ScheduleWS.java
touch src/main/java/org/allowed/bitarus/TestMDB.java
touch src/main/java/org/allowed/bitarus/MessageEntity.java
mkdir -p src/main/resources/META-INF
touch src/main/resources/META-INF/ejb-jar.xml
touch src/main/resources/META-INF/persistence.xml

mvn clean compile package
# Tested in GlassFish Server Open Source Edition 3.1.2.2 (build 5)
-->
}}}

'''ejb-jar.xml'''
{{{#!highlight xml
<ejb-jar>
</ejb-jar>
}}}

'''persistence.xml'''
{{{#!highlight xml
<persistence>
    <persistence-unit name="puMysql" transaction-type="JTA">
        <jta-data-source>jdbc/mysql</jta-data-source>
        <properties>
            <!--property name="eclipselink.ddl-generation" value="create-or-extend-tables"/-->    
            <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
            <property name="eclipselink.ddl-generation.output-mode" value="both"/>
            <property name="eclipselink.target-database" value="MySQL"/>
        </properties>
    </persistence-unit>
</persistence>
<!-- 
Copy mysql-connector-java-5.1.30-bin.jar
cp mysql-connector-java-5.1.30-bin.jar /opt/glassfish-3.1.2.2/glassfish/domains/domain1/lib/
mysql -u root -p
create database mysqljdbc;
create user 'mysqljdbc'@'%' identified by '12345678';
GRANT ALL PRIVILEGES ON mysqljdbc.* TO 'mysqljdbc'@'%';
mysql -u mysqljdbc -p

JDBC Connection Pool
  Name: MySQLPool
  Resource type: javax.sql.DataSource
  Datasource class name: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
  Additional properties
  portNumber: 3306
  databaseName: mysqljdbc
  user: mysqljdbc
  password: 12345678
  serverName: 127.0.0.1

JDBC Resource:
  New, 
  Pool Name: MySQLPool
  JNDI name: jdbc/mysql
-->
}}}


'''Scheduler.java'''
{{{#!highlight java
package org.allowed.bitarus;
import javax.ejb.Singleton;
import javax.ejb.Schedule;
import javax.ejb.ScheduleExpression;
import javax.annotation.Resource;
import javax.ejb.Timeout;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.ejb.Timer;
import javax.annotation.PostConstruct;
import javax.ejb.Startup;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Connection;
import javax.jms.Session;
import javax.jms.MessageProducer;
import javax.jms.TextMessage;
@Singleton
@Startup
public class Scheduler {
    @Resource(mappedName="jms/ConnectionFactory")
    private ConnectionFactory connectionFactory;
    @Resource(mappedName="jms/Queuex")
    private Queue queue;    
    
    @Resource
    private TimerService timerService;

    @PostConstruct
    private void postConstruct() {    
        TimerConfig config = new TimerConfig("OneMinutePassed", false);
        ScheduleExpression se = new ScheduleExpression();
        se.minute("*");
        se.hour("*");
        timerService.createCalendarTimer(se, config);
    }

    public String addSchedule(String second,String minute,String hour,String info){
        TimerConfig config = new TimerConfig(info, false);
        ScheduleExpression se = new ScheduleExpression();
        se.second(second);
        se.minute(minute);
        se.hour(hour);
        timerService.createCalendarTimer(se, config);        
        return "Added " + info;
    }    
    
    @Schedule(minute="*/5", hour="*")
    private void eachFiveMinutes(){
        System.out.println("Called each five minute");
    }    

    @Timeout
    public void timeout(Timer timer) {
        if ("OneMinutePassed".equals(timer.getInfo())) {    
            System.out.println("OneMinutePassed !!!");
            /*for(Timer t : timerService.getTimers() ){
                System.out.println(">>> "+ t.getInfo() );
            }*/
        }else{
            System.out.println("!!! "+ timer.getInfo() );
            // send jms message
            try{
                Connection connection = connectionFactory.createConnection();
                Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
                MessageProducer mp = session.createProducer(queue);
                TextMessage message = session.createTextMessage();
                message.setText( timer.getInfo().toString() );
                mp.send(message);
                mp.close();
                session.close();
                connection.close();                
            }catch(Exception ex){ ex.printStackTrace(); }
        }        
    }    
}
}}}

'''ScheduleRemote.java'''
{{{#!highlight java
package org.allowed.bitarus;
import javax.ejb.Remote;

@Remote
public interface ScheduleRemote{
    String addSchedule(String second,String minute,String hour,String info);
}
}}}

'''ScheduleWS.java'''
{{{#!highlight java
package org.allowed.bitarus;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.ejb.ScheduleExpression;
import javax.annotation.Resource;
import javax.ejb.TimerService;
import javax.ejb.TimerConfig;
import javax.ejb.EJB;
@Stateless
@WebService
public class ScheduleWS implements ScheduleRemote{
    @Resource
    private TimerService timerService;    
    @EJB
    Scheduler sc;
    
    @WebMethod
    public String addSchedule(String second,String minute,String hour,String info){
        return sc.addSchedule(second, minute, hour, info);
    }
}
}}}

'''TestMDB.java'''
{{{#!highlight java
package org.allowed.bitarus;

import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.TextMessage;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
@MessageDriven(mappedName="jms/Queuex")
public class TestMDB{
    @PersistenceContext(unitName="puMysql")
    EntityManager em;
    
    public void onMessage(Message inMessage) {
        try{
            String text = ( (TextMessage) inMessage).getText() ;
            System.out.println( text );     
            MessageEntity me = new MessageEntity();
            me.setMessage( text  );
            me.setCreationDate( new java.util.Date() );
            em.persist(me);
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}
}}}

'''MessageEntity.java'''
{{{#!highlight java
import java.util.Date;
import javax.persistence.Id;
import javax.persistence.Entity;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.TemporalType;
import javax.persistence.Temporal;
@Entity
public class MessageEntity{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    // @GeneratedValue(strategy = GenerationType.AUTO) 
    // @OneToMany 
    // @NamedQueries( { @NamedQuery(name="MessageEntity.byId",query="Select me From MessageEntity e where e.id = :id;") , @NamedQuery()  } )
    // JPQL Select me From MessageEntity e where e.id = :id;
    // Query q = em.createQuery("Select me From MessageEntity e where e.id = :id;");
    // Query q = em.createNamedQuery("MessageEntity.byId");
    // q.setParameter("id",12);
    // List<MessageEntity> res = q.getResultList ();
    private long id;
    @Column
    @Temporal(TemporalType.TIMESTAMP) 
    private Date creationDate;
    @Column
    private String message;
    
    public long getId(){return this.id;}
    public void setId(long id){ this.id=id;}

    public Date getCreationDate(){return this.creationDate;}
    public void setCreationDate(Date creationDate){ this.creationDate=creationDate;}
    
    public String getMessage(){return this.message;}
    public void setMessage(String message){ this.message=message;}        
}
}}}

== Glassfish OpenMQ standalone client ==
'''Structure'''
{{{
.
|-- pom.xml
|-- src
|   `-- main
|       `-- java
|           `-- org
|               `-- allowed
|                   `-- bitarus
|                       `-- JmsClient.java
}}}

'''pom.xml'''
{{{
<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>org.allowed.bitarus</groupId>
    <artifactId>jmsclient</artifactId>
    <version>0.0.1</version>
    <packaging>jar</packaging> 
    <dependencies>
        <dependency>
            <groupId>org.glassfish.mq</groupId>
            <artifactId>imq</artifactId>
            <version>5.1</version>
        </dependency>   
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>org.allowed.bitarus.JmsClient</mainClass>
                        </manifest>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id> 
                        <phase>package</phase> 
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>  
</project>
}}}

'''JmsClient.java'''
{{{#!highlight java
package org.allowed.bitarus;
import com.sun.messaging.ConnectionConfiguration;
import com.sun.messaging.ConnectionFactory;
import com.sun.messaging.Queue;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

public class JmsClient {
    
    public static void main( String[] args ) 
    {
        try{
            ConnectionFactory connFactory = new ConnectionFactory();
            connFactory.setProperty(ConnectionConfiguration.imqAddressList, "127.0.0.1:7676");
            Queue q = new Queue("Queuex");      
            Connection connection = connFactory.createConnection(); 
            System.out.println("After create connection");
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); 
            MessageProducer producer = session.createProducer(q); 
            Message message = session.createTextMessage("Bitarus test message");
            producer.send(message);
            producer.close();
            session.close();
            connection.close();
            System.out.println("After send message");
        }catch(Exception ex){
            ex.printStackTrace();             
        }
        
        System.out.println("End");
    }
}
}}}

=== Check OpenMQ MessageQueue state ===
 * cd /opt/glassfish-3.1.2.2/mq/bin
 * imqcmd list dst  # input the admin user and pass

=== Check used tcp ports by OpenMQ ===
 * nc openmqServer 7676
 * telnet openmqServer 7676

Should show in text the available ports, with 7676 on the list and other dynamic port with the text '''jms tcp normal''' next to it.
That dynamic port should also be added in NAT port forwarding if required together withport 7676.

== JMS message selector ==
[[ https://docs.oracle.com/cd/E19798-01/821-1841/bncer/index.html | JMS Message Selectors ]]

Filter queue messages based on a JMS property value.

[[ http://docs.oracle.com/javaee/6/api/javax/jms/Session.html#createConsumer(javax.jms.Destination, java.lang.String) | Session createConsumer ]]

Creates a MessageConsumer for the specified destination, using a message selector.
{{{#!highlight java
// on the producer
myMessage.setStringProperty("PropertyX", "teste");

// on the consumer to receive messages with the property PropertyX with value teste
sessionx.createConsumer(queuex,"PropertyX='teste'");
}}}

Message selector in a MessageDrivenBean
{{{#!highlight java
@MessageDriven(mappedName="jms/Queuex", activationConfig =  {
  @ActivationConfigProperty(propertyName = "messageSelector",propertyValue = "PropertyX='teste'")
})
}}}

From [[http://docs.oracle.com/javaee/5/api/javax/jms/Message.html | Message]]
{{{
A JMS message selector allows a client to specify, by header field references and property references, the messages it is interested in. Only messages whose header and property values match the selector are delivered.

A message selector matches a message if the selector evaluates to true when the message's header field values and property values are substituted for their corresponding identifiers in the selector.

Message header field references are restricted to JMSDeliveryMode, JMSPriority, JMSMessageID, JMSTimestamp, JMSCorrelationID, and JMSType. 

The following message selector selects messages with a message type of car and color of blue and weight greater than 2500 pounds:
"JMSType = 'car' AND color = 'blue' AND weight > 2500"
}}}

JMS header fields:
 * JMSDeliveryMode
 * JMSPriority 
 * JMSMessageID 
 * JMSTimestamp 
 * JMSCorrelationID 
 * JMSType