Saturday, December 19, 2015

JavaOne 2015 Session: EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples by Gohar

I have recently watched my friend Ahmed Nabil Gohar's session at JavaOne 2015. It's really a clear and straight to the point session. I'm sharing with you the sessions details (inluding the YouTube + the presentation downloadable link) as mentioned in his post.
Session ID: CON7535
Session Title: EJB 3.2/JPA 2.1 Best Practice with life examples (Download Link)
Session Type: Conference Session
Session Abstract:
This session’s speaker, an architect, discusses lessons learned from using JPA and EJB to support a high-volume, high-performance applications. These best practices don't only involve JPA/EJB but also its integration with other Java EE 7 technologies. They also include coding best practices, testing and production practices. The presentation focuses primarily on some Key concepts such as persistence context, lazy loading, caching, flushing, dirty checking, transaction and connection demarcation. This is a fast-paced presentation with many code samples. Categories covered include configuration, JPA, concurrency, performance tuning, exception handling and many more.

Friday, December 18, 2015

Creating JSF/CDI Maven project on Eclipse

While I was working on a JSF and CDI example, I thought it would be useful to mention the steps required to create JSF and CDI Maven project. You can find the bellow steps to do so.
Tools:
  • Eclipse Luna that's shipped with the M2E plugin by default. So no need to install the plugin yourself.
  • WildFlye 8.x.
