Primitive types bookmark

			
/**
 * Show how to use primitive types
 */
public void primitiveTypes() {
	// this is an integer, but should not be
	// used as a numerical value
	// chars represent character symbols
	char character = 0;

	// this is a byte, it is unsigned
	byte veryShortInt = 0;

	// this is a short integer, it is signed
	short shortInt = 0;

	// it's a normal range integer, it is signed
	int normalInt = 0;

	//  it's a wide range integer; it is signed,
	//	notice that to be a long, you have to put
	//	a "l" after the number
	long longInt = 022222222222222222l;

	// This is a floating point number
	float floatingPoint = 0;

	// this is a floating point number with a
	// wide range
	double bigFloatingPoint = 0;

	// this is a boolean (can have true or false as
	// a value)
	boolean aBooleanExample;
}
			

Autoboxing

			
/**
 * Shows how primitive types can be "boxed" (automatically cast) to Objects
 */
public void autoBoxing() {
	char character = 0;
	byte veryShortInt = 0;
	short shortInt = 0;
	int normalInt = 0;
	long longInt = 0l;

	float floatingPoint = 0;
	double bigFloatingPoint = 0;

	boolean aBooleanExample = true;

	// Object style

	Byte byteSample = veryShortInt;
	Short shortSample = shortInt;
	Integer intSample = normalInt;
	Long longSample = longInt;

	Float floatSample = floatingPoint;
	Double doubleSample = bigFloatingPoint;
	Boolean booleanSample = aBooleanExample;
}
			
			

Loops

			
// for-loop
String[] table = new String[10];
for (int i = 0; i < 10; i++) {
	String current = table[i];
	System.out.println(current);
}

// for-loop, "foreach" way
for (String s : table) {
	System.out.println(s);
}

// while
int size = 10;
int i = 0;
while (i < size) {
	System.out.println(table[i]);
	i++;
}
			
			

Switch

			
int toBeTested = 2;
// Switches can be based on integer values, chars, or enums. Since java
// 7, it can even be based on Strings
switch (toBeTested) {
case 1:
	// treat case one;
	break; // put this break so the case stops
case 2:
	// in this example, this the case we pass into
	break;

default:
	// this is the instruction to perform if no cases were satisfied
	break;
}

			
			

Lists

			
List<String> listSample = new ArrayList<String>();
listSample.add("test.test2.test3");
Integer listSize = listSample.size();

// first the "old school" method

for (int i = 0; i < listSize; i++) {
	String currentString = listSample.get(i);
}

// for each method

for (String current : listSample) {
	// do something with current
	System.out.println("current : " + current);
	String[] strArray = current.split("\\");
	for (String strPart : strArray) {
		System.out.println("part : " + strPart);
	}
}

//
Collections.sort(listSample);
			
			

Sets

			
Set<String> setSample = new HashSet<String>();
setSample.add("string1");
setSample.add("string2");
setSample.add("string1");

for (String current : setSample) {
	System.out.println("current : " + current);
}

List<String> converted = new ArrayList<String>(setSample);
			
			

Tests and comparisons

			
/**
* Comparison Operators are:
* - "=="  equality
*  - ">"   greater than
*  - "<"   lesser than
*  - "<="  lesser than or equal
*  - ">="  greater than or equal
*
* Conditions combinations operators are:
* - "&&" logical AND
* - "||" logical OR
* - "&"  binary AND
* - "|"  binary OR
* - "!"  Negation
*/

// A boolean to do the demo
final boolean tester = true;
final boolean anotherTester = false;

/*
 * The if instruction is followed by a parenthesis block, allowing to
 * put the condition. If the condition is matched, then the curly
 * bracket is executed. Else the "else" block is performed
 */

if (tester) {
    // do something
} else {
    // do something else
}

// -------------------------------------------
// composed test
if (tester && !anotherTester) {
    // do something
} else {
    // do something else
}

// --------------------------------------------
// you can combine several if else instructions

if (tester && anotherTester) {
    // do something
} else if (!anotherTester) {
    // do anotherThing
} else {
    // do a third thing
}

// --------------------------------------------
// Ternary way

final String result = tester && anotherTester ? "true" : "false";
			
			

