Saturday, March 17, 2018

Introduzione a Git

1. Introduzione

Git e' un sistema di version control (http://git-scm.org). Lo scopo di Git e' quello di tener traccia di tutti i cambiamenti effettuati all'interno di un progetto software in modo da assicurare sempre una versione di backup delle versioni precedenti. In questo modo, se qualcosa va storto, e' possibile invertire le modifiche e ripristinare il precedente stato funzionante del software.
A differenza degli altri sistemi di versionamento, quasi tutte le operazioni in Git non hanno bisogno di una connessione internet, perché sono operazioni che avvengono su disco locale. Git salva lo storico completo del progetto direttamente su disco locale e recuperare una vecchia versione di un file dalla history é una operazione istantanea. Anche le commit avvengono sul database locale

1.1 Git vs GitHub

Git e GitHub sono due cose diverse: GitHub è un servizio online basato su Git, ma non è indispensabile per usare Git e creare un repository. GitHub permette di hostare online un repository creato con Git e condividerlo con altri sviluppatori. L'hosting pubblico su GitHub è gratuito, l'hosting privato è a pagamento. Per questo motivo gli sviluppatori usano altri servizi online per condividere repository Git, come GitLab.com e bitbucket.org.

1.2 Le aree di lavoro di Git

Git e' composto da quattro aree di lavoro:


Il luogo dove lo sviluppatore crea e modifica il codice del progetto e' rappresentato dalla working directory di Git, che contiene i file che andranno a costituire il repository Git.

Friday, February 23, 2018

Enterprise Beans

Enterprise beans run in the EJB container:

  • the EJB container is a runtime environment within a Java application server
  • the EJB container provides system-level services to enterprise beans such as transactions and security

Content:

  1. What Is an Enterprise Bean?
  2. What Is a Session Bean?
  3. What Is a Message-Driven Bean?

1 What Is an Enterprise Bean?

An enterprise bean is a server-side component that contains the application's business logic

  • for example, in an auction application, the AuctionManager enterprise bean implements the business logic in the methods named createAuction, placeBid, closeAuction.
1.1 Benefits of Enterprise Beans

Enterprise beans simplify the development of large applications:

  • the EJB container, not the developer, is responsible for system level services such as transaction management and security authorization
  • the beans not the clients contain the business logic, the clients only contain the presentation. As a consequence, application clients are thinner
  • enterprise beans are portable, they are portable accross any compliant Java EE server and developers can build new applications from existing beans
1.2 When to Use Enterprise Beans

You should consider using enterprise beans if your application has any of the following requirements:

  • the application must be scalable to support more users and you need to distribute application's components to multiple machines
  • transactions must ensure data consistency
  • application will be accessed by a variety of clients
1.3 Types of Enterprise Beans

There are two types of enterprise beans, which fulfill different purposes:

  • Session: a session bean performs a task for a client
  • Message-driven: a message-driven bean acts as a listener for messages

Tuesday, January 16, 2018

Introduction to Java Platform, Enterprise Edition

Companies need distributed, transactional and portable applications: enterprise java applications fulfill the business logic for the enterprise.

Java platform provides APIs to developers and shortens developement time

The Java Community Process (JCP) writes Java Specification Requests (JSRs) to define the Java EE technologies

The Java EE 7 platform simplifies the programming model:

  • Developers can use annotations in Java source files, instead of optional XML deployment descriptors. The Java EE server reads annotations and configures components at deployment and runtime
  • With dependency Injection, required resources can be injected in component, instead of using JNDI lookup code. Dependency injection can be used in any container type: EJB container, web container and application client container. The container is aware of annotations and inject references to other component/resource

1 Java EE Application Model

Java EE applications implement enterprise services for customers, access data from different sources and distribute applications to a variety of clients

The business functions of Java enterprise applications are in the middle tier: the middle tier is usually on a dedicated server hardware.

The Java application model architecture implements the customer's services as multitier applications

The Java model partitions the work in two parts:

  • business logic and presentation implemented by developers
  • standard services provided by Java EE platform

Friday, September 15, 2017

Requirements of Java EE 7 Enterprise Applications

The Java EE technology elements

Java EE specifications incorporates a group of other technologies and specifications to provide server-side functionalities for enterprise application developers

  • application components: these components allow creation of application business logic and control elements
  • integration: integration elements allow to interact with the functionalities from other applications and systems
  • container management: these elements provide runtime support for Java EE application components

Monday, August 28, 2017

Creating a Simple Maven Project

1 Generating a simple project with Maven and Eclipse

