Friday, June 15, 2018

Java SE 8 Date and Time API

Time is a scalar quantity, so it would only need a number to express a time value.
Since you want to relate time to calendars, which are made for humans, things get more complicated.

Java date and time classes' history:

  • the java.util.Date class was introduced in Java 1.0
  • the java.util.Calendar class was introduced in Java 1.1
  • third-party date and time libraries, such as Joda-Time, were used by developer to overcome Java standard API's issues
  • the java.time API was introduced in Java 1.8 to fix the flaws in the previous versions of the platforms

1 The Time Line

The unit of time is the second, which is derived from the Earth's rotation around its axis.

Universal Time

  • Earth rotation is not uniform: in 1967, a more precise definition of second was derived from the property of atoms of caesium-133 and atomic clocks were introduced to keep the official time.
  • Since rotation rate of Earth varies with climate events, official time keepers synchronize absolute time with solar mean time
    • official time keepers add or remove a second to keep the Universal Time close to the mean solar time
  • In UTC, a day has 24 * 60 * 60 = 86400 seconds.
    • the number of seconds in a minute is usually 60, but with an occasional leap second it may be 61.

Universal Time and Computer Systems

  • Computer system keeps 86400 seconds per day and do not respect leap seconds.
  • when a leap second is officially introduced, computer systems slow down or speed up before the leap second.

Java Date and Time API specification for the time scale:

  • A day has 86,400 seconds
  • Time scale matches the official time at noon each day

The Time Line in Java and the Instant class

  • the Instant class represents a point in the time line
  • The static method Instant.now() returns the current instant
  • time is measured on time scale with origin set at midnigth of January 1, 1970 at Greenwich meridian
  • from that origin, time is measured in 86,400 seconds per day
  • Instant.MIN and Instant.MAX are one billion behind and ahead the origin

The Duration class represents the amount of time between two instants

  • the static method Duration.between gives the difference between two instants

Example:

 Instant start = Instant.now();
 callMethod();
 Instant stop = Instant.now();
 Duration timeElapsed = Duration.between(start, stop);
 long millis = timeElapsed.toMillis(); 

Wednesday, May 23, 2018

UTC Date Time System and ISO Representation

1 UTC Date Time System

1.1 UTC Time standard definition

Coordinated Universal Time (UTC) is the time standard by which the world regulates clocks and time.

The UTC is defined by an International Telecommunications Union recommendation and is based on International Atomic Time.

  • the standard adopt leap seconds to adjust UTC Time and compensate for the slowing of Earth's rotation.
  • Greenwich Mean Time (GMT) was formerly used as the international time standard, then UTC superseded GMT.
1.2 How UTC Time works

UTC divides time into days, hours, minutes and seconds.

UTC days

  • are identified using the Gregorian calendar.
  • contain 24 hours and each hour contains 60 minutes.
  • almost all UTC days contain exactly 86,400 SI seconds.

UTC minutes:

  • usually a minute contains 60 seconds, but (with an occasional leap second) a minute may contain 61 or 59.
  • because of leap seconds, the minute and all larger time units are of variable duration.

UTC seconds:

  • is the smaller time units of constant duration.
1.3 UTC Time Zones

Time zones are regions of the earth where the local time is defined as differing the UTC Time by an integer number of hours

  • but some countries have established time zones that differ by a number of half-hours or quarter-hours from UTC.
  • this difference or offset is positive or negative:
    • the westernmost time zone is twelve hours behind UTC and is UTC-12
    • the easternmost time zone is fourteen hours ahead of UTC and is UTC+14

Civil Time

Civil Time indicates the time designated by authorities or local time indicated by clocks.

  • civil time is generally standard time in a time zone at a fixed offset from Coordinated Universal Time (UTC), adjusted by daylight saving time during part of the year.

The Civil Time in a particular time zone can be determined from the UTC Time by adding or subtracting the number of hours and minutes specified by the UTC offset.

1.4 Daylight Saving Time

UTC does not observe daylight saving time and does not change with seasons

Local Time or Civil Time may change if a time zone jurisdiction observes Daylight Saving Time (summer time).

Example:

  • local time on the east coast of the United States is five hours behind UTC during winter, but four hours behind UTC during summer.
1.5 Who uses UTC

UTC is used by Computer systems and the Internet

  • in the internet and World Wide Web standards
  • the Network Time Protocol synchronizes the clocks of computers over the internet, using the UTC system
  • email systems and other messaging systems time-stamp messages using UTC
  • database records that include a time stamp use UTC

UTC is also the time standard used in aviation, weather forecasts, maps, amateur radio operators

Friday, April 6, 2018

Introduction to GIT

Content:

  1. Getting a Git Repository
  2.     1.1 How to get a Git repository
        1.2 Initializing a Repository in an Existing Directory
        1.3 Cloning an Existing Repository
  3. Recording Changes to the Repository
  4.     2.1 Recording Changes to the Repository
        2.2 Checking the Status of Your Files
        2.3 Adding a new file to your projecty
        2.4 Tracking New Files
        2.5 Staging Modified Files
        2.6 Ignoring Files
        2.7 Viewing Your Staged and Unstaged Changes
        2.8 Committing Your Changes
        2.9 Removing Files
        2.10 Moving Files
  5. Viewing the Commit History
  6.     3.1 Viewing the Commit History
  7. Working with Remotes
  8.     4.1 Working with Remotes
        4.2 Showing Your Remotes
        4.3 Adding Remote Repositories
        4.4 Fetching and Pulling from Your Remotes
        4.5 Pushing to Your Remotes
        4.6 Inspecting a Remote
        4.7 Renaming and Removing Remotes
  9. Branching
  10. Rewriting History
  11. Configuration

0 Getting Started

Git differs from other VCS in that it makes snapshots not differences

Git stores and thinks about information in a very different way than other VCSs.

  • Other version control systems store informations as a set of base files and the changes made to each file over time, this is commonly described as delta-based version control. Instead, Git stores the data as series of snapshots of a filesystem.
  • To store the state of the your project, Git makes a copy, or snapshot, all the files of the project and save them. To be more efficient, if a file has not changed, Git doesn’t store the file again but a link to the already saved file in a previous snapshot.
  • This is an important distinction between Git and all other VCSs, that makes Git more like a mini filesystem. This have many benefits when branching a Git project.

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>