Friday, April 6, 2018

Introduction to GIT

Content:

  1. Getting a Git Repository
  2. Recording Changes to the Repository
  3. Viewing the Commit History
  4. Working with Remotes

1 Getting a Git Repository

This guide contains the basic commands required to work with Git.

How to get a Git repository

You can get a Git repository in two ways:

  • turn a local directory into a Git repository
  • get a copy of an existing repository
Initializing a Repository in an Existing Directory

You have a project directory, not under version control, you want to control with Git

  • go to the directory of the project
  • type git init

The git init command create a .git subdirectory that contains the files required by the Git repository.

Cloning an Existing Repository

To get a copy of an existing Git repository use the clone command

  • you can clone a project's repository you want to contribute to.

For example, you can clone the Oracle's First Cup Java Tutorial with the following command:

  • $ git clone https://github.com/javaee/firstcup-examples
  • it is said that the command pulls down or check out a working copy of the latest version

To clone the Oracle's First Cup Java Tutorial in a target directory of your choice use the command:

  • $ git clone https://github.com/javaee/firstcup-examples firstCupJavaTutorial

2 Recording Changes to the Repository

Recording Changes to the Repository

Now, you want to make change to files and commit snapshots into your repository.

Files in your working directory can be in two states: traked and untraked.

  • Traked files are files that were in the last snapshot.
    • traked files can be: unmodified, modified and staged
    • when you clone a repository, the files in your working directory are all traked and unmodified
  • Untraked files are files in your working directory that were not in the last snapshot or in the Staging area.
    • a file just created is in the untracked state
Checking the Status of Your Files

The git status command allows you to determine in which state your files are.

If you run the git status command after a clone, you should see an output like the one below:

user@host:~$ cd firstcup-examples/
user@host:~/firstcup-examples$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working tree clean
user@host:~/firstcup-examples$

The Git status command also tell you in which branch you are on: master is the default branch.

Adding a new file to your project

Add a new file, the README file, to your project and run the git status command to see what has happened.

user@host:~$ cd firstcup-examples/
user@host:~/firstcup-examples$ vim README
user@host:~/firstcup-examples$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

Untracked files:
  (use "git add ..." to include in what will be committed)

 README

nothing added to commit but untracked files present (use "git add" to track)
user@host:~/firstcup-examples$

The git status command shows the README file as untracked.

Tracking New Files

To begin traking a new file, you use the git add command.

user@host:~/firstcup-examples$ git add README

Run the git status command, again. The README file now is traked and staged.

user@host:~/firstcup-examples$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD ..." to unstage)

 new file:   README

user@host:~/firstcup-examples$
Staging Modified Files

Modify the CONTRIBUTING.md file and run the git status command.

user@host:~/firstcup-examples$ vim CONTRIBUTING.md
user@host:~/firstcup-examples$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD ..." to unstage)

 new file:   README

Changes not staged for commit:
  (use "git add ..." to update what will be committed)
  (use "git checkout -- ..." to discard changes in working directory)

 modified:   CONTRIBUTING.md

user@host:~/firstcup-examples$

The modified file appears under the “Changes not staged for commit” section.

  • run the git add CONTRIBUTING.md
  • run the git status command again
user@host:~/firstcup-examples$ git add CONTRIBUTING.md
user@host:~/firstcup-examples$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD ..." to unstage)

 modified:   CONTRIBUTING.md
 new file:   README

user@host:~/firstcup-examples$ 

Both files are staged

The git add command is used to:

  • to start traking new files
  • to stage modified files
  • to mark merge conflict as resolved

If you modify the CONTRIBUTING.md file again, the file will appear both in the staged files and in the unstaged files.

$ vim CONTRIBUTING.md
$ git status

On branch master
Your branch is up-to-date with 'origin/master'.
Changes to be committed:
  (use "git reset HEAD ..." to unstage)

    new file:   README
    modified:   CONTRIBUTING.md