To generate a project with maven from command line:

 mvn -B archetype:generate \
  -DgroupId=com.company.application \
  -DartifactId=project \
  -Dpackage=com.company.application \
  -Dversion=1.0 
  -DarchetypeGroupId=org.apache.maven.archetypes \
  -DarchetypeArtifactId=maven-archetype-quickstart \
  • the maven command mvn archetype:generate executes the generate goal of the archetype plugin
  • an archetype is defined as a "model from which similar thing are patterned; a prototype"
  • when you run the archetype:generate goal you pass the goal parameter: archetypeArtifactId=maven-archetype-quickstart
  • you can select the maven archetypes that fits your purpose
  • the maven-archetype-quickstart is the most basic archetype to create a java project

Friday, July 21, 2017

Serializing Java Objects with JAXB

Java Model

The model class Team

package j2s.team;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/* 
 * As the class Team is annotated with @XmlRootElement, JAXB transforms a Team 
 * instance into an XML document whose root element is <team> 
 */
@XmlRootElement(name="team")
@XmlType(propOrder={"name","description","playerList"})
@XmlAccessorType(XmlAccessType.FIELD)
public class Team {

 // fields
 private String name;
 private String description;

 @XmlElement(name = "player")
 @XmlElementWrapper(name = "players")
 private List<Player> playerList;

 public Team(String name, String description) {
  this.name = name;
  this.description = description;
  this.playerList = new ArrayList<Player>();
 }

 // default constructor required by JAXB
 public Team() {
  this("team name", "team descr");
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getDescription() {
  return description;
 }

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

 public List<Player> getPlayers() {
  return playerList;
 }

 public void setPlayers(List<Player> playerList) {
  this.playerList = playerList;
 }

 public void addPlayer(Player dev) {
  playerList.add(dev);
 }

 @Override
 public String toString() {
  return "Team [name=" + name + ", description=" + description + ", players=" + playerList + "]";
 }

}

Tuesday, June 6, 2017

Web Services Introduction

Common definitions

Hypermedia systems are systems where text, pictures, audio, video and other media are stored in network hosts and connected through hyperlinks. The web is the example of hypermedia system.

The TCP-IP protocol stack makes it possible the data communication within a network of computer. The protocol stack is arranged in abstraction layers. From lowest to highest, the layers are: the link layer (for communication within a single network segment or link) the internet layer (for communication between independent networks) the transport layer (for communication host-to-host) and the application layer (for communication between two running application programs or processes: for example a client and a server). - (Internet_protocol_suite on wikipedia)

The HyperText Transfer Protocol or HTTP is an application-level protocol for hypermedia information systems.
HTTP is used by the World Wide Web with Hypertext to transfer data from servers to clients. HTTP is a generic protocol which can be used for many tasks beyond hypertext (such as Domain Name System and distributed object systems, like CORBA) through extension of its request methods, error codes and headers. (HTTP on wikipedia, HTTP on mozilla , rfc2616)

In computer networking, a communication channel is a logical connection that allows to transport information, from transmitters to receivers. A communication endpoint is an abstract object or interface that is the final point of a communication path; the transmitter writes to the endpoint and the receiver reads from the endpoint. For example, in operating systems, a software port is a communication endpoint managed by a computer's operating system, which identifies a specific process or a type of network service.

Web Service definitions

  • A web service is a distributed software whose components can be deployed and executed on distinct devices.
  • A web service consists of a service (a.k.a. producer) and a client (a.k.a. consumer or requester).

Web Service compared to Website

  • both web services and websites are examples of distributed systems.
  • websites deliver HMTL payloads whereas web services deliver XML or JSON payloads

Web service terminology

  • endpoint: a web service endpoint is an association between a binding and a network address, specified by a URI, that may be used to communicate with an instance of a service.
  • message: the basic unit of communication between a web service and a requester; data to be communicated to or from a web service as a single logical transmission.
  • operation: a description of an action supported by the service; a set of messages related to a single web service action.
  • synchronous: an interaction is said to be synchronous when the participating agents must be available to receive and process the associated messages from the time the interaction is initiated until all messages are actually received or some failure condition is determined.
  • asynchronous: an interaction is said to be asynchronous when the associated messages are chronologically and procedurally decoupled.

Web Service communication layer

  • A web service typically communicates over HTTP. A web service over HTTP is a web service that uses HTTP to transport web service messages (we say that HTTP protocol and HTTP messages are infrastructure). HTTP messages follow four kinds of conversational pattern: request/response, solicit/response, one-way and subscribe/notify
  • the communication payloads are structured text, usually XML or JSON documents. XML and JSON are web service data interchange formats that provide an intermediary level and handle the differences in data types between different programming languages.

Web Service architecture