File manipulations

			
/**
* This is a sample log class
*/
public void manipulateFile(String path) {
	try {
	    final File pathDir = new File(path);
	//The exists() method return true if the file is found
	    if (!pathDir.exists()) {
			//the mkdirs() method creates the missing directories
			pathDir.mkdirs();
	    }
	//The file object takes the path as a String parameter
	//Notice the File.separator constant: it is used to
	// call the built-in path separator of the system
	    final File file = new File(path + File.separator
				+ outputFileSdf.format(new Date())
				+ ".txt");
	    if (!file.exists()) {
			file.createNewFile();
	    }

	//The FileWriter is a writer allowing to write to a file
	    final FileWriter writer = new FileWriter(file);
	//If you want to have more useful methods like
	// "newLine()", you have to use the BufferedWriter class
	    this.fileWriter = new BufferedWriter(writer);
		this.fileWriter.write(builder.toString());
	    this.fileWriter.newLine();

	//the flush method allows to write concretely in the file
	    this.fileWriter.flush();

	} catch (final IOException e) {
	    e.printStackTrace();
	}
}
			
			

Maps

The Map Interface allows the Java developer to associate a key to a value inside a data structure

The Map is parametrized for the key and the value types. It allows to add a safety in the data access

			
/**
* the map is usually used in the storage of a properties set
*/
final Map<String, String> mapSample = new HashMap<String, String>();
mapSample.put("sampleKey", "sampleValue");
mapSample.put("theConfigurationPath", "C:/test");

mapSample.put("Family name", "Broussard");

final Integer mapSize = mapSample.size();

for (final Entry<String, String> entry : mapSample.entrySet()) {
    System.out.println("this key : " + entry.getKey() +
				" is associated with this value :" +
				entry.getValue());
}

final String value = mapSample.get("Family name");
System.out.println(value);
			
			

XML Manipulation : parsing an XML File

			
/**
 * Creates a "document" from an XML File, the document is the object
 * representing the xml file, allowing to query it in order to get the
 * contained data
 *
 * @param file the location of the xml file
 * @return document, an xml document
 */
private Document getDocument(File file) {
  // It's generally painful to manipulate XML in java,
  // because Apis are quite heavy
  //First, get a document builder factory
  final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  Document doc = null;

  //Then get a document builder from the file
  try {
      final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      log.info("working on this file :" + file.getAbsolutePath());
      //In the end, ask the document builder to parse the inputfile
      doc = dBuilder.parse(inputFile);

  } catch (SAXException | IOException | ParserConfigurationException e) {
      e.printStackTrace();
      return null;
  }
  return doc;
}
			
			
DocumentBuilderFactory DocumentBuilder The document builder takes the file as an argument for the parse method Document Parses the file

XML Manipulations : Getting data

		  
/**
 * gets the list of Identities matching the given criteria
 * @param the criteria the returned identities must match
 * @return a list of Identity
 */
public List<Identity> serialize(SerializationCriteria criteria) {
  log.info("entering the serialize() method");
  // get the document
  Document doc = getDocument(this.inputFile);
  final List<Identity> idList = new ArrayList<Identity>();
  if (doc != null) {
      return null;
  }
  //getDocumentElement(); will get the main XML node (root)
  //the root element is "identities" see the xml file below
  final Element root = doc.getDocumentElement();

  /* generic way of doing */
  final NodeList nodeList = root.getChildNodes();
  if (nodeList == null) {
      return null;
  }

  /* better way  when you know what is inside*/
  final NodeList identityTagList = root.getElementsByTagName("identity");
  if (identityTagList == null) {
      return null;
  }

  final int identityListSize = identityTagList.getLength();
  for (int i = 0; i < identityListSize; i++) {
      idList.add(XmlImport.getIdentityFromXml((Element) identityTagList.item(i)));
  }
  log.info("exiting the serializer");
  return idList;
}
		  
	  
		  
/**
 * Transforms an XML element into an Identity POJO
 * @param el the element assumed to be an Identity
 * @return an identity object
 */
public static Identity getIdentityFromXml(final Element el) {
  //get the sub elements list
  final NodeList nl = el.getChildNodes();
  if (nl == null) {
      return null;
  }
  final Identity id = new Identity();
  final int size = nl.getLength();
  for (int i = 0; i < size; i++) {
      final Node attr = nl.item(i);
      if (attr instanceof Element) { //test the instance of operator

  	switch (attr.getNodeName()) {
  	case "displayedName":
  	    //associate each known node to its corresponding value
  	    //in the identity object
  	    id.setDisplayedName(attr.getTextContent());
  	    break;
  	/*
  	 * case "": break;
  	 */
  	}
      }
  }
  return id;
}
		  
	  

The corresponding xml file:



    
        1
        Thomas Broussard
        thomas.broussard@gmail.com
        +33123456789
    
    
        2
        David Mahery
        david.mah@gmail.com
        +33123456781
    

		
	
DomAPIs getChildNodes getElementsByTagName "identity" the getChildNodes() API gets all the nodes regardless of their tag name the getElementsByTagName() API gets all the nodes with the given tag name as a parameter Node 1 Node 2 Node n identity 1 identity 2 identity n