Changes not staged for commit:
  (use "git add ..." to update what will be committed)
  (use "git checkout -- ..." to discard changes in working directory)

    modified:   CONTRIBUTING.md

Every time you modifiy a staged file, you have to run git add to stage the latest version of the file.

Ignoring Files

Suppose you have a class of file you don't want Git to automatically add to staging area or show as being untraked.

  • you can create a file named .gitignore with patterns of names of files that are to be ignored.

Below a sample .gitignore file for java projects.

# Compiled class file
*.class

# Log file
*.log

# Package Files #
*.jar
*.war
*.ear
*.zip
*.tar.gz
*.rar

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid* 

The first line tells Git to ignore any files ending in “.class” — class files that are the product of building your code. The second line tells Git to ignore log files, etc.

The rules for patterns in the .gitignore file use standard glob patterns that shells employ.

Viewing Your Staged and Unstaged Changes

The git diff command shows you what has changed, but is more accurate than the status command.

  • while the status command shows you which files are changed, the diff command shows you what is changed
  • the diff command shows you the patch: the lines of code added and removed.
  • use the git diff command to see:
    • what you have changed but not yet staged
    • what you have staged and you are going to commit

The command git diff without arguments shows you what you have changed but not yet staged

  • the command compares what is your working directory and what is in your staging area.

The command git diff --staged (or git diff --cached) shows you the changes you have staged and are going to be committed

  • this command compares the changes you have staged to your last commit
Committing Your Changes

When you want to take a snapshot of your project, commit your changes.

The simplest way to commit is to type the git commit command:

  • this launches the editor you configured with the git config --global core.editor command
  • the editor displays a default message:

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# On branch master
# Your branch is up-to-date with 'origin/master'.
#
# Changes to be committed:
#       modified:   CONTRIBUTING.md
#       new file:   README
#
~                         
~ 

The default message contains an empty line and the latest output of the git status command. If you run the command git commit -v , the -v option put the diff of your change in the commit message.

Alternatively, you can use the commit command with the -m flag and pass an inline message for the commit

  • for example: $ git commit -m "fix the xxx bug in the YYY file"

A commit records a snapshot of the changes you prepared in the staging area. Things in the working directory you didn't stage do not take part in the commit. You can always revert to or compare your project to a snapshot you previously recorded.

Removing Files

To remove a file from the git repository run the git rm <file> command

  • the git rm <file> command delete the file from working directory and staging area
  • after using the rm command, you have to commit the changes

The bash rm <file> command only remove the file from the working directory

How to make Git stop to trak a file and keep it in your working directory

  • to mark a file as untraked, it means the file is removed from the staging area
  • to stop traking a file run the git rm --cached <file> command
Moving Files

To rename a file in git use the git command: git mv <file-from> <file-to>

3 Viewing the Commit History

Viewing the Commit History

If you want to see the history of all the commits on a repository, use the git log command

The git log command (used without arguments) lists the commits made in a repository from the most recent to the oldest ones.

  • for each commit, it shows checksum, author, date and message

The git log command option -p or --patch shows the difference or patch for each commit.

The git log command option --pretty=<option> produces different output according to the option passed

  • for example git log --pretty=oneline produce a single line information
  • other options are --pretty=short, --pretty=full and --pretty=fuller
  • you can also pass a format string to specify your own output format
  • the --graph log option adds an ASCII graph showing branch and merge history

4 Working with Remotes

Working with Remotes

If you want to collaborate on a Git project, you must know how to handle remote repositories. A remote repository is a version of a project that is hosted on a machine connected to the internet or network. A Git project can have multiple remote repositories, each one is read-only or read/write.

Working with a remote repository implies:

  • pushing and pulling data to and from repositories
  • adding new repositories and removing invalid repositories
  • managing different branches

Note: it is possible to have a remote repository on the same host you are.

Showing Your Remotes