  • The architecture of a simple web service is a client and a server.
  • The architecture of a complicated web service have many clients and a service composed of other services.
  • Example: an e-commerce service can be composed of multiple software components (each hosted on a separate web server) and any combination of PCs, tablets, mobile phones and other networked devices may host programs that make requests to the service.

Web services come in two flavors: SAOP-based and REST-style.

  • SOAP is an XML dialect with a grammar that specifies the structure that documents must follow in order to be accepted as SOAP messages. SOAP-based services are transport neutral, but HTTP is the most common trasport for SOAP-based services
  • REST-style services use HTTP not only as service transport protocol but also as service messaging system.

Why using web services?

  • interoperability: clients and services can interact despite differences in programming languages, operating systems and hardware platforms.
  • system integration: web services offers software integration for legacy system or databases. For example, you can write a web service that integrates with a legacy system written in COBOL or a web service that integrates with a RDBMS.

Tuesday, May 9, 2017

How to validate an xml document against a schema

STEP 1: Create the XML

To create a new XML file, start eclipse IDE and choose File->New->Other->XML file->Create XML file from XML template.
Model the data of interest in the XML file. In my case, I have created the following XML.

The teams.xml file

<?xml version="1.0" encoding="UTF-8"?>
<team>
 <name>the great team</name>
 <description>these team was recruited by google to develop a secret product</description>
 <developers>
  <developer role="frontend">
   <name>John Carrot</name>
  </developer>
  <developer role="backend">
   <name>Joshua Allock</name>
  </developer>
  <developer role="frontend">
   <name>Brendan Tich</name>
  </developer>
 </developers>
</team>

Tuesday, March 14, 2017

XML Schema Primer

1 Introduction

Basic Concepts: The Purchase Order (§2) covers the basic mechanisms of XML Schema. It describes how to declare the elements and attributes that appear in XML documents, the distinctions between simple and complex types, defining complex types, the use of simple types for element and attribute values, schema annotation, a simple mechanism for re-using element and attribute definitions, and nil values.

Advanced Concepts I: Namespaces, Schemas & Qualification (§3), explains the basics of how namespaces are used in XML and schema documents.

2 Basic Concepts: The Purchase Order

The purpose of XML schemas

  • a schema defines a class of XML documents (is a description of an XML document)
  • an instance document is an XML document that conforms to a particular schema

The instance document, the po.xml file, describes a purchase order that may be generated by a product ordering application.

Example
The Purchase Order, po.xml
<?xml version="1.0"?>
<purchaseOrder orderDate="1999-10-20">
   <shipTo country="US">
      <name>Alice Smith</name>
      <street>123 Maple Street</street>
      <city>Mill Valley</city>
      <state>CA</state>
      <zip>90952</zip>
   </shipTo>
   <billTo country="US">
      <name>Robert Smith</name>
      <street>8 Oak Avenue</street>
      <city>Old Town</city>
      <state>PA</state>
      <zip>95819</zip>
   </billTo>
   <comment>Hurry, my lawn is going wild!</comment>
   <items>
      <item partNum="872-AA">
         <productName>Lawnmower</productName>
         <quantity>1</quantity>
         <USPrice>148.95</USPrice>
         <comment>Confirm this is electric</comment>
      </item>
      <item partNum="926-AA">
         <productName>Baby Monitor</productName>
         <quantity>1</quantity>
         <USPrice>39.98</USPrice>
         <shipDate>1999-05-21</shipDate>
      </item>
   </items>
</purchaseOrder>

The purchase order's elements have simple types or complex types

  • the purchase order consists of a main element purchaseOrder and the subelements {shipTo, billTo, comment, items}.
  • subelements can contain other subelements or data
  • elements that contain subelements or carry attributes are said to have complex types
  • elements that contain numbers, strings, dates and no subelements are said to have simple types, attributes always have simple types

Where to find the definitions of the types in the instance document

  • the complex types in the instance document are defined in the schema for purchase orders
  • the simple types in the instance document are defined either in the schema for purchase orders or are part of the built-in simple types of XML Schema

What is the association between the instance document and the the purchase order schema?