1- Select from the main menu File->New->Other. Then select Maven->Maven Project.
2- Click the Next button and then check "Create a simple project (skip archetype selection)".
3- Write the Group Id and the Artifact Id then select Packaging as WAR.
4- Click the Finish button to create the project with the bellow structure displayed in the Navigator view.
5- As you can see there is no deployment descriptor file (web.xml) as there is no WEB-INF folder. Also by checking on the Project Facets (select the project then ALT+ENTER then choose from the left menu Project Facets), we can see that the version of the Dynamic Web Module is 2.5 and the JavaServer Faces is not selected. So it's time to do some configurations to our project.
6- Right click on the project name then Configure->Add JSF Capabilities. This will configure the project as JSF project and adds the WEB-INF with the web.xml and the faces-config.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 version="2.5">
 <display-name>JSFCDIMavenProject</display-name>
 <servlet>
  <servlet-name>Faces Servlet</servlet-name>
  <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>Faces Servlet</servlet-name>
  <url-pattern>/faces/*</url-pattern>
 </servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">

</faces-config>
7- Adding the necessary API's as dependencies to the pom.xml. Also, adding the maven-compiler-plugin with version 3.1. I have also pointed maven to use the Java compiler version 1.7. So here is the final 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>com.ithinkisink</groupId>
 <artifactId>JSFCDIMavenProject</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>war</packaging>

 <name>JSFCDIMavenProject Maven Webapp</name>

 <dependencies>
  <dependency>
   <groupId>javax.inject</groupId>
   <artifactId>javax.inject</artifactId>
   <version>1</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.faces</groupId>
   <artifactId>jsf-api</artifactId>
   <version>2.1</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.enterprise</groupId>
   <artifactId>cdi-api</artifactId>
   <version>1.0</version>
   <scope>provided</scope>
  </dependency>
 </dependencies>
 <build>
  <finalName>JSFCDIMavenProject</finalName>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>1.7</source>
     <target>1.7</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>
8- Now right click on the project name then choose Maven->Update Project to update the project with the newly added configurations.
9- The deployment descriptor (web,xml) has version 2.5 and we are pointing to the servlet 3.1 in our dependency. So as per Java EE 7XML schema, the namespace is changed to be http://xmlns.jcp.org/xml/ns/javaee/. This is the final web.xml after applying that change.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
 version="3.1">
 <display-name>JSFCDIMavenProject</display-name>
 <servlet>
  <servlet-name>Faces Servlet</servlet-name>
  <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>Faces Servlet</servlet-name>
  <url-pattern>/faces/*</url-pattern>
 </servlet-mapping>
</web-app>
10- Check again the Project Facets. You can change the Dynamic Web Module for the version 3.1 and the JavaServer Faces is checked with version 2.2 as per the version added in the dependencies.
11- The last configuration that is needed is enabling the CDI context. This could be done by creating an XML file named beans.xml and add it to the WEB-INF folder as the bellow one.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
  http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       bean-discovery-mode="all">
</beans>

12- Finally adding the project to WildFly and then starting the server. You will see in the Console view that WildFly started a service for the CDI deployment to the application.
I have pushed this stub project to my GitHub and you can find it through the bellow URL.
https://github.com/belalgalal/Blogging/tree/master/JSFCDIMavenProject

Tuesday, December 8, 2015

DynamicReports and JasperReports with JSF, Servlet and CDI

In this example, I will show how to integrate DynamicReport and JasperReports with Servlet and CDI.
Tools:
  • TIBCO Jaspersoft Studio-6.0.4.final.
  • Eclipse  Luna Service Release 2 (4.4.2).
  • WildFly 8.x application server.
This is a screenshot from the project hierarchy on Eclipse.

1- The pom.xml file contains the required dependencies for the Servlets + JSF + CDI + DynamicReports.
<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/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.ithinkisink</groupId>
 <artifactId>DynamicReportsWithJSFServletsAndCDI</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>DynamicReportsWithJSFServletsAndCDI Maven Webapp</name>

 <dependencies>
  <dependency>
   <groupId>javax.inject</groupId>
   <artifactId>javax.inject</artifactId>
   <version>1</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.faces</groupId>
   <artifactId>jsf-api</artifactId>
   <version>2.1</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.enterprise</groupId>
   <artifactId>cdi-api</artifactId>
   <version>1.0</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>net.sourceforge.dynamicreports</groupId>
    <artifactId>dynamicreports-core</artifactId>
    <version>4.0.0</version>
  </dependency>
 </dependencies>
 <build>
  <finalName>DynamicReportsWithJSFServletsAndCDI</finalName>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>1.7</source>
     <target>1.7</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>

2- Creating a simple JRXML template using the TIBCO Jaspersoft Studio containing an image that will pass its path dynamically as a parameter from the DynamicReportsManagedBean to the DynamicReports later on.
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.0.4.final using JasperReports Library version 6.0.4  -->
<!-- 2015-12-04T17:15:43 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Invoice" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="4eedbb89-b4f6-4469-9ab6-f642a1688cf7">
 <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
 <style name="Title" forecolor="#FFFFFF" fontName="Times New Roman" fontSize="50" isBold="false" pdfFontName="Times-Bold"/>
 <style name="SubTitle" forecolor="#CCCCCC" fontName="Times New Roman" fontSize="18" isBold="false" pdfFontName="Times-Roman"/>
 <style name="Column header" forecolor="#666666" fontName="Times New Roman" fontSize="14" isBold="true"/>
 <style name="Detail" mode="Transparent" fontName="Times New Roman"/>
 <style name="Row" mode="Transparent" fontName="Times New Roman" pdfFontName="Times-Roman">
  <conditionalStyle>
   <conditionExpression><![CDATA[$V{REPORT_COUNT}%2 == 0]]></conditionExpression>
   <style mode="Opaque" backcolor="#EEEFF0"/>
  </conditionalStyle>
 </style>
 <style name="Table">
  <box>
   <pen lineWidth="1.0" lineColor="#000000"/>
   <topPen lineWidth="1.0" lineColor="#000000"/>
   <leftPen lineWidth="1.0" lineColor="#000000"/>
   <bottomPen lineWidth="1.0" lineColor="#000000"/>
   <rightPen lineWidth="1.0" lineColor="#000000"/>
  </box>
 </style>
 <style name="Table_TH" mode="Opaque" backcolor="#FFFFFF">
  <box>
   <pen lineWidth="0.5" lineColor="#000000"/>
   <topPen lineWidth="0.5" lineColor="#000000"/>
   <leftPen lineWidth="0.5" lineColor="#000000"/>
   <bottomPen lineWidth="0.5" lineColor="#000000"/>
   <rightPen lineWidth="0.5" lineColor="#000000"/>
  </box>
 </style>
 <style name="Table_CH" mode="Opaque" backcolor="#CACED0">
  <box>
   <pen lineWidth="0.5" lineColor="#000000"/>
   <topPen lineWidth="0.5" lineColor="#000000"/>
   <leftPen lineWidth="0.5" lineColor="#000000"/>
   <bottomPen lineWidth="0.5" lineColor="#000000"/>
   <rightPen lineWidth="0.5" lineColor="#000000"/>
  </box>
 </style>
 <style name="Table_TD" mode="Opaque" backcolor="#FFFFFF">
  <box>
   <pen lineWidth="0.5" lineColor="#000000"/>
   <topPen lineWidth="0.5" lineColor="#000000"/>
   <leftPen lineWidth="0.5" lineColor="#000000"/>
   <bottomPen lineWidth="0.5" lineColor="#000000"/>
   <rightPen lineWidth="0.5" lineColor="#000000"/>
  </box>
  <conditionalStyle>
   <conditionExpression><![CDATA[$V{REPORT_COUNT}%2 == 0]]></conditionExpression>
   <style backcolor="#D8D8D8"/>
  </conditionalStyle>
 </style>
 <subDataset name="tableDataset" uuid="f13e6d36-5148-4ecc-bbe3-3035def80980">
  <queryString>
   <![CDATA[]]>
  </queryString>
 </subDataset>
 <parameter name="invoiceNo" class="java.lang.String"/>
 <parameter name="billingCompanyName" class="java.lang.String"/>
 <parameter name="billingCompanyAddress" class="java.lang.String"/>
 <parameter name="billingCompanyFirstState" class="java.lang.String"/>
 <parameter name="billingCompanySecondState" class="java.lang.String"/>
 <parameter name="shippingName" class="java.lang.String"/>
 <parameter name="shippingAddress" class="java.lang.String"/>
 <parameter name="shippingFirstState" class="java.lang.String"/>
 <parameter name="shippingSecondState" class="java.lang.String"/>
 <parameter name="IMAGE_PATH" class="java.lang.String"/>
 <queryString language="SQL">
  <![CDATA[]]>
 </queryString>
 <field name="itemNo" class="java.lang.String"/>
 <field name="description" class="java.lang.String"/>
 <field name="unitCost" class="java.lang.Double"/>
 <field name="quantity" class="java.lang.Integer"/>
 <group name="Gruppo1">
  <groupExpression><![CDATA[(int)($V{REPORT_COUNT}/15)]]></groupExpression>
  <groupHeader>
   <band/>
  </groupHeader>
  <groupFooter>
   <band>
    <property name="local_mesure_unitheight" value="pixel"/>
    <property name="com.jaspersoft.studio.unit.height" value="px"/>
   </band>
  </groupFooter>
 </group>
 <title>
  <band height="196" splitType="Stretch">
   <staticText>
    <reportElement x="0" y="90" width="84" height="25" uuid="57aed2b1-4f4e-40a3-a6ad-54dae8dd4c5a">
     <property name="local_mesure_unitheight" value="pixel"/>
     <property name="com.jaspersoft.studio.unit.height" value="px"/>
    </reportElement>
    <textElement>
     <font size="16" isBold="true"/>
    </textElement>
    <text><![CDATA[Bill to:]]></text>
   </staticText>
   <line>
    <reportElement x="0" y="80" width="556" height="1" uuid="806ce5df-1219-4876-ae0c-ca7405b1f246">
     <property name="local_mesure_unitheight" value="pixel"/>
     <property name="com.jaspersoft.studio.unit.height" value="px"/>
    </reportElement>
   </line>
   <staticText>
    <reportElement x="400" y="90" width="84" height="25" uuid="139ebe8d-25b0-411e-986c-270015400874">
     <property name="local_mesure_unitheight" value="pixel"/>
     <property name="com.jaspersoft.studio.unit.height" value="px"/>
    </reportElement>
    <textElement>
     <font size="16" isBold="true"/>
    </textElement>
    <text><![CDATA[Ship to:]]></text>
   </staticText>
   <staticText>
    <reportElement x="415" y="10" width="50" height="20" uuid="0f86baff-6386-4f3f-b3fe-2388707babe8"/>
    <box rightPadding="4"/>
    <textElement textAlignment="Right"/>
    <text><![CDATA[Date:]]></text>
   </staticText>
   <textField pattern="EEEEE dd MMMMM yyyy">
    <reportElement x="465" y="10" width="84" height="20" uuid="bb10dbe1-0a4f-4722-9953-c163b63cf979"/>
    <textFieldExpression><![CDATA[new java.util.Date()]]></textFieldExpression>
   </textField>
   <image hAlign="Center">
    <reportElement x="0" y="0" width="65" height="60" uuid="94883631-a913-43e2-b182-ab8d77d0181e"/>
    <imageExpression><![CDATA[$P{IMAGE_PATH} + "/invoice_logo.png"]]></imageExpression>
   </image>
   <textField pattern="EEEEE dd MMMMM yyyy">
    <reportElement x="465" y="30" width="84" height="20" uuid="3836ce65-eca3-4cad-a6de-b1818def0a2b"/>
    <textFieldExpression><![CDATA[$P{invoiceNo}]]></textFieldExpression>
   </textField>
   <staticText>
    <reportElement x="415" y="30" width="50" height="20" uuid="0b3f9342-da78-4cfa-9fc5-2301c4749678"/>
    <box rightPadding="4"/>
    <textElement textAlignment="Right"/>
    <text><![CDATA[Invoice #]]></text>
   </staticText>
   <staticText>
    <reportElement x="95" y="0" width="210" height="25" uuid="e622555d-198b-4ccd-a4a1-c59c53304058">
     <property name="local_mesure_unitheight" value="pixel"/>
     <property name="com.jaspersoft.studio.unit.height" value="px"/>
    </reportElement>
    <textElement>
     <font size="19" isBold="true"/>
    </textElement>
    <text><![CDATA[I think, I sink!]]></text>
   </staticText>
   <staticText>
    <reportElement x="95" y="55" width="205" height="15" uuid="b8cc42fd-b569-497d-834d-7e854040ad18"/>
    <text><![CDATA[+20 10 000 0000]]></text>
   </staticText>
   <staticText>
    <reportElement x="95" y="25" width="205" height="15" uuid="c226e44d-3bb5-4145-b0b3-903bf1d79fde"/>
    <text><![CDATA[Sesame street]]></text>
   </staticText>
   <staticText>
    <reportElement x="95" y="40" width="205" height="15" uuid="b96f7183-44f8-43ad-ba60-43d8fbf50b6e"/>
    <text><![CDATA[Sesame city]]></text>
   </staticText>
   <textField>
    <reportElement x="0" y="115" width="150" height="15" uuid="7e9e0af2-08d1-4997-b3e1-971e74b1c8ad">
     <property name="local_mesure_unitheight" value="pixel"/>
     <property name="com.jaspersoft.studio.unit.height" value="px"/>
    </reportElement>
    <textFieldExpression><![CDATA[$P{billingCompanyName}]]></textFieldExpression>
   </textField>
   <textField>
    <reportElement x="0" y="130" width="150" height="15" uuid="a0eaddab-ed2f-46fc-b9fc-d0d9747c6df3">
     <property name="local_mesure_unitheight" value="pixel"/>
     <property name="com.jaspersoft.studio.unit.height" value="px"/>
    </reportElement>
    <textFieldExpression><![CDATA[$P{billingCompanyAddress}]]></textFieldExpression>
   </textField>
   <textField>
    <reportElement x="0" y="145" width="150" height="15" uuid="f9371f1e-125e-408d-a0f0-aa0ea5adc171">
     <property name="local_mesure_unitheight" value="pixel"/>
     <property name="com.jaspersoft.studio.unit.height" value="px"/>
    </reportElement>
    <textFieldExpression><![CDATA[$P{billingCompanyFirstState}]]></textFieldExpression>
   </textField>
   <textField>
    <reportElement x="0" y="160" width="150" height="15" uuid="c14d7758-80e6-45d7-8526-797330e515d3">
     <property name="local_mesure_unitheight" value="pixel"/>
     <property name="com.jaspersoft.studio.unit.height" value="px"/>
    </reportElement>
    <textFieldExpression><![CDATA[$P{billingCompanySecondState}]]></textFieldExpression>
   </textField>
   <textField>
    <reportElement x="400" y="160" width="140" height="15" uuid="a9baefea-45b3-4826-a81e-3572507eea6d">
     <property name="local_mesure_unitheight" value="pixel"/>
     <property name="com.jaspersoft.studio.unit.height" value="px"/>
    </reportElement>
    <textFieldExpression><![CDATA[$P{shippingSecondState}]]></textFieldExpression>
   </textField>
   <textField>
    <reportElement x="400" y="145" width="140" height="15" uuid="338e1f40-9a03-4b77-aedc-568b1907628b">
     <property name="local_mesure_unitheight" value="pixel"/>
     <property name="com.jaspersoft.studio.unit.height" value="px"/>
    </reportElement>
    <textFieldExpression><![CDATA[$P{shippingFirstState}]]></textFieldExpression>
   </textField>
   <textField>
    <reportElement x="400" y="130" width="140" height="15" uuid="54e6473f-44ef-4839-8f87-29e65af72561">
     <property name="local_mesure_unitheight" value="pixel"/>
     <property name="com.jaspersoft.studio.unit.height" value="px"/>
    </reportElement>
    <textFieldExpression><![CDATA[$P{shippingAddress}]]></textFieldExpression>
   </textField>
   <textField>
    <reportElement x="400" y="115" width="140" height="15" uuid="1f093c2e-2d6f-403e-9c11-160dbaf82e6f">
     <property name="local_mesure_unitheight" value="pixel"/>
     <property name="com.jaspersoft.studio.unit.height" value="px"/>
    </reportElement>
    <textFieldExpression><![CDATA[$P{shippingName}]]></textFieldExpression>
   </textField>
  </band>
 </title>
 <columnHeader>
  <band height="24">
   <staticText>
    <reportElement x="366" y="4" width="80" height="20" uuid="be792358-dade-4931-965d-fe4d4958b71c"/>
    <textElement textAlignment="Center">
     <font size="12" isBold="false"/>
    </textElement>
    <text><![CDATA[Quantity]]></text>
   </staticText>
   <rectangle>
    <reportElement mode="Opaque" x="10" y="2" width="531" height="20" backcolor="#C0D4EC" uuid="ce42b0b0-0d12-48c1-8020-576969255150"/>
    <graphicElement>
     <pen lineColor="#666666"/>
    </graphicElement>
   </rectangle>
   <staticText>
    <reportElement x="430" y="3" width="111" height="18" uuid="95b85246-2e67-42d0-9e41-987314cddba0"/>
    <textElement textAlignment="Center">
     <font size="12" isBold="false"/>
    </textElement>
    <text><![CDATA[Price $]]></text>
   </staticText>
   <staticText>
    <reportElement x="261" y="3" width="80" height="20" uuid="40050754-f800-4283-a0ed-64894f5652a2"/>
    <textElement textAlignment="Center">
     <font size="12" isBold="false"/>
    </textElement>
    <text><![CDATA[Unit Cost $]]></text>
   </staticText>
   <staticText>
    <reportElement x="10" y="3" width="50" height="20" uuid="299467fd-8d2b-48b0-af5b-769cc9d9bb37"/>
    <textElement textAlignment="Center">
     <font size="12" isBold="false"/>
    </textElement>
    <text><![CDATA[Item]]></text>
   </staticText>
   <staticText>
    <reportElement x="71" y="2" width="179" height="20" uuid="9818ad45-9dc2-4e62-821c-953f3801de84"/>
    <textElement textAlignment="Center">
     <font size="12" isBold="false"/>
    </textElement>
    <text><![CDATA[Description]]></text>
   </staticText>
   <staticText>
    <reportElement x="347" y="3" width="80" height="20" uuid="f10ae7d8-7499-404a-a1ab-a2ce63b22b3b"/>
    <textElement textAlignment="Center">
     <font size="12" isBold="false"/>
    </textElement>
    <text><![CDATA[Quantity]]></text>
   </staticText>
  </band>
 </columnHeader>
 <detail>
  <band height="29">
   <textField>
    <reportElement x="11" y="5" width="54" height="20" uuid="0cd6aa63-bd20-45fb-8543-51931badd2fc"/>
    <textElement textAlignment="Left"/>
    <textFieldExpression><![CDATA[$F{itemNo}]]></textFieldExpression>
   </textField>
   <textField>
    <reportElement x="70" y="5" width="180" height="20" uuid="1be950c3-370a-43fa-9510-2ee8db740774"/>
    <textElement textAlignment="Left"/>
    <textFieldExpression><![CDATA[$F{description}]]></textFieldExpression>
   </textField>
   <textField>
    <reportElement x="261" y="5" width="80" height="20" uuid="3637c327-f832-4e7c-bb82-4cf41e607ca6"/>
    <textElement textAlignment="Left"/>
    <textFieldExpression><![CDATA[$F{unitCost}]]></textFieldExpression>
   </textField>
   <textField>
    <reportElement x="347" y="5" width="80" height="20" uuid="e9bfe6dc-7101-4d22-90a7-4766122c4e8a"/>
    <textElement textAlignment="Left"/>
    <textFieldExpression><![CDATA[$F{quantity}]]></textFieldExpression>
   </textField>
   <textField>
    <reportElement x="430" y="5" width="118" height="20" uuid="77c9d024-651d-4207-9f32-8637cd4dd449"/>
    <textElement textAlignment="Left"/>
    <textFieldExpression><![CDATA[$F{unitCost} * $F{quantity}]]></textFieldExpression>
   </textField>
  </band>
 </detail>
 <lastPageFooter>
  <band height="177">
   <staticText>
    <reportElement positionType="Float" x="-1" y="30" width="261" height="101" uuid="1a0d7088-5af7-4865-8be1-41ec5f51fb36"/>
    <box>
     <topPen lineWidth="1.1" lineStyle="Dashed"/>
     <leftPen lineWidth="1.1" lineStyle="Dashed"/>
     <bottomPen lineWidth="1.1" lineStyle="Dashed"/>
     <rightPen lineWidth="1.1" lineStyle="Dashed"/>
    </box>
    <text><![CDATA[Your notes here]]></text>
   </staticText>
   <staticText>
    <reportElement positionType="Float" mode="Opaque" x="0" y="147" width="556" height="30" backcolor="#E6E8E9" uuid="36aa233d-4305-48e6-974a-1bbf89bb3c8f"/>
    <textElement textAlignment="Center" verticalAlignment="Middle">
     <font fontName="Serif" size="9" isItalic="true"/>
    </textElement>
    <text><![CDATA[THANKYOU FOR YOUR BUSINESS]]></text>
   </staticText>
  </band>
 </lastPageFooter>
</jasperReport>

3- Creating an Item class that will be the model object containing the data that be binded to the JRXML template fields. Also, I created an InvoiceDetails class that will have the data that will be binded to the JRXML template parameters.
package com.ithinkisink.model;

/**
 * 
 * @author Belal
 *
 */
