Friday, July 24, 2015

Java - ArrayList constructors and methods example

ArrayList is a dynamic array that implements the List interface that is a sorted collection that the user of this interface has total control over the inserted elements and position by accessing and searching for items in the list.

ArrayList implements all methods List, more than that, the class has its own methods such as manipulating the size of the array used to store the list. This class is equivalent to Vector.
Arraylist uses an array that stores data, this table has a capability that automatically adapts to each time an item is inserted. There is a ensureCapacity method that increases the capacity of ArrayList before adding many elements to ensure the size.

Access to the list is made simultaneously by multiple threads. This can cause problems when it comes to a change, insert, delete because another thread will access and update the size of the list is underway. The solution is synchronization process using the Collections.synchronizedList method.

List list = Collections.synchronizedList(new ArrayList(...));

To browse the list with the iterator class or ListIterator, but if the list has changed: delete, insert ... after creating iterator, it will trigger a ConcurrentModificationException exception. The solution is to create a mutual exclusion with the aim to prevent other threads to access it after creating iterator and during playback.

ArraylList Consturctors

ArrayList three manufacturer:

- ArrayList (): creates an empty list with an initial size of 10.
- ArrayList (<? Extends E> Collection c) Creates a list from a collection of data and returns a NullPointerException if the collection is zero.
- ArrayList (int size) Creates a list by setting the initial size and returns an IllegalArgumentException if size is negative.

ArrayList Methods

1) add(Object o): add element in the end.
list.add("hello");

2) add(int indice, Object o): insert element in the middle
list.add(2, "hi");
It insert the string in the second position of the list.

3) addAll(Collection c): add a collection to the list.
ArrayList toadd = new ArrayList();
l1.add("e1");
l1.add("e2");
l1.add("e3");
list.addAll(toadd);
This operation add a list toadd to the end of the list.

4) addAll(int indice, Collection c): insert a collection c in the middle
list.addAll(3, l1);
this method insert the collection l1 in the fourth position of the list.

5) clear(): remove all elements from the list.

6) contains(Object o): return true if the searched object o is in the list.
boolean b = list.contains(o)

8) ensureCapacity(int capacite): set and ensure the minimum capacity.
list.ensureCapacity(8);
This will ensure at least 8 elements.

9) get(int index): return object at the specific position.
system.out.println(list.get(3));
This will print the object at the third position.

10) indexOf(Object o): search and return the first occurrece of object o.
int k = indexOf("o2");

11) isEmpty(): if the list is empty, this method return true.
boolean empty = list.isEmpty();

12) remove(Object o): remove the first occurrence of object o.
boolean b = list.remove("o3");
This wil return true if the object o3 is found and deleted with success.

13) removeAll(Collection<?> c): remove all elements that belong to collection c.
AarrayList<String> c = new ArrayList<String>();
c.add("o1");
c.add("o2");
c.add("o3");
list.removeAll(c);

14) removeRange( int startIndex, int endIndex): remove elements between startIndex and endIndex.
list.removeRange(4,7);
This method remove elements between 4 and 7.

15) retainsAll(Collection<?> c):  retain only elements that belong to collection c.

16) set(int index, Object o): set object value in a specific index.
list.set(2, "o4");
object in position 2 has been replaced with value "o54.

17) size(): return the arralist size.

18) subList(int startIndex, int endIndex): return a sublist that belong between startIndex and endIndex.

19) toArray(): create an array from ArrayList.
String[] t = list.toArray();
Result array contains all elments of ArrayList. This method is usefull when you use a method that accept only array type argument.

20) trimToSize(): reduce the storage capacity to its miminum.

How to iterate through ArrayList

We can use two methods:

1) for loop

for(int i = 0; i < list.size(); i++)
    system.out.println(list.get(i));
//if we use generic type. In this example an Integer (ArrayList<Integer>)
for(Integer digit: list)
    system.out.println(digit);

2) Iterator+ while loop

Iterator itr = list.iterator();
while(itr.hasNext())
      system.out.println(itr.next());

ArrayList Exemple

import java.util.ArrayList;

public class Test {