  • an instance document does not need to refer to a schema
  • the purchase order does not reference the purchase order schema

Saturday, October 8, 2016

How to run maven

1 Maven Command (mvn)

The basic syntax for running Maven is:

mvn [options] [<plugin:goal>] [<phase>]

The execution order depends on how goals and build phases are specified on the command line.

2 Running Maven Phases

Example: Compile a project

mvn clean compile

This command removes the previous build output and compiles the project's source code.

3 Running Unit Tests and Integration Tests

Unit tests usually test individual classes or components in isolation. Integration tests verify that multiple components work together, for example an application communicating with a database.

Maven itself does not inherently know whether a test is a unit test or an integration test. The distinction is usually created through plugin configuration and test class naming conventions.

Different Maven plugins can recognize different test class naming patterns. For example, the maven-surefire-plugin is normally used for unit tests, while the maven-failsafe-plugin is normally used for integration tests.

3.1 How Maven Test Plugins Recognize Test Classes

Each test plugin has its own default include patterns. These patterns determine which Java classes are considered test classes and executed by the plugin.

For example, the maven-surefire-plugin, which is normally used for unit tests, recognizes common test class names such as:

Test*.java
*Test.java
*Tests.java
*TestCase.java

Therefore, classes such as the following can be recognized as unit tests:

UserTest.java
TestUser.java
UserTests.java
UserTestCase.java

The maven-failsafe-plugin uses different default patterns for integration tests:

IT*.java
*IT.java
*ITCase.java

Therefore, classes such as the following can be recognized as integration tests:

ITDatabase.java
DatabaseIT.java
DatabaseITCase.java

This naming convention makes it possible to separate unit tests from integration tests while keeping both types of tests in the same Maven test source directory.

Example: Run Unit Tests

mvn test

This command executes the Maven lifecycle up to the test phase. It compiles the application, compiles the test code, and runs the unit tests.

The unit tests are normally executed by the maven-surefire-plugin.

For example:

mvn clean test

This command first removes the previous build output and then compiles and executes the unit tests.

Example: Run Unit Tests and Integration Tests

mvn verify

The verify phase occurs later in the Maven default lifecycle. Therefore, Maven executes all the preceding phases before reaching verify.

If the project is configured with the maven-failsafe-plugin, the integration tests are executed during the integration-test and verify phases.

A common command is:

mvn clean verify

This command performs a clean build, runs the unit tests, packages the application, and executes the integration tests.

The simplified execution flow is:

clean
  |
compile
  |
test
  |---- Unit Tests
  |
package
  |
integration-test
  |---- Integration Tests
  |
verify

3.2 Running Integration Tests with Surefire

Using the maven-failsafe-plugin is the standard approach when you want to separate unit tests from integration tests. However, using two test plugins is not mandatory.

If you prefer to use only the maven-surefire-plugin, you can name your integration test classes using one of Surefire's default test patterns.

For example, both of the following classes match Surefire's default naming conventions:

UserServiceTest.java
DatabaseIntegrationTest.java

Although DatabaseIntegrationTest.java is logically an integration test, its name matches the *Test.java pattern. Therefore, Surefire recognizes it as a test class and executes it together with the unit tests.

For example, consider the following test structure:

src
|
+-- test
    |
    +-- java
        |
        +-- UserServiceTest.java
        +-- RepositoryTest.java
        +-- DatabaseIntegrationTest.java
        +-- JpaIntegrationTest.java

All these classes match the default patterns recognized by the maven-surefire-plugin.

Therefore, the following command executes both the unit tests and the integration tests:

mvn test

Or, for a clean build:

mvn clean test

In this configuration, Maven does not distinguish between unit tests and integration tests. Both types of tests are executed during the test phase by the Surefire plugin.

UserServiceTest.java
RepositoryTest.java
        |
        +----> maven-surefire-plugin
        |
DatabaseIntegrationTest.java
JpaIntegrationTest.java
        |
        +----> maven-surefire-plugin
                    |
                    v
                test phase

This approach can be useful for small projects where running all tests together is sufficient and a separate integration test lifecycle is not required.

However, if integration tests require additional setup or cleanup operations, such as starting and stopping a database, a container, or an external service, using the maven-failsafe-plugin is usually the better approach.

3.3 integration-test vs verify

The integration-test and verify phases are both part of the Maven default lifecycle, but they have different purposes.

The command:

mvn integration-test

runs the Maven lifecycle up to the integration-test phase. Therefore, all preceding phases are executed first.

In a project using the maven-failsafe-plugin, the integration tests are executed during this phase.

For example, the execution flow can be summarized as:

mvn test
    ↓
Unit tests


mvn package
    ↓
Unit tests
    ↓
Package


mvn integration-test
    ↓
Unit tests
    ↓
Package
    ↓
Integration tests


mvn verify
    ↓
Unit tests
    ↓
Package
    ↓
Integration tests
    ↓
Verification of integration-test results


mvn install
    ↓
Unit tests
    ↓
Package
    ↓
Integration tests
    ↓
Verification of integration-test results
    ↓
Install artifact into local repository


mvn deploy
    ↓
Unit tests
    ↓
Package
    ↓
Integration tests
    ↓
Verification of integration-test results
    ↓
Install artifact into local repository
    ↓
Deploy artifact to remote repository

The important difference is that integration-test is the phase where the integration tests are executed, while verify is a later phase where the results of the integration-test execution can be checked.

This is why the Maven Failsafe Plugin is normally configured with both the integration-test and verify goals:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>3.5.2</version>