public class Item {

 private String itemNo;
 private String description;
 private double unitCost;
 private int quantity;
 
 public Item(String itemNo, String description, double unitCost, int quantity) {
  super();
  this.itemNo = itemNo;
  this.description = description;
  this.unitCost = unitCost;
  this.quantity = quantity;
 }

 public String getItemNo() {
  return itemNo;
 }

 public void setItemNo(String itemNo) {
  this.itemNo = itemNo;
 }

 public String getDescription() {
  return description;
 }

 public void setDescription(String description) {
  this.description = description;
 }

 public double getUnitCost() {
  return unitCost;
 }

 public void setUnitCost(double unitCost) {
  this.unitCost = unitCost;
 }

 public int getQuantity() {
  return quantity;
 }

 public void setQuantity(int quantity) {
  this.quantity = quantity;
 }
}

4- The DynamicReportsManagedBean will be responsible to prepare the parameters map and the JRBeanCollectionDataSource containing List<Item> that will be binded to the JRXML fields.
package com.ithinkisink.managedbean;

import static net.sf.dynamicreports.report.builder.DynamicReports.report;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import javax.servlet.ServletContext;

import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import com.ithinkisink.model.InvoiceDetails;
import com.ithinkisink.model.Item;

/**
 * 
 * @author Belal
 *
 */