 public static void main(String[] args) {
  
  //create ArrayList with generic string type
  ArrayList<String> stringList= new ArrayList<String>();
  //add elements to arraylist
  stringList.add("e1");
  stringList.add("e2");
  stringList.add("e3");
  stringList.add("e4");
  stringList.add("e5");

  //operations example
  System.out.println("e1 exist ? "+stringList.contains("o3"));
  System.out.println("index of "+"o2: "+stringList.indexOf("o2"));
  System.out.println("e5 is deleted: "+stringList.remove("o2"));
  System.out.println("arraylist size: "+stringList.size());
  System.out.println("sublist[0, 2] : "+stringList.subList(0, 2));
  
  //loop arraylist
  for(String s : stringList)
     System.out.println(s);

  stringList.clear();
  System.out.println("is empty ? "+stringList.isEmpty());
 }
}
Output:
e1 exist ? false
index of o2: -1
e5 is deleted: false
arraylist size: 5
sublist[0, 2] : [e1, e2]
e1
e2
e3
e4
e5
is empty ? true

Java socket programming: create client/server chat application

In this tutorial you will learn how to create a java chat between two hosts using sockets, as well as your network configuration in order to communicate two machines on the local network of your home for example. We will implement what we saw in theory: Client / Server model.

At the end of this tutorial you will be able to know how sockets can exchange messages.

1- Java Server

The java server initiates the connection and launches listening on a port and waits for incoming connections to accept. For example, the port number is 5000, the client sends a request to the server with the port number 5000. The server accepts the request and forwarded his information (IP address) to the client. Now connection is established and an exchange of messages can be done.

Java has a java.net package that processes the network, we need only two classes:
  • java.net.ServerSocket: accepts connections goings of clients.
  • java.net.Socket: allows connection to the remote machine.
We also need tools to capture, send and receive the stream:
  • Scanner: read keyboard input.
  • BufferedReader: read the text received from the transmitter.
  • PrintWriter: send the text entered.

ServerSocket serverSocket;
Socket socket;
Final BufferedReader in;
final PrintWriter out;
Final Scanner sc = new Scanner (System.in);
try {
    serverSocket = new ServerSocket (5000);
    serverSocket.accept = ();
    out = new PrintWriter ( .getOutputStream ());
    in = new BufferedReader (new InputStreamReader ( .getInputStream ()));
    String s;
    s = sc.next ();
    System.out.println (s);
    out.flush ();
    String receivedmessage;
    receivedmessage in.readLine = ();
    System.out.println ("Client:" + receivedmessage);
    }
catch (IOException e) {
  e.printStackTrace ();
}

After creating the server socket that carries the port number 5000, the server waits for incoming connections and as soon as one is found, he accepts it. in and out are initialized so that they are directly connected with the sending and receiving streams.
Variable 's' stores the entered text with the next() method, and then sent to the println (s) method.
The flush() method is important because it flushes the write buffer to the output if a null value will be received by the other side.
The receivedmessage variable stores the received message is displayed with println() method.

The limit of this code is that it is able to send and receive a message once. You will have an idea in the head: to make a while loop (true). This is true, but if for example the server sends to the client, the client can not retrieve the message until it has sent also. The optimal solution is to create two threads: one for sending and one for receiving. Both processes allow the sending and receiving are done simultaneously.

java.io.BufferedReader import;
import java.io.IOException;
java.io.InputStreamReader import;
java.io.PrintWriter import;
java.net.ServerSocket import;
java.net.Socket import;
java.util.Scanner import;
/ *
 * javaisback.blogspot.com
 * /
public class Server {

   public static void main (String [] test) {
 
     ServerSocket final serverSocket;
     Socket final clientSocket;
     Final BufferedReader in;
     final PrintWriter out;
     Final Scanner sc = new Scanner (System.in);
 
     try {
       serverSocket = new ServerSocket (5000);
       clientSocket serverSocket.accept = ();
       out = new PrintWriter (clientSocket.getOutputStream ());
       in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
       Thread sending = new Thread (new Runnable () {
          String msg;
          Override
          public void run () {
             while (true) {
                sc.nextLine msg = ();
                System.out.println (msg);
                out.flush ();
             }
          }
       });
       envoi.start ();
 
       Thread receive = new Thread (new Runnable () {
          String msg;
          Override
          public void run () {
             try {
                in.readLine msg = ();
                // As the client is connected
                while (msg! = null) {
                   System.out.println ("Client:" + msg);
                   in.readLine msg = ();
                }
                // Exit the loop if the client connection is ended
                System.out.println ("Client deconected");
                // Close the stream and socket session
                out.close ();
                clientSocket.close ();
                serverSocket.close ();
             } Catch (IOException e) {
                  e.printStackTrace ();
             }
         }
      });
      receive.start ();
      } Catch (IOException e) {
         e.printStackTrace ();
      }
   }
}

The separation of the two processes is clear, the Server and the Client can exchange data at any time and infinitely. The while loop reading tests if the connection is not yet established if not forget to close your streams reading and writing as well as the connection after the exit of the while loop with close() method.

2- Java Client