    <executions>
        <execution>
            <goals>
                <goal>integration-test</goal>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
</plugin>

For this reason, when you want to perform a complete build including integration tests, mvn verify is generally preferred over mvn integration-test.

The commonly used command is:

mvn clean verify

This performs a clean build, runs the unit tests, packages the application, runs the integration tests, and verifies their results.

In other words, integration-test is mainly the phase where integration testing takes place, while verify is the phase normally used to confirm that the complete build has successfully passed all required checks.

4 Configuring Unit and Integration Tests

Maven uses plugins to execute tests. Each plugin can have its own rules for recognizing test classes.

  • maven-surefire-plugin is normally used for unit tests and recognizes class names such as *Test.java.
  • maven-failsafe-plugin is normally used for integration tests and recognizes class names such as *IT.java.

The naming conventions are important because they allow the two plugins to execute different groups of tests.

The following is a simple pom.xml configuration:

<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.example</groupId>
    <artifactId>maven-tests-example</artifactId>
    <version>1.0.0</version>

    <properties>
        <maven.compiler.release>8</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.13.0</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.5.2</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>3.5.2</version>

                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>

            </plugin>

        </plugins>
    </build>

</project>

The following diagram summarizes how the two plugins work:

                    Maven Project
                          |
                          |
                 src/test/java
                          |
              +-----------+-----------+
              |                       |
              |                       |
      UserServiceTest.java      DatabaseIT.java
      RepositoryTest.java       JpaIT.java
              |                       |
              |                       |
              v                       v
    maven-surefire-plugin    maven-failsafe-plugin
              |                       |
              v                       v
          test phase         integration-test phase
              |                       |
              +-----------+-----------+
                          |
                          v
                    verify phase

5 Package a Project

Example: Package a project

mvn clean package

This command compiles the code, runs the unit tests, and packages the application into a distributable format such as a JAR or WAR.

Example: Run a Spring Web application

For example, assume you created a Spring Boot web application named my-spring-webapp.

  • To compile the project and produce an artifact, run mvn clean package from the project root.
  • To run the application, execute java -jar target/my-spring-webapp-1.0.0.jar from the project root.

The embedded Tomcat server starts on port 8080. Open your browser and go to http://localhost:8080.

Example: Install to the local repository

mvn clean install

This is one of the most common Maven commands. It builds the project and installs the generated artifact into your local repository, making it available for other local projects.

Maven executes all default lifecycle phases up to install. If Failsafe is configured, integration tests are also executed before the artifact is installed.

Example: Deploy to a shared repository

mvn clean deploy

In a build environment, this command cleans, builds, tests, and deploys artifacts to a remote repository. In multi-module projects, Maven processes each submodule in order and deploys their artifacts.

Introduction to maven

What is Maven ?

Maven is a project management tool, based on the concept of a project object model (POM).
Maven includes a project lifecycle, a dependency management system and execution of plugin goals at defined phases in a lifecycle.

Convention over configuration

Maven uses convention over configuration. Convention over configuration means that the system assume resonable defaults and the user is not required to do the configuration of the system.

Maven's conventions apply to build phases:

  • a maven project is assumed to produce a JAR file.
  • maven defines a default lifecycle and a set of common plugins that know how to build and integrate software.
  • maven core plugins apply conventions for many common processes.

Maven provides default location of directories:

     basedir/
          |__pom.xml
          |
          |__src/
          |   |___main/
          |   |    |___java/       (java source code)
          |   |    |___resources/  (java configuration)
          |   |    |___webapp/     (web content root)
          |   |
          |   |___test                     
          |        |___java/       (test code)
          |        |___resources/  (test configuration)
          |
          |__target/               (generated JAR)
              |___classes/         (compiled code)

The directory src/main is the most important directory, all of its content will become part of the maven artifact

  • the java source code is assumed to be in src/main/java
  • the java configuration are assumed to be in src/main/resources
  • the document root of the web module is src/main/webapp

The directory src/test is the place where tests reside, its content will not become part of the maven artifact:

  • the test sources are assumed to be in src/test/java
  • the test configuration are assumed to be in src/test/resources

The directory target contains the JAR artifact

  • the compiled code is in target/classes

When you use maven, you write your source code and if you follow the conventions, you only have to put the code in the predefined directory, maven will take care of the rest.