@Named
@SessionScoped
public class DynamicReportsManagedBean implements Serializable {

 private static final long serialVersionUID = -1;

 private String invoiceName;
 private JRBeanCollectionDataSource beanCollectionDataSource;
 private Map<String, Object> parameters;

 @PostConstruct
 public void init() {
  invoiceName="Invoice.jrxml";
  
  List<Item> itemList = new ArrayList<>(Arrays.asList(
    new Item("01", "Item 01 description", 1.1, 1), 
    new Item("02", "Item 02 description", 2.2, 2),
    new Item("03", "Item 03 description", 3.3, 3)));
  beanCollectionDataSource = new JRBeanCollectionDataSource(itemList);
  
  parameters = (new InvoiceDetails("INV#01", "Billing Company", "Billing Company Add", 
    "Billing Company State 1", "Billing Company State 2", 
    "Shipping Name", "Shipping Address", "Shipping State 1", "Shipping State 2", 1000)).toMap();
 }
 
 /**
  * Preparing an output stream of the generated PDF invoice.
  * 
  * @return
  */
 public OutputStream getOS(ServletContext context, OutputStream outputStream) {

  parameters.put("IMAGE_PATH", context.getRealPath("/jasper/invoices"));

  InputStream is = context.getResourceAsStream("/jasper/invoices/" + invoiceName);

  try {
   report().setTemplateDesign(is)
     .setDataSource(beanCollectionDataSource)
     .setParameters(parameters).toPdf(outputStream);
  } catch (DRException e) {
   e.printStackTrace();
  }

  return outputStream;
 }

