4/15/2014

Java - SDK 8 New Features

Hi,

This code shows some of the coolest features of the SDK 8.

As you can see functional methods have been added and will facilitate our work.

Yeeeeeaaaaay

 package uk.ac.imperial.cup.main;  
 import java.util.Comparator;  
 import java.util.List;  
 import java.util.ArrayList;  
 import java.util.Optional;  
 public class Main {  

   public static void main(String[] args) {  
     List<People> peoples = populateList();  
     peoples.stream()  //USE OF STREAM, THE SAME AS PIPE IN LINUX|UNIX
         .filter((People p) -> p.getLastName().equals("Stevens")) //FILTER PEOPLE WITH STEVENS AS LAST NAME
         .sorted(Comparator.comparing(People::getFirstName).reversed()) //SORT FILTERED LIST BY FIRST NAME DESC  
         .forEach((People p) -> System.out.println(p.toString()));  //PRINT EACH ELEMENT OF THE SORTED AND FILTERED LIST
    }  

   private static java.util.List<People> populateList() {  
     java.util.List<People> peoples = new ArrayList<People>();  
     peoples.add(new People("Christophe", "Stevens", Optional.ofNullable(28))); //CREATE AN OPTIONAL IN CONSTRUCTOR 
     peoples.add(new People("Vincent", "Stevens", Optional.ofNullable(30)));  
     peoples.add(new People("Kilye", "Minogue", Optional.ofNullable(45)));  
     peoples.add(new People("William", "Adams", Optional.ofNullable(39)));  
     peoples.add(new People("Tom", "Jones", Optional.ofNullable(73)));  
     peoples.add(new People("Ricky", "Wilson", Optional.ofNullable(null)));  
     return peoples;  
   }  
 }  
 class People  
 {  
   private String FirstName, LastName;  
   private Optional<Integer> Age;  //DECLARING AN OPTIONAL
   public People(String firstName, String lastName, Optional<Integer> age) {  
     FirstName = firstName;  
     LastName = lastName;  
     Age = age;  
   }  
   public String getFirstName() {  
     return FirstName;  
   }  
   public void setFirstName(String firstName) {  
     FirstName = firstName;  
   }  
   public String getLastName() {  
     return LastName;  
   }  
   public void setLastName(String lastName) {  
     LastName = lastName;  
   }  
   public Optional<Integer> getAge() {  
     return Age;  
   }  
   public void setAge(Optional<Integer> age) {  
     Age = age;  
   }  
   //TESTING IF OPTIONAL IS PRESENT WITH TERNARY OPERATOR
   @Override  
   public String toString()  
   {  
     return String.format("%s, %s %s", getLastName(), getFirstName(), getAge().isPresent()?getAge().get() + " year":"");  
   }  
 }  

3/20/2014

JAVA - Read A Huge Excel Files (xlsx-XSSF) with SAX parser (avoid gc limit exceeded)

I adapted a piece of code I found on internet in order to read a huge Excel file without facing a "gc limited exceeded" as I always got in POI.

My test file was 42,723 rows long. 

It would be a great idea for you, to browse a xlsx file first. The understanding of the sheets and xml elements and attributes names is important.

To do that:
  1.  rename your .xlsx file in .zip file.
  2. Extract the content of your zip file in a folder.
  3. Open the xl\worksheets\sheets1.xml (Notepad++ is recommanded)
  4. Open the xl\sharedStrings.xml (Notepadd++ is recommanded)
You just have to understand that the parser will throw the startElement and endElement while starting or finishing  to read an xml element in sheets1.xml. When ending the reading of a "v" element (index of the value of a cell) it will retrieve the string value in sharedStrings.xml with the code " new XSSFRichTextString(sst.getEntryAt(idx)).toString()"

After you can adapt the code to your own business objects depending of your organisation in cells.