The client side needs only the Socket class to establish the server connection, the constructor takes as input the server IP address and port number. The rest of the code is the same as that of the server.

java.io.BufferedReader import;
import java.io.IOException;
java.io.InputStreamReader import;
java.io.PrintWriter import;
java.net.Socket import;
java.util.Scanner import;
/ *
 * javaisback.blogspot.com
 * /
public class Client{

   public static void main (String [] args) {
   
      Socket final clientSocket;
      Final BufferedReader in;
      final PrintWriter out;
      Final Scanner sc = new Scanner (System.in); // to read from the keyboard

      try {
         / *
         * Server informations (port and IP address or host name
         * 127.0.0.1 is the host local address
         * /
         clientSocket = new Socket ("127.0.0.1", 5000);
 
         // Flow to send
         out = new PrintWriter (clientSocket.getOutputStream ());
         // Feed to receive
         in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
 
         Thread send = new Thread (new Runnable () {
             String msg;
              Override
              public void run () {
                while (true) {
                  sc.nextLine msg = ();
                  System.out.println (msg);
                  out.flush ();
                }
             }
         });
         send.start ();
 
        Thread receive = new Thread (new Runnable () {
            String msg;
            Override
            public void run () {
               try {
                 in.readLine msg = ();
                 while (msg! = null) {
                    System.out.println ("Server:" + msg);
                    in.readLine msg = ();
                 }
                 System.out.println ("Server deconected");
                 out.close ();
                 clientSocket.close ();
               } Catch (IOException e) {
                   e.printStackTrace ();
               }
            }
        });
        receive.start ();
 
      } Catch (IOException e) {
           e.printStackTrace ();
      }
  }
}

Output:

create java chat server using sockets
Server
create java chat client using sockets
Client
If you work on the same machine you need to run Eclipse twice. one for the server and one for the client.

Saturday, July 18, 2015

Apache POI: How to create, write and read excel file in java

Typically, spreadsheets are widely used in finance domain and accounting to facilitate the calculation and creation of bills, management reports, etc. If part of your required application of such operations: creation, reading or writing, several API are available and most efficient is Apache POI API.

The API also manages POI Word and PowerPoint documents, over time users have had more confidence.

Download Apache POI API

You can download Apache POI. Then, import  the following .jar into your project:
- poi
- poi-OOXML
- poi-OOXML-schemas
- xmlbeans

Create and write

The two main classes which processes the Excel file are:

HSSFWorkbook: for Microsoft Excel 97 and 2003 files with xls extension.
XSSFWorkbook: for Microsoft Excel 2007 with .xlsx file extension.

The following code creates an excel file with the values of different types:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class writeDemo{
    public static void main(String[] args) {
   
       //create a blanc document
       XSSFWorkbook wb = new XSSFWorkbook();
       //create a black sheet
       Sheet sheet = wb.createSheet("new sheet");
       //create a new row 0
       Row row = sheet.createRow((short)0);
       //create a new cell
       Cell cell = row.createCell(0);
       //insert value in the created cell
       cell.setCellValue(1.4);
   
       //add other cells with different types
       /*int*/row.createCell(1).setCellValue(7);
       /*int*/row.createCell(2).setCellValue(99);
       /*string*/row.createCell(3).setCellValue("string");
       /*boolean*/row.createCell(4).setCellValue(true);

       FileOutputStream fos;
       try {
         fos= new FileOutputStream("newFile.xlsx");
         wb.write(fos);
         fos.close();
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }
    }
}
create excel file with java

The date to be inserted and the current time, the date format is created as follows:

//insert value in cell F1
cell = row.createCell((short) 6);
cell.setCellValue(new Date());
XSSFCellStyle cellStyle = wb.createCellStyle();
XSSFDataFormat xssfDataFormat = wb.createDataFormat();
//create date and time format
cellStyle.setDataFormat(xssfDataFormat.getFormat("dd/mm/yyyy h:mm"));
cell.setCellStyle(cellStyle);
insert date in excel file with java

Text Formatting

Text formatting includes: font, size, Italic / Bold / Underline, color, background and alignment.

Here is an example of alignment that will be applied to the cell Date:

//Row high
row.setHeightInPoints(20);
//horizontal alignement 
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
//vertical alignement
cellStyle.setVerticalAlignment(CellStyle.VERTICAL_TOP);
text formating excel java

Create new font

/*create a new font*/
Font font = wb.createFont();
//size: 13px
font.setFontHeightInPoints((short)13);
font.setFontName("Courier New");
font.setItalic(true);
font.setBold(true);

/*create a new style*/
CellStyle cs = wb.createCellStyle();
cs.setFont(font);
//apply the style to cell 3(D1)
row.getCell(3).setCellStyle(cs);
change the excel font with java

Background color

/*change the background color*/
XSSFCellStyle csColor = wb.createCellStyle();
csColor.setFillForegroundColor(new XSSFColor(new Color(194, 154, 250)));
csColor.setFillPattern(csColor.SOLID_FOREGROUND);
//apply to the cell 3
row.getCell(2).setCellStyle(csColor);
        
/*change font color*/
Font font = wb.createFont();
font.setColor((short)45);
CellStyle csCF = wb.createCellStyle();
csCF.setFont(font);
//apply style to cell 0
row.getCell(0).setCellStyle(csCF);
change background color excel with java

Merging cells

In this example, we will merge, center horizontally and vertically four cells B2, C2, B3 and C3 with the addMergedRegion method that takes as parameters the range of cells to be fused.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;

public class mergingCells{