The git remote command lists which remote severs have been configured:

  • if your repository was cloned, the remote command prints origin
  • origin is the default name Git gives to the server from which your repository was cloned.
  • the -v option lists name and URL for each remote repository.
  • name and URL are used when reading and writing to that remote
user@host:~$ git clone https://github.com/javaee/firstcup-examples
Cloning into 'firstcup-examples'...
remote: Counting objects: 194, done.
remote: Total 194 (delta 0), reused 0 (delta 0), pack-reused 194
Receiving objects: 100% (194/194), 29.64 KiB | 210.00 KiB/s, done.
Resolving deltas: 100% (69/69), done.
user@host:~$ cd firstcup-examples/

The firstcup-example Java repository has only one remote.

user@host:~/firstcup-examples$ git remote
origin
user@host:~/firstcup-examples$ 

See name and URL of the remote of the firstcup-example repository

user@host:~/firstcup-examples$ git remote -v
origin https://github.com/javaee/firstcup-examples (fetch)
origin https://github.com/javaee/firstcup-examples (push)
user@host:~/firstcup-examples$ 

A repository with multiple remotes allows to work with many collaborators

  • you pull contributions from any remotes
  • you may additionaly have permission to push your commits, but you can't understand that here

If you run the git remote -v command on a repository with multiple remotes, the output is likely to look like this:

$ cd grit
$ git remote -v
backstab   https://github.com/backstab/grit (fetch)
backstab   https://github.com/backstab/grit (push)
cho45      https://github.com/cho45/grit (fetch)
cho45      https://github.com/cho45/grit (push)
merten     https://github.com/merten/grit (fetch)
merten     https://github.com/merten/grit (push)
softdrink  git://github.com/softdrink/grit.git (fetch)
softdrink  git://github.com/softdrink/grit.git (push)
origin     git@github.com:mojombo/grit.git (fetch)
origin     git@github.com:mojombo/grit.git (push)
Adding Remote Repositories

The git remote add <name> <url> command adds a new remote repository.

  • you can reference the remote you added by its name
  • you can use the remote's name in the command line, while executing commands to pull contributions
  • the git clone command implicitly adds that remote repository under the name "origin"
Fetching and Pulling from Your Remotes

The git fetch <name> command gets data from that remote repository.

  • after the command execution, you have all that remote's branches, which you can merge or inspect
  • the git fetch origin command pulls data from the origin remote, added when your repository was cloned

The git fetch command only download data the local repository and does not merge them.

  • the git fetch command does not modify the current working directory
  • you have to merge the downloaded data into your working directory manually

Git Branching

When you run the git command, Git creates a commit object and stores this object in the Git repository. If you commit again, the following commit stores a reference to the commit that came immediately before it. As you make more commits, the history of your project creates a stream of snapshots in the Git repository.

A branch in Git is simply a movable pointer to one of these commits. When you make the first commit, this creates a branch, which is named by default master. The master branch points to the last commit you made. Every time you commit, it moves forward automatically.

In versioning systems, the term branching is used to indicate that you diverge from the main line of development and continue to work and commit into a different line. In Git, the creation of a new branch implies the creation of a new pointer to commit objects.

If a repository has several branches, Git knows what branch you’re currently on by using a special pointer called HEAD. The HEAD is a pointer to the local branch you’re currently on: usually you are on master.

A Git 'tracking branch' is a local branch that is connected to a remote branch. When you push and pull on that branch, it automatically pushes and pulls to the remote branch that it is connected to

If your current branch tracks a remote branch, the git pull command fetches data from the remote and tries to merge that remote branch in your current branch.

  • as the git clone command implicitly sets your local master branch to track the master branch on the remote you cloned from, the git pull command fetches data from the origin remote and automatically tries to merge it into your working tree
  • generally, it’s better to use the fetch and merge commands explicitly than the pull command
Pushing to Your Remotes

To share your work, you push the commits you have done to a remote that you have write access.