 // setters and getters
 public String getInvoiceName() {
  return invoiceName;
 }

 public void setInvoiceName(String invoiceName) {
  this.invoiceName = invoiceName;
 }

 public JRBeanCollectionDataSource getBeanCollectionDataSource() {
  return beanCollectionDataSource;
 }

 public void setBeanCollectionDataSource(
   JRBeanCollectionDataSource beanCollectionDataSource) {
  this.beanCollectionDataSource = beanCollectionDataSource;
 }

 public void setParameters(Map<String, Object> parameters) {
  this.parameters = parameters;
 }

 public Map<String, Object> getParameters() {
  return parameters;
 }
}

5- The CDI enables us to inject an instance of the DynamicReportsManagedBean  to the DynamicReportsServlet. The servlet will handle the response output stream which will present the created output stream from the DynamicReports of the template.
package com.ithinkisink.servlet;

import java.io.IOException;
import java.io.OutputStream;

import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ithinkisink.managedbean.DynamicReportsManagedBean;

/**
 * 
 * @author Belal
 *
 */
public class DynamicReportsServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

 @Inject
 private DynamicReportsManagedBean dynamicReportsManagedBean;
 
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  resp.setContentType("application/pdf");
  OutputStream out = resp.getOutputStream();
  out = dynamicReportsManagedBean.getOS(getServletContext(), out);
  out.close();
 }
 
 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  super.doPost(req, resp);
  this.doGet(req, resp);
 }
 
 public void setDynamicReportsManagedBean(
   DynamicReportsManagedBean dynamicReportsManagedBean) {
  this.dynamicReportsManagedBean = dynamicReportsManagedBean;
 }
 
 public DynamicReportsManagedBean getDynamicReportsManagedBean() {
  return dynamicReportsManagedBean;
 }
}