   public static void main(String[] args) throws FileNotFoundException {
       Workbook wb = new HSSFWorkbook();
       Sheet sheet = wb.createSheet("sheet1");

       Row row = sheet.createRow((short) 1);
       Cell cell = row.createCell((short) 1);
       cell.setCellValue("testing merge cells");

       sheet.addMergedRegion(new CellRangeAddress(
             1, //first row B2
             2, //last row B3
             1, //first column C2
             2  //last column C3 
       ));
       /*Center alignment*/
       cell.getCellStyle().setAlignment((short)2);
       cell.getCellStyle().setVerticalAlignment((short)1);
     
       FileOutputStream fs = null;
       try {
         fs = new FileOutputStream("Mergingdemo.xlsx");
         wb.write(fs);
         fs.close();
       } catch (IOException e) {
          e.printStackTrace();
       }
   }
}
merge cells in excel with java

Using Formulas

Excel is primarily used in the calculation and use of sometimes complex formulas in cells result. Apache poi provides a very effective means to add and test cells with their formulas.

The following code handles a simple calculation of the average 4 semesters. The formula is (A2 + B2 + C2 + D2) / 4.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class FormulaDemo{

  public static void main(String[] args) {
     XSSFWorkbook wb = new XSSFWorkbook();
     XSSFSheet sheet = wb.createSheet("Average");

     Row row = sheet.createRow((short) 0);
     row.createCell(0).setCellValue("January");
     row.createCell(1).setCellValue("February");
     row.createCell(2).setCellValue("March");
     row.createCell(3).setCellValue("April");
     row.createCell(4).setCellValue("Average");
     
     Row row1 = sheet.createRow((short) 1);
     row1.createCell(0).setCellValue(4.5);
     row1.createCell(1).setCellValue(15.4);
     row1.createCell(2).setCellValue(3.4);
     row1.createCell(3).setCellValue(6);
     row1.createCell(4).setCellFormula("(A2+B2+C2+D2)/4");

     try {
         FileOutputStream out = new FileOutputStream(new File("formulademo.xlsx"));
         wb.write(out);
         out.close();
         System.out.println("Le fichier excel a été créé avec succés");
           
     } catch (FileNotFoundException e) {
         e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
     }
  }
}
using formula in excel with java

Evaluate and browse cells

To view the value of a cell, you must know its type. Apache poi provides FormulaEvaluator.evaluateFormulaCell class that checks if the cell contains a formula. If so, it evaluates and returns the type of the formula.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class IterateDemo{

    public static void main(String[] args) throws IOException {
       FileInputStream fichier = new FileInputStream(new File("formuladomo.xlsx"));
       //create workbook instance that refers to xlsx file
       XSSFWorkbook wb = new XSSFWorkbook(fichier);
       XSSFSheet sheet = wb.getSheetAt(0);
  
       FormulaEvaluator formulaEvaluator = 
                     wb.getCreationHelper().createFormulaEvaluator();
  
       for (Row ligne : sheet) {//iterate rows
         for (Cell cell : ligne) {//iterate columns
           //cell type
           switch (formulaEvaluator.evaluateInCell(cell).getCellType())
           {
                 case Cell.CELL_TYPE_NUMERIC:
                     System.out.print(cell.getNumericCellValue() + "\t\t");
                     break;
                 case Cell.CELL_TYPE_STRING:
                     System.out.print(cell.getStringCellValue() + "\t");
                     break;
           }
         }
         System.out.println();
       }  
    }
}
Execution:

January February March April Average
4.5  15.4  3.4  6.0  7.325 
For more informations read from apache documentation http://poi.apache.org/spreadsheet/quick-guide.html