The git push <name> <branch> command pushes the branch to the remote with that name

  • for example: git push origin master pushes the master branch to the origin remote
$ git push origin master

The above push command works only if nobody has pushed since you cloned your repository.
If somebody has already cloned and pushed:

  • your push will be rejected
  • you have to fetch their work and merge it with yours, before being allowed to push
Inspecting a Remote

The git remote show <name> command shows information about a remote repository.

  • for example: git remote show origin
  • the output lists: the URL for the remote repository, traking branches and how your local branches are configured for the push and pull commands

An output of the git remote show command may look like below:

$ git remote show origin
* remote origin
  Fetch URL: https://github.com/schacon/ticgit
  Push  URL: https://github.com/schacon/ticgit
  HEAD branch: master
  Remote branches:
    master tracked
    dev-branch tracked
  Local branch configured for 'git pull':
    master merges with remote master
  Local ref configured for 'git push':
    master pushes to master (up to date)
Renaming and Removing Remotes

The command git remote rename <from-name> <to-name> change a remote's name.

  • when you rename a remote also tracking branches are renamed

The command git remote remove <name> removes a remote.

  • when you remove a remote, you also remove tracking branches with that remote

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

Git vs GitHub

Git e GitHub sono due cose diverse: GitHub e' un servizio online basato su Git, ma non e' 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 e' gratuito, l'hosting privato e' a pagamento. Per questo motivo gli sviluppatori usano altri servizi online per condividere repository Git, come GitLab.com e bitbucket.org.

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.

Per creare la cartella di progetto ed inizializzare un nuovo repository Git, lancio il comando:

 git init myproject

Lo sviluppatore modifica il file nella working directory: lo sviluppatore effettua n modifiche al file. Dopo n tentativi, la versione n-ima compila e/o produce il risultato aspettato, per cui lo sviluppatore sposta il file in Staging.

Per spostare un file dalla working directory allo Staging si lancia il comando git add:

 git add <filepath>

Il comando git add non modifica in modo permanente il repository, ma specifica solo che il file parteciperá alla prossima commit.

Si puó utilizzare il comando git add per piú obbiettivi: incominciare a fare tracking di un file, aggiungere un file alla Staging Area e marcare i conflitti di merging come risolti.

Committare i file nel repository locale

Lo sviluppatore ha modificato alcuni file, i file di cui e' soddisfatto delle modifiche apportate si trovano nella Staging area, i file che richiedono ancora delle modifiche si trovano nella working directory. Siccome lo sviluppatore ha terminato la sessione di lavoro, vuole registrare uno snapshot del progetto e per fare cio' lo sviluppatore sposta i file dallo staging al repository.

Per committare tutti i file che si trovano nella Staging Area, si lancia il comando commit:

 git commit

Supponiamo che lo sviluppatore stia modificando uno staged file nella working directory, non vuole fare il commit del file perche' non ha ancora finito di lavorare sul file, ma vuole cambiare branches per lavorare su qualcos'altro. A questo punto, se lo sviluppatore non vuole salvare il lavoro incompleto nel repository, puo' salvare lo stato della Working Directory nello Stashing. In futuro lo sviluppatore puo' ripristinare lo stato della Working Directory dallo Stashing.

Per spostare i files dalla Working Directory allo Stashing uso il comando:

 git stash 

Per spostare i files dallo Stashing alla Working Directory uso il comando:

 git stash pop
Il workflow di Git
Gli stati di un file: committed, modified, staged

Un file nuovo, appena creato, per Git si trova nello stato untraked. Quando si sposta il file nella Staging area con git add, il file si trova nello stato staged. Quando si committa il file nel database, il file si trova nello stato committed. Se il file si trova nello stato staged o committed e viene editato, Git segnala che esiste una copia del file nel working tree nello stato modified.

2. Comandi Base di Git con esempio step-by-step

Vediamo come creare di un nuovo local repository Git, partendo da zero.

 cd  progetto-con-git/
 git init