6- I prefer the old school in adding the servlet to the web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

 <display-name>DynamicReportsWithJSFServletsAndCDI Maven Webapp</display-name>

 <servlet>
  <description></description>
  <display-name>DynamicReportsServlet</display-name>
  <servlet-name>DynamicReportsServlet</servlet-name>
  <servlet-class>com.ithinkisink.servlet.DynamicReportsServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>DynamicReportsServlet</servlet-name>
  <url-pattern>/*</url-pattern>
 </servlet-mapping>
 
 <welcome-file-list>
  <welcome-file>/index.xhtml</welcome-file>
 </welcome-file-list>
</web-app>

7- The index.xhtml contains an <iframe> that points to the servlet.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
 xmlns:h="http://java.sun.com/jsf/html">

<h:head>
 <title>DynamicReports with Servlets, JSF and CDI</title>
</h:head>

<h:body>
 <h:form>
  <iframe name="receipt" height="600" id="theIFrame" width="100%"
   src="http://localhost:8080/DynamicReportsWithJSFServletsAndCDI" />
 </h:form>
</h:body>

</html>

8- The final output by running the example.
You can find the complete example on my Github from this link:

Sunday, September 27, 2015

Enable autocomplete for JSF in Eclipse

The autocomplete is not presented with Eclipse to discover the classes annotated with the @ManagedBean in the XHTML pages. Fortunately, JBoss Tools plugin enables to by installing the JBoss Tools JSF as shown in the bellow screenshot.

This is the link for installing the JBoss Tools for Eclipse Luna.
Update:
I have tried the latest Eclipse Mars and I figured out that Eclipse made things easier for us as developers. Now Eclipse Mars is delivered with support for autocomplete of the JSF Managed Beans. That's cool!

Friday, September 11, 2015

Weekly Readings

I will start to post weekly posts about readings (that could be articles, technical documentations, references, technical questions ... etc) that I have gone through during every week. This would be useful to share with you what other people wrote about some technical stuff. I hope this would be useful in a way or another :)

Saturday, July 11, 2015

Friday, July 10, 2015

Bidirectional relationship with Jackson in REST web services in WildFly

This is an example for a Bidirectional relationship between Java entities in a REST web service with the Jackson API.

1- Assume we have a bidirectional relationship between two entities Parent and Child.
2- Using MySQL workbench to generate the SQL schema file for this two tables.
DROP SCHEMA IF EXISTS `bidirectional_schema` ;
CREATE SCHEMA IF NOT EXISTS `bidirectional_schema` DEFAULT CHARACTER SET utf8 ;
USE `bidirectional_schema` ;

-- -----------------------------------------------------
-- Table `bidirectional_schema`.`PARENT`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `bidirectional_schema`.`PARENT` ;

CREATE  TABLE IF NOT EXISTS `bidirectional_schema`.`PARENT` (
  `PARENT_ID` INT NOT NULL ,
  `PARENT_CONTENT` VARCHAR(45) NULL ,
  PRIMARY KEY (`PARENT_ID`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `bidirectional_schema`.`CHILD`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `bidirectional_schema`.`CHILD` ;

CREATE  TABLE IF NOT EXISTS `bidirectional_schema`.`CHILD` (
  `CHILD_ID` INT NOT NULL ,
  `CHILD_CONTENT` VARCHAR(45) NULL ,
  `PARENT_PARENT_ID` INT NOT NULL ,
  PRIMARY KEY (`CHILD_ID`) ,
  INDEX `fk_CHILD_PARENT_idx` (`PARENT_PARENT_ID` ASC) ,
  CONSTRAINT `fk_CHILD_PARENT`
    FOREIGN KEY (`PARENT_PARENT_ID` )
    REFERENCES `bidirectional_schema`.`PARENT` (`PARENT_ID` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

Installing WebSphere Liberty Profile server then adding features

IBM WebSphere Liberty Profile is a really fast and easy to to use application server. According to the About page, the latest stable release of Liberty is Java EE 6 Web Profile-certified and they’re gradually adding Java EE 7 technologies. Any Java EE 6 applications you write on Liberty can be deployed in production, without changes, on WebSphere Application Server which is certified for the full Java EE 6 platform. You can, of course, deploy to production on Liberty too. Bellow we will see how to start working on it and adding some features to it.

1. Download the Liberty server from this link as a stand alone server.
https://developer.ibm.com/wasdev/downloads/liberty-profile-using-non-eclipse-environments/
Also you can embed it in Eclipse after installing the WebSphere Developer Tools through this link:
https://developer.ibm.com/wasdev/downloads/liberty-profile-using-eclipse/
The Eclipse Marketplace would start like this for installing an adapter for the Eclipse.

Monday, June 1, 2015

Killing Websphere Liberty Profile processes in Windows

I face such issue as the Websphere Liberty Profile ports are used by a previous installation for the WMB so I have to manually kill the process in order to be able to start the application.
1- This is the error message that I got when I try to start the WLP server instance.
2- The bellow command lists the current ports and their processes ID's.
netstat -a -n -o
4- Open the CMD.exe as Administrator.

3- Now that we knew the processes ID's we kill them by one of the two bellow commands. The argument /F forces the killing of the process.
taskkill /PID <process_Id>
taskkill /F /PID <process_Id>

Saturday, May 30, 2015

PrimeFaces Push with Atmosphere

PrimeFaces Push is based on Atmosphere to establish WebSocket communication in an easy way. Bellow I will share the configuration to be able to do such kind of communication.
1- Adding the PrimeFaces and Atmosphere to the pom.xml for Maven dependency. Also, I added the dependency of the Apache Commons Lang3 to use the StringEscapeUtils while sending the notification message.
<dependency>
 <groupId>org.atmosphere</groupId>
 <artifactId>atmosphere-runtime</artifactId>
 <version>2.1.7</version>
</dependency>

<dependency>
 <groupId>org.apache.commons</groupId>
 <artifactId>commons-lang3</artifactId>
 <version>3.4</version>
</dependency>

<dependency>
 <groupId>org.primefaces</groupId>
 <artifactId>primefaces</artifactId>
 <version>5.0</version>
</dependency>
2- The web.xml configuration for the push servlet.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>PrimePushNotify</display-name>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>PrimePushServlet</servlet-name>
    <servlet-class>org.primefaces.push.PushServlet</servlet-class>
    <init-param>
      <param-name>org.atmosphere.cpr.broadcasterCacheClass</param-name>
      <param-value>org.atmosphere.cache.UUIDBroadcasterCache</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
    <servlet-name>PrimePushServlet</servlet-name>
    <url-pattern>/primepush/*</url-pattern>
  </servlet-mapping>
</web-app>

Friday, May 29, 2015

EclipseLink on WildFly 8.2.0

WildFly application server uses Hibernate as a default JPA provider. So you can ignore specifying the persistence provider configuration in the persistence.xml file as bellow:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
 <persistence-unit name="BidirectionalPU">
     <jta-data-source>java:jboss/datasources/Bidirectional_DataSource</jta-data-source>
     <class>com.ithinkisink.entity.Child</class>
     <class>com.ithinkisink.entity.Parent</class>
     <class>model.TempTable</class>
 </persistence-unit>
</persistence>
The deployed application will then use Hibernate as default JPA provider. In order to switch WildFly to use EclipseLink, you can follow the bellow steps:
1- Download the EclipseLink JAR file from the bellow Maven repository link:
http://mvnrepository.com/artifact/org.eclipse.persistence/eclipselink/2.6.0
2- Now navigate to the following directory under the WildFly server directory:
<PATH_TO_WILDFLY_DIRECTORY>\wildfly-8.2.0.Final\modules\system\layers\base\org\eclipse\persistence\main
3- Move the EclipseLink JAR file to the above directory and remove the version from the file name, so it would be eclipselink.jar.
4- Add the eclipselink.jar to the <resources> of the module.xml in the mentioned directory.
<module xmlns="urn:jboss:module:1.3" name="org.eclipse.persistence">
    <resources>
        <resource-root path="jipijapa-eclipselink-1.0.1.Final.jar"/>
  <resource-root path="eclipselink.jar"/>
    </resources>

    <dependencies>
        <module name="asm.asm"/>
        <module name="javax.api"/>
        <module name="javax.annotation.api"/>
        <module name="javax.enterprise.api"/>
        <module name="javax.persistence.api"/>
        <module name="javax.transaction.api"/>
        <module name="javax.validation.api"/>
        <module name="javax.xml.bind.api"/>
        <module name="org.antlr"/>
        <module name="org.apache.commons.collections"/>
        <module name="org.dom4j"/>
        <module name="org.javassist"/>
        <module name="org.jboss.as.jpa.spi"/>
        <module name="org.jboss.logging"/>
        <module name="org.jboss.vfs"/>
    </dependencies>
</module>
5- Now you can point the JPA provider to org.eclipse.persistence.jpa.PersistenceProvider.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
 <persistence-unit name="BidirectionalPU">
     <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
     <jta-data-source>java:jboss/datasources/Bidirectional_DataSource</jta-data-source>
     <class>com.ithinkisink.entity.Child</class>
     <class>com.ithinkisink.entity.Parent</class>
     <class>model.TempTable</class>
 </persistence-unit>
</persistence>

Thursday, May 28, 2015

Bind WildFly to all available IP addresses on Eclipse

In order to be able to access the deployed applications on the WildFly server through the machine IP address, you should add the bellow configuration to the Eclipse lunch configuration as shown in the bellow screenshots.

1- Open launch configuration dialog from Eclipse.

2- Append "-b 0.0.0.0" to the Program argument.

For more information about binding the WildFly server to different IP addresses, check the link by Arun Gupta.

References:
http://blog.arungupta.me/bind-wildfly-different-ip-address-multihomed/

Friday, May 1, 2015

Postman, a REST web service client for Chrome

In case you needed to test a REST web service through a web service client. You can install Postman which is a Chrome extension. It's a pretty good one. You can install it from the bellow link:
https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
Update:
I figured out that there is a another packaged application version. So I'm sharing with you the other one also:
https://chrome.google.com/webstore/detail/postman-rest-client-packa/fhbjgbiflinjbdggehcddcbncdddomop?hl=en

Wednesday, April 15, 2015

Agile Architecture by Molly Dishman and Martin Fowler

I'm copying here what Mahmoud Atef mentioned in his post on Linkedin that sums up this video. I think it's really important to follow such tips in order to provide some sort of architecture management during the software development. Here is what Mahmoud wrote:

I was lucky to listen to  "Agile Architecture" talk by Molly Dishman & Martin Fowler (attached @the end of this post). I come up with eight points that I want to share my thoughts about.

  1. Focus on the things that are hard to change and make them changeable. Mainly, service contracts and database design are the most rigid parts in any architecture design. Sometimes it's OK to fix them if the requirements are very clear from the beginning of the project, which is rare to happen. Most of the time, you need to find a way to simplify the change in these parts whenever it is needed.
  2. Architects are more working as team leads and have to get their hands into code. In agile project, architects are almost engaged along the project lifetime. They are required to solve day-to-day technical challenges and come up with solutions to new problems. This couldn't be done unless they have hands on the project code and know its current status and improvements needed.
  3. Architecture is more like city planing with all the dynamics implied rather than a static building structure. Evolutionary design and refactoring are two of the main features in agile projects nowadays. Architects have to believe that their designs will be changed with time and start to think how flexible and tolerant are their designs. They also need to be more willing to experiment things and change if it doesn't work.
  4. The best place of detailed design is in people minds. Detailed design document became part of the history because, simply nobody needs it. If it comes to details, code is the most updated detailed design a programmer can get. Architect has to make sure that there is a common understanding of the application design and how it works.
  5. Highlight example part of the code and let people to understand and copy from. Sample of code is one of the most powerful methods of ensuring common understanding for the design. It also puts programmers on the right track rapidly by copping the sample and put their changes with lowest effort.
  6. Use code analysis tool to keep the code standards followed across the project. You need to have a tool to scan the code base and give you a comprehensive report about the standard violations. This will give you and your team faster and broader vision on the problems you have to tackle.
  7. Keep an eye on the code commits to get an overview of developers performance. It's not enough to use tools to give you report on how code is going on, you need to check some of the project commits to get an overview on how programmers are implementing their stories and how far is the code stream from your design.
  8. Give architects and senior developers time to think about architecture. Time is the key factor for innovation and improvement. If the team is always on rush to deliver and no time to step back and think, they won't have a chance to think about the application which will affect the overall implementation and performance in a very bad way.


Finally, for more videos for Martin Fowler you can check this page.



Thursday, April 9, 2015

Adding MyBatis mapper files dynamically

I'm currently working in a project that we needed to implement such case. Assuming you are using MyBatis CDI in a EJB/CDI context, the bellow code will produce the MyBatis SqlSessionFactory for the MyBatis mapper files that are defined in a static way.

First, your Configuration.xml will only contain the database connection as bellow:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="UNPOOLED">
                <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
                <property name="url" value="jdbc:oracle:thin:@<HOST>:<PORT>:<DB_NAME>"/>
                <property name="username" value="<SCHEMA>"/>
                <property name="password" value="<PASSWORD>"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

Saturday, January 17, 2015

Using JUnit with GlassFish EJB embedded EJB container

1- Add the Glassfish embedded EJB container dependency to your Maven POM file. Also the JUnit dependency.
<dependency>
 <groupId>org.glassfish.main.extras</groupId>
 <artifactId>glassfish-embedded-all</artifactId>
 <version>3.1.2</version>
 <scope>test</scope>
</dependency>

<dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.11</version>
</dependency>
The scope is test so it can be applied during the testing of the application.

2- The service class is annotated with @Stateless as bellow
package com.ithinkisink.blog.service;
@Stateless
public class MyService {
   public String getMessage() {
      return "Hello!";
   }
}
For the sake of simplicity, the service class doesn't implement an interface as EJB supports injecting classes with no need to have interfaces.

3- Now the unit test class could be as bellow:
import javax.ejb.embeddable.EJBContainer;
import javax.ejb.embeddable.EJBContainer;
import javax.naming.Context;
import javax.naming.NamingException;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.ithinkisink.blog.service.MyService;

/**
 *
 *@author Belal
 */
public class MyServiceTest {

   private static Context  ctx;
   private static EJBContainer ejbContainer;
   private MyService myService;

   @BeforeClass
   public static void setUpBeforeClass() {
      ejbContainer = EJBContainer.createEJBContainer();
      System.out.println("Container Opening" );
      ctx = ejbContainer.getContext();
   }

   @AfterClass
   public static void tearDownAfterClass() {
      ejbContainer.close();
      System.out.println("Container Closing" );
   }

   @Test
   public void getMessageTest() throws NamingException {
      //note the JNDI path of the EJB container in case you used another container, this would need to be changed!
      myService = (MyService) ctx.lookup("java:global/ejb-app/classesejb/MyService");
      Assert.assertEquals(myService.getMessage(), "Hello!");
   }
}