Have fun! (But don't forget to work :D )


 package BL.Parser;  
 import BO.Files.ExcelPublicationFile;  
 import BO.Publication.RisPublication;  
 import org.apache.poi.openxml4j.opc.OPCPackage;  
 import org.apache.poi.xssf.eventusermodel.XSSFReader;  
 import org.apache.poi.xssf.model.SharedStringsTable;  
 import org.apache.poi.xssf.usermodel.*;  
 import org.xml.sax.*;  
 import org.xml.sax.helpers.DefaultHandler;  
 import org.xml.sax.helpers.XMLReaderFactory;  
 import java.io.*;  
 import java.util.ArrayList;  
 import java.util.Iterator;  
 import java.util.List;  
 /**  
  * Created by casteven on 19/03/14.  
  */  
 public class ExcelPublicationFileParser  
 {  
   public ExcelPublicationFile ParseFile(ExcelPublicationFile file) throws Exception {  
     OPCPackage pkg = OPCPackage.open(file);  
     XSSFReader r = new XSSFReader( pkg );  
     SharedStringsTable sst = r.getSharedStringsTable();     //XML file containing all the String values, referenced by index  
     XMLReader parser = fetchSheetParser(sst);  
     Iterator<InputStream> sheets = r.getSheetsData();  
     //Browsing sheets 1  and extracting data.  
     if (sheets.hasNext())  
     {  
       InputStream sheet = sheets.next();  
       InputSource sheetSource = new InputSource(sheet);  
       parser.parse(sheetSource);  
       sheet.close();  
     }  
     file.setPublications(SheetHandler.getPubs());  
     return file;  
   }  
   public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {  
     XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");  
     ContentHandler handler = new SheetHandler(sst);  
     parser.setContentHandler(handler);  
     return parser;  
   }  
   /**  
    * See org.xml.sax.helpers.DefaultHandler javadocs  
    */  
   private static class SheetHandler extends DefaultHandler {  
     private SharedStringsTable sst;  
     private String lastContents;  
     private RisPublication pub=new RisPublication();  
     private static List<RisPublication> pubs=new ArrayList<RisPublication>();  
     private int column=0;  
     private int row=0;  
     private SheetHandler(SharedStringsTable sst) {  
       this.sst = sst;  
       pubs=new ArrayList<RisPublication>();  
     }  
     /*  
       GETTER AND SETTER  
     */  
     public static List<RisPublication> getPubs() {  
       return pubs;  
     }  
     public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException  
     {  
       // Clear contents cache  
       lastContents = "";  
     }  
     public void endElement(String uri, String localName, String name) throws SAXException {  
       // v => index of the content of a cell.  
       if(name.equals("v")) {  
         try {  
           int idx = Integer.parseInt(lastContents); //Catch the ID in int  
           lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString(); // Get the value referenced by index ()  
         } catch (NumberFormatException e) {  
         }  
       }  
       //If we are reading a cell and columns is not the first  
       if(name.equals("c") && row>0) {  
         switch (column)  
         {  
           case 0:pub.setU3(lastContents);  
             break;  
           case 1:pub.setU4(lastContents);  
             break;  
           case 2:pub.setID(lastContents);  
             break;  
           case 3:pub.setT1(lastContents);  
             break;  
           case 4:String author=lastContents;  
             List<String> authors=Util.List_Util.convertCommaSeparatedStringToListOfString(author);  
             for (String s:authors)  
               pub.addA1(s);  
             break;  
           case 5:pub.setY1(lastContents);  
             break;  
           case 6:pub.setN2(lastContents);  
           case 7:String keyword=lastContents;  
             List<String> keywords=Util.List_Util.convertCommaSeparatedStringToListOfString(keyword);  
             for (String s:keywords)  
               pub.addKW(s);  
             break;  
           case 8:pub.setJF(lastContents);  
             break;  
           case 9:pub.setJA(lastContents);  
             break;  
           case 10:pub.setVL(lastContents);  
             break;  
           case 11:pub.setIS(lastContents);  
             break;  
           case 12:pub.setSP(lastContents);  
             break;  
           case 13:pub.setEP(lastContents);  
             break;  
           case 14:pub.setCY(lastContents);  
             break;  
           case 15:pub.setPB(lastContents);  
             break;  
           case 16:pub.setSN(lastContents);  
             break;  
           case 17:pub.setM1(lastContents);  
             break;  
           case 18:pub.setU1(lastContents);  
             break;  
           case 19:pub.setU2(lastContents);  
             break;  
           case 20:pub.setU5(lastContents);  
             break;  
           case 21:pub.setUR(lastContents);  
         }  
         column++;  
       }  
       //If it is the end of a row, save the current publication. An create a new one  
       if(name.equals("row")) {  
         if (row>0)  
           pubs.add(pub);  
         pub=new RisPublication();  
         row++;  
         column=0;  
       }  
     }  
     //Extracting the content of an element  
     public void characters(char[] ch, int start, int length) throws SAXException {  
       lastContents += new String(ch, start, length);  
     }  
   }  
 }  

3/13/2014

JavaScript - Direction and Show Map on SmartPhone Native App

Hi,

Here is the code I used on the new Mobile version of www.belle-campagne.be

The first method is used to detect whether or not the accessing device is a Computer or a Smartphone (only the size of the screen is considered)

The 2 other method launch the native maps application in Windows Phone, IOS 6-7, Android.

Have fun and keep coding!

Christophe



 function redirect()  
 {  
      if ( (screen.width > 1024) && (screen.height > 768) )   
      {   
       window.location = 'http://www.belle-campagne.be/index.html';  
      }   
 }  
 function openInMap()  
 {  
   if( (navigator.platform.indexOf("iPhone") != -1)   
     || (navigator.platform.indexOf("iPod") != -1))  
     window.open("http://maps.apple.com/maps?q=50.3258755,5.593183&z=11");  
   else if (navigator.platform.indexOf("Win32") != -1)   
     window.open("explore-maps://v2.0/show/place/?latlon=50.3258755,5.593183&zoom=11");  
      else  
      {  
           var ua = navigator.userAgent.toLowerCase();  
           var isAndroid = ua.indexOf("android") > -1;  
           if(isAndroid)   
                window.open('http://maps.google.com/maps?q=50.3258755,5.593183&z=2');  
           else  
                window.open("comgooglemaps://?center=50.3258755,5.593183&zoom=11&views=traffic");  
      }  
 }  
 function showRouteInMap()  
 {  
   if( (navigator.platform.indexOf("iPhone") != -1)   
     || (navigator.platform.indexOf("iPod") != -1))  
     window.open("http://maps.apple.com/maps?daddr=50.3258755,5.593183");  
   else if (navigator.platform.indexOf("Win32") != -1)   
     window.open("directions://v2.0/route/destination/?latlon=50.3258755,5.593183");  
      else  
      {  
           var ua = navigator.userAgent.toLowerCase();  
           var isAndroid = ua.indexOf("android") > -1;  
           if(isAndroid)   
                window.open('http://maps.google.com/?daddr=50.3258755,5.593183&directionsmode=transit');  
           else  
                window.open("comgooglemaps://?daddr=50.3258755,5.593183&directionsmode=transit");  
      }  
 }  

12/02/2013

Excel - Switching Row Foreground Color for each new value


This code permit to switch the text color each time a row have a different value.

Here the column considered for changement is the column "B"

cheers

 Sub test()  
   Dim currWCRFCode$  
   Call InitilizeColor  
   currWCRFCode = Range("B2").Value  
   For i = 2 To Range("B65536").End(xlUp).row  
     If (currWCRFCode <> Range("B" & i).Value) Then  
        Call incrementColorIndex  
     End If  
     Call setFont(i)  
     currWCRFCode = Range("B" & i).Value  
   Next i  
 End Sub  

 Private Sub setFont(ByVal row As Long)  
   Rows(row & ":" & row).Select  
    With Selection.Font  
     .color = getColor()  
     .TintAndShade = 0  
   End With  
 End Sub  

 Private Function getColor() As Long  
   getColor = colorsArray(currColorIndex)  
 End Function  

 Private Sub incrementColorIndex()  
   If (currColorIndex = 2) Then  
     currColorIndex = 0  
   Else  
     currColorIndex = currColorIndex + 1  
   End If  
 End Sub 
 
 Private Sub InitilizeColor()  
   currColorIndex = 0  
   colorsArray(0) = RGB(0, 0, 0)  
   colorsArray(1) = RGB(152, 14, 138)  
   colorsArray(2) = RGB(28, 152, 14)  
 End Sub  

10/23/2013

Excel - Wedding Count Down

Hi,

I will wed soon and it pass thru my mind that make a countdown in Excel could be a good idea.


Here is How to do it:

  1. Right Click on the Cell and change The Format to
        As you the character with a special meaning has been escaped... (d day, s second, h hour, ....)

2. Add the formula and the 2 dates (Current date is NOW function)


3.It's cool already \yeay/, I have my countdown, except it is not running yet :(
To do that I add an infinite loop who will calculate my formula (In a Macro)


4. Tadaaa