Vediamo cosa ha fatto il comando git init, lanciando il comando ls: Git ha creato la cartella di progetto di nome progetto-con-git. Se mi sposto all'interno della cartella di progetto e lancio il comando ls -la, vedo la cartella di sistema di nome .git, che contiene i file che controllano le versioni storiche dei file di progetto, lo snapshots di documenti, immagini, sorgenti, etc.

Creo di un nuovo file chiamato my-file.txt, usando l'editor di testo nano.

 cd progetto-con-git
 nano my-file.txt 

Per vedere lo stato del working tree:

 git status

Si puo' leggere che sono sul ramo master, git segnala il file appena creato come untraked.

Il file e' pronto, per cui lo invio alla staging area (anche detta index):

 git add my-file.txt

Lancio ancora git status per vedere lo stato della working directory. Si puo' leggere che sono sul ramo master, il nome del file non e' piu' rosso ma verde e non ci sono commit ancora.
Inoltre, git suggerisce di usare il comando "git rm --cached <file>..." per rimuovere il file appena aggiunto dalla Staging area. Si provi ad usare il comando git rm per rimuovere il file dalla staging area.

Una volta copiato il file nella staging area, proviamo a modificare lo stesso file nella working directory. Per cui apriamo il file con l'editor di testo, lo modifichiamo e lo salviamo di nuovo. Lancio il comando git status e vedo che nello staging area c'é ancora il my-file.txt pronto per il commit, ma nel working tree c'é di nuovo my-file.txt nello stato modified pronto per essere aggiunto alla staging area per aggiornare la prossima commit.

Quindi, eseguo di nuovo git add . per avere tutte le modifiche pronte nella staging area.

Per committare le modifiche, uso il comando:

 git commit

Il comando apre l'editor di testo preferito allo scopo di inserire il messaggio relativo a quel commit. Posso decommentare la riga "# Initial commit" ed inserire un mio messaggio sulla prima riga.

Ogni volta che si fa un commit in Git, quel commit ha un commento ed un codice: il commento e' il messaggio che si aggiunge al commit e commenta le modifiche fatte, il codice e' autogenerato da Git. Il codice del commit serve nel caso in cui si vuole tornare indietro e ripristinare lo stato del progetto al momento del commit con uno specifico commento.

Eseguire git commit con flag -m

Se eseguo di nuovo git status, appare il messaggio: "nothing to commit, working tree clean", che vuol dire che non ci sono modifiche da committare.

Poi, creo un altro file di nome "second-file.txt", lo aggiungo alla staging area e infine faccio la commit. Questa volta lancio il comando commit con il parametro -m, per evitare di inserire il messaggio con l'editor di testo .

 git commit -m 'added second-file.txt'

Per vedere lo storico delle modifiche in Git posso usare il comando:

 git log

Che mosta tutte le commit effettuate nel repository corrente con rispettivo codice e nome.

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, October 20, 2017

Java EE Component Model

1 Component-Based Development

The Java EE platform supports component-based development
  • component-based development is based on the principle of loose coupling
  • loosely coupled systems are easy to test and maintain

2 Java EE Components

A Java EE component is a group of classes and interfaces that implements a single functionality

  • a component is assembled into a Java EE application, with its related classes and files
The java EE specifications define different types of components:
  • Application clients and applets are components that run on the client.
  • Java Servlet, JavaServer Faces, and JavaServer Pages (JSP) technology components are web components that run on the server.
  • EJBs components (enterprise beans) and Entity classes are business components that run on the server.

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

Generating a simple project with Maven and Eclipse

To generate a project with maven from command line:

 mvn -B archetype:generate \
-DarchetypeGroupId=org.apache.maven.archetypes \
-DarchetypeArtifactId=maven-archetype-quickstart \
-DgroupId=com.mycompany.application \
-DartifactId=maven-project \
-Dpackage=com.mycompany.application \
-Dversion=1.0
  • 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