Suggested Pages

Tuesday, January 31, 2017

convert xml to json


maven dependency

  <dependencies>
  <dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20160810</version>
  </dependency>
   </dependencies>

Example of Java Code to convert XML into json

 int PRETTY_PRINT_INDENT_FACTOR = 4;
  JSONObject jsonObject = XML.toJSONObject(TEST_XML_STRING);
  String output = jsonObject.toString(PRETTY_PRINT_INDENT_FACTOR);
  System.out.println(output);


XML to json

<?xml version="1.0" ?>
<parent parentAttribute1="parentValue">
<child>2</child>
<child attribute="value">3
</child>Example
</parent>

output of json


{"parent": {
    "parentAttribute1": "parentValue",
    "content": "Example",
    "child": [
        2,
        {
            "attribute": "value",
            "content": 3
        }
    ]
}}

Generics List vs Array

The two most important differences between Array and Generics List are:
  • arrays are covariant;
  • arrays are reified.

Arrays are Covariant


Given a subtype B of a supertype A, the array B[] is a subtype of A[].
Given a subtype B of a supertype A, List<B> is not a subtype of List<A>.

As you can see in the following class, there is a Compiler Error because List<B> is not covariant with List<A> and so it's not a correct overriding.

import java.util.LinkedList;

public class A {
 
 public List<A> doThis(){
  return null;
 }
}
class B extends A {
 
 public List<B> doThis(){ // Compiler Error
  return null;
 }
}
As you can see in the following class, this is a correct overriding because B[] is covariant with A[].


import java.util.LinkedList;

public class A {
 
 public A[] doThis(){
  return null;
 }
}
class B extends A {
 
 public B[] doThis(){
  return null;
 }
}

Arrays are Reified


Arrays enforce element types at runtime, infact it can occur an exception at runtime because of constraints on types. Instead Generics work with erasure, so the contraints are enforced at compile time.

Instance of

Instance of is a keyword that works at this way.
Suppose you have a class A and its subclass B and the following class Main.java
A.java

public class A {
 
}
class B extends A{
 
}
Main.java

public class Main {

 public static void main(String[] args) {
    A[]a=new B[1];
    A[]b=new A[1];
    System.out.println(a instanceof A[]);
    System.out.println(a instanceof B[]);
    System.out.println(b instanceof A[]);
    System.out.println(b instanceof B[]);
 }
}
The output of Main class is:
  true
  true
  true
  false
The following Main.java instead has two compiler errors. Main.java

public class Main {

   public static void main(String[] args) {
        A[]a=new B[1];
        A[]b=new A[1];
        System.out.println(a instanceof A); // Compiler Error
        System.out.println(a instanceof B); // Compiler Error
   }
}

Comparable vs Comparator

In Java programming one of the most important things to understand is the divide et impera concept. When you develop an algoritm that has to sort a data structure, it's important to divide these two concepts:
  • Sorting Logic
  • Structure Data Rappresentation
In Java there are two commons way to perform an sorting algoritm: using Comparator or using Comparable. Both these mechanisms aim to focus on the logic of the ordering, so developers should not have to think on the data structure to sort.
The main difference between Comparable and Comparator is that: the former is the natural way to sort a class, the latter is the unusual way to sort a class. Comparator is usually used for a specific scope in your application; if we have to implement the same concept in two different applications, we will implement probably the same bean class with the same implementation of Comparable. Instead we will write different Comparator classes in these two applications because Comparator is typically useful when there are multiple ways of comparing two instances of a certain type.

Comparable


Comparable is an interface that imposes total ordering, called Natural Ordering, on the objects. Comparable exposes int compareTo(T o) method that developers must implement in Comparable subclasses. Developers also have to be sure that its implementation is consistent with equals method at this way: o1.compareTo(o2) == 0 must have the same boolean value as o1.equals(o2).
Comparable interface is very important because if you want to sort a data structure as a List, you can use Collections.sort(List list) method. Collections class uses the Natural Ordering to sort data elements of the structure, therefore it take into consideration the way you implement int compareTo(T o) method.
In the following code there's an example of Archer class that implements public int compareTo(T t) of Comparable interface. You can notice that this method is perfectly consistent with equals method.

Archer.java
   public class Archer implements Comparable {

 private String name;
 
 private String company;
 
  
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getCompany() {
  return company;
 }

 public void setCompany(String company) {
  this.company = company;
 }

 
 @Override
 public String toString() {
  return "Archer [name=" + name + ", company=" + company + "]";
 }

        @Override
 public int compareTo(Archer archer) {
  if (archer == this) {
   return 0;
  }
  return this.name.compareTo(archer.getName());
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Archer other = (Archer) obj;

  if (name == null) {
   if (other.name != null) {
    return false;
   }
  } else if (!name.equals(other.name)) {
   return false;
  }

  return true;
 }

 
 @Override
 public int hashCode() {
  return this.getName().hashCode()+this.company.hashCode();
 }

}


DataOrdering.java

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;


public class DataOrdering {

 
 public static void order(Listarchers){
  Collections.sort(archers);
 }
}


Comparator


Comparator in an interface that has int compare(T o1, T o2) method.
As said above, Collections class in addition to using the natural ordering of sorting a list, it uses a method that takes as a parameter the Comparator object ( Collections.sort (List<T> list, Comparator <? super T>comparator ). In the following code there's an example of ArcheryCompanyComparator class that implements int compare(T o1, T o2) of Comparator interface.
As you can see we implement public int compare(Archer a1, Archer a2) method, giving an ordering that is not the usual way to sort Archer by the name.

ArcheryCompanyComparator.java
import java.util.Comparator;

public class ArcheryCompanyComparator implements Comparator{

 @Override
 public int compare(Archer a1, Archer a2) {
  return a1.getCompany().compareTo(a2.getCompany());
 }

}

Java Generics

Motivations


Generics have been introduced in the Java language to avoid runtime errors and allow the compiler to detect problems. Suppose you have the following code:
    
    String count="count:";
    Integer countNumber=20;
    List list=new LinkedList();
    list.add(count);
    list.add(countNumber);
    Iterator it=list.iterator();
    String result="";
    while(it.hasNext()){
     result+=(String)it.next();
    }
    System.out.println(result);
The code above compiles successfully but launches this error at runtime:
 java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

if we replace the code above with the code shown below
   
   String count="count:";
   Integer countNumber=20;
   List<string> list=new LinkedList<string>();
   list.add(count);
   list.add(countNumber);
   Iterator<string> it=list.iterator();
   String result="";
   while(it.hasNext()){
     result+=it.next();
   }
   System.out.println(result);
Now the code doesn't compile successfully but launches the following compiler error:
The method add(String) in the type List is not applicable for the arguments (Integer)
As you can see problems are detected at compile time and not at runtime

Erasure


Generics work at runtime with erasure, so the compiler removes all of the information on type parameters of generics method or class. This compiler behaviour allows Java Applications to be compatible with previous Java versions that don't make use of generics. So we can consider Generics Types as information given to the compiler, but at runtime no information is present on Generics Types.
We can distinguish two terms :
  • Generics Types: List<String>
  • Raw Types (legacy code): List

Besides generics can be used at different level:
  • Generic Class: a class that makes use of variable types;
  • Generic Method: a method that makes use of variable types.

Sunday, January 29, 2017

Ubiquitous Language : create, maintain, sustain (Part I)

Create Ubiquitous Language 


First of all, a consideration regarding Ubiquitous Language is that: if you take care of the language (project language or product language ) then your "Software Design" could be simpler and maintainable.

When we talk about project language or product language, actually we are talking about the domain you are working into (financial, sports, paper e.g.). Domain Driven Development suggests to direct efforts and attentions to your specific Domain and consider the opportunity to support your Software with concepts.

The first steps for creating a Domain Language is to grasp from Requirements the concepts that you need. Let us think of a requirement expressed in a Natural Language, a good process is of identifyng words that are concepts to be modeled and that give value to your domain.
.
This step regards the process of identifying concepts, not how to convert a Domain into a Domain Model.

As a first step, a domain can be extracted from reality but then you are free to add additional concepts (even "pure fabrication") that make sense and contribute to your domain.
Basically requirements and reality are the source of your language. Another important step is to design relation among concepts

A simple exercise is : write concepts on a blackboard or in a document and assign them a meaning and a meaning to each relation.

Maintain Ubiquitous Language


Mantain requires to update documentation/reference guide and to make effort (spend time) in a language direction instead of a technology direction.



Sustain Ubiquitous Language


To sustain an Ubiquitous Language , the Management has to be engaged on speaking the same language of the Development Team. So the output of briefing, brainstorming or just requirements, should adopt a Domain Language.



Wednesday, January 25, 2017

JAXB maven plugin example xjc

In this example we can see the xjc goal of the jaxb maven plugin used to generate java classes from an existing schema.

pom.xml (maven plugin)


<plugin>
 <groupId>org.codehaus.mojo</groupId>
 <artifactId>jaxb2-maven-plugin</artifactId>
 <version>2.2</version>
 <executions>
    <execution>
  <id>xjc</id>
  <goals>
    <goal>xjc</goal>
  </goals>
    </execution>
 </executions>
        <configuration>
<!-- package of out for generated classes -->
   <packageName>com.example.generated</packageName>
    <sources>
  <source>src/main/resources/sitemap.xsd</source>
    </sources>
 </configuration>    
</plugin>

sitemap.xsd


<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            targetNamespace="http://www.sitemaps.org/schemas/sitemap/0.9"
            xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
            elementFormDefault="qualified">
  <xsd:annotation>
    <xsd:documentation>
      XML Schema for Sitemap files.
      Last Modifed 2008-03-26
    </xsd:documentation>
  </xsd:annotation>

  <xsd:element name="urlset">
    <xsd:annotation>
      <xsd:documentation>
        Container for a set of up to 50,000 document elements.
        This is the root element of the XML file.
      </xsd:documentation>
    </xsd:annotation>
    <xsd:complexType>
      <xsd:sequence>
        <xsd:any namespace="##other" minOccurs="0" maxOccurs="unbounded" processContents="strict"/>
        <xsd:element name="url" type="tUrl" maxOccurs="unbounded"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>

  <xsd:complexType name="tUrl">
    <xsd:annotation>
      <xsd:documentation>
        Container for the data needed to describe a document to crawl.
      </xsd:documentation>
    </xsd:annotation>
    <xsd:sequence>
      <xsd:element name="loc" type="tLoc"/>
      <xsd:element name="lastmod" type="tLastmod" minOccurs="0"/>
      <xsd:element name="changefreq" type="tChangeFreq" minOccurs="0"/>
      <xsd:element name="priority" type="tPriority" minOccurs="0"/>
      <xsd:any namespace="##other" minOccurs="0" maxOccurs="unbounded" processContents="strict"/>
    </xsd:sequence>
  </xsd:complexType>

  <xsd:simpleType name="tLoc">
    <xsd:annotation>
      <xsd:documentation>
        REQUIRED: The location URI of a document.
        The URI must conform to RFC 2396 (http://www.ietf.org/rfc/rfc2396.txt).
      </xsd:documentation>
    </xsd:annotation>
    <xsd:restriction base="xsd:anyURI">
      <xsd:minLength value="12"/>
      <xsd:maxLength value="2048"/>
    </xsd:restriction>
  </xsd:simpleType>

  <xsd:simpleType name="tLastmod">
    <xsd:annotation>
      <xsd:documentation>
        OPTIONAL: The date the document was last modified. The date must conform
        to the W3C DATETIME format (http://www.w3.org/TR/NOTE-datetime).
        Example: 2005-05-10
        Lastmod may also contain a timestamp.
        Example: 2005-05-10T17:33:30+08:00
      </xsd:documentation>
    </xsd:annotation>
    <xsd:union>
      <xsd:simpleType>
        <xsd:restriction base="xsd:date"/>
      </xsd:simpleType>
      <xsd:simpleType>
        <xsd:restriction base="xsd:dateTime"/>
      </xsd:simpleType>
    </xsd:union>
  </xsd:simpleType>

  <xsd:simpleType name="tChangeFreq">
    <xsd:annotation>
      <xsd:documentation>
        OPTIONAL: Indicates how frequently the content at a particular URL is
        likely to change. The value "always" should be used to describe
        documents that change each time they are accessed. The value "never"
        should be used to describe archived URLs. Please note that web
        crawlers may not necessarily crawl pages marked "always" more often.
        Consider this element as a friendly suggestion and not a command.
      </xsd:documentation>
    </xsd:annotation>
    <xsd:restriction base="xsd:string">
      <xsd:enumeration value="always"/>
      <xsd:enumeration value="hourly"/>
      <xsd:enumeration value="daily"/>
      <xsd:enumeration value="weekly"/>
      <xsd:enumeration value="monthly"/>
      <xsd:enumeration value="yearly"/>
      <xsd:enumeration value="never"/>
    </xsd:restriction>
  </xsd:simpleType>

  <xsd:simpleType name="tPriority">
    <xsd:annotation>
      <xsd:documentation>
        OPTIONAL: The priority of a particular URL relative to other pages
        on the same site. The value for this element is a number between
        0.0 and 1.0 where 0.0 identifies the lowest priority page(s).
        The default priority of a page is 0.5. Priority is used to select
        between pages on your site. Setting a priority of 1.0 for all URLs
        will not help you, as the relative priority of pages on your site
        is what will be considered.
      </xsd:documentation>
    </xsd:annotation>
    <xsd:restriction base="xsd:decimal">
      <xsd:minInclusive value="0.0"/>
      <xsd:maxInclusive value="1.0"/>
    </xsd:restriction>
  </xsd:simpleType>

</xsd:schema>

Generated classes in package com.example.generated

ObjectFactory.java
package-info.java
TChangeFreq.java
TUrl.java
Urlset.java

Example of Main


File file =new File("src/main/resources/sitemap.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Urlset urlset = (Urlset) jaxbUnmarshaller.unmarshal(file);

sitemap.xml


<?xml version='1.0' encoding='UTF-8'?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
 <url>
  <loc>http://simone-folino.blogspot.com/2017/01/android-update-error-comandroidsistemui.html</loc>
  <lastmod>2017-01-23T23:26:41Z</lastmod>
 </url>
 <url>
  <loc>http://simone-folino.blogspot.com/2017/01/weakhashmap-how-it-works.html</loc>
  <lastmod>2017-01-23T22:03:28Z</lastmod>
 </url>
 <url>
  <loc>http://simone-folino.blogspot.com/2017/01/search-annotation-in-package-example.html</loc>
  <lastmod>2017-01-23T07:47:23Z</lastmod>
 </url>
 <url>
  <loc>http://simone-folino.blogspot.com/2017/01/example-of-mongo-db-client.html</loc>
  <lastmod>2017-01-20T08:58:11Z</lastmod>
 </url>

</urlset>


Tuesday, January 24, 2017

Android Update Error : com.android.sistemui

If you notice the following problem in the last android update

COM.ANDROID.SISTEMUI

I found a workaround:
1. Click on goggle store
2. Search for Google app and uninstall

At the end of these steps you are able to use the Home button without errors.
I don't know the cause but this work.

Monday, January 23, 2017

WeakHashMap (How it works)

WeakHashMap Unit Test

This is a simple example of JUnit class that can be used to understand WeakHashMap behaviour. Runtime.getRuntime().gc() is unreliable but it can help to understand how a WeakHashMap works.

import java.util.WeakHashMap;

import org.junit.Assert;
import org.junit.Test;


public class WeakHashMapTest {

 
 @Test
 public void testServer1() {
  Server server=new Server();
  add(server);
  Runtime.getRuntime().gc();
  Monitor monitor = get(server);
  Assert.assertNotNull(monitor);
 }
 
 @Test
 public void testServer1NOCG() {
  Server server=new Server();
  add(server);
  Monitor monitor = get(server);
  Assert.assertNotNull(monitor);
 }
 
 @Test
 public void testServer2() {
  Server2 server=new Server2();
  add2(server);
  Runtime.getRuntime().gc();
  String monitor = get2(server);
  Assert.assertNull(monitor);
 }
 
 @Test
 public void testServer2NOGC() {
  Server2 server=new Server2();
  add2(server);
  String monitor = get2(server);
  Assert.assertNotNull(monitor);
 }

 @Test
 public void testServer3() {
  Server3 server=new Server3();
  add3(server);
  Runtime.getRuntime().gc();
  Monitor monitor = get3(server);
  Assert.assertNotNull(monitor);
 }
 
 @Test
 public void testServer3NOGC() {
  Server3 server=new Server3();
  add3(server);
  Monitor monitor = get3(server);
  Assert.assertNotNull(monitor);
 }


 private static Monitor get(Server server) {
  return server.get(new Monitor(new String("1")));
 }
 
 private static void add(Server server){
  String string = new String("1");
  Monitor monitor = new Monitor(string);
  server.put(monitor);
  monitor=null;
  string=null;
 }
 
 private static String get2(Server2 server) {
  return server.get(new Monitor(new String("2")));
 }
 
 private static void add2(Server2 server){
  String string = new String("2");
  Monitor monitor = new Monitor(string);
  server.put(monitor);
  monitor=null;
  string=null;
 }
 
 private static Monitor get3(Server3 server) {
  return server.get(new String("3"));
 }
 
 private static void add3(Server3 server){
  String string = new String("3");
  Monitor monitor = new Monitor(string);
  server.put(monitor);
  monitor=null;
  string=null;
 }
 
 private static class Server{
  private WeakHashMap<Monitor, Monitor>weakMap=new WeakHashMap<>();
  
  public void put(Monitor monitor){
   weakMap.put(monitor, monitor);
  }
  public Monitor get(Monitor id){
   return  weakMap.get(id);
  }
 }
 
 private static class Server2{
  private WeakHashMap<Monitor, String>weakMap=new WeakHashMap<>();
  
  public void put(Monitor monitor){
   weakMap.put(monitor, monitor.getId());
  }
  public String get(Monitor id){
   return  weakMap.get(id);
  }
 }
 
 private static class Server3{
  private WeakHashMap<String, Monitor>weakMap=new WeakHashMap<>();
  
  public void put(Monitor monitor){
   weakMap.put(monitor.getId(), monitor);
  }
  public Monitor get(String id){
   return  weakMap.get(id);
  }
 }
 
 
 private static class Monitor{
  
  public Monitor(String id) {
   super();
   this.id = id;
  }

  private String id;

  public String getId() {
   return id;
  }

  public void setId(String id) {
   this.id = id;
  }

  @Override
  public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + ((id == null) ? 0 : id.hashCode());
   return result;
  }

  @Override
  public boolean equals(Object obj) {
   if (this == obj)
    return true;
   if (obj == null)
    return false;
   if (getClass() != obj.getClass())
    return false;
   Monitor other = (Monitor) obj;
   if (id == null) {
    if (other.id != null)
     return false;
   } else if (!id.equals(other.id))
    return false;
   return true;
  }

  @Override
  public String toString() {
   return "Monitor [id=" + id + "]";
  }
  
 }
}


Friday, January 20, 2017

Search Annotation in a Package Example

A simple java class that allows you to load annotation given a package without import external libraries.

AnnotationResolver.java


package it.boomerang.common;

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class AnnotationResolver {

 public static class AnnotationResult {

  private Class<?> clazz;

  private List<Annotation> annotations;

  public AnnotationResult(Class<?> clazz, List<Annotation> annotations) {
   super();
   this.clazz = clazz;
   this.annotations = annotations;
  }

  public Class<?> getClazz() {
   return clazz;
  }

  public List<Annotation> getAnnotation() {
   return annotations;
  }

  @Override
  public String toString() {
   return "AnnotationResult [clazz=" + clazz + ", annotations=" + annotations + "]";
  }
  
  
 }

 public static List<AnnotationResult> findAnnotation(String packageName, Class<? extends Annotation> annotationClazz) {
  List<AnnotationResult> annotationResults = new ArrayList<>();

  if (packageName==null) {
   throw new IllegalArgumentException("packageName cannot be null");
  }
  if (!annotationClazz.isAnnotation()) {
   throw new IllegalArgumentException("class " + annotationClazz + " is not annotation");
  }
  List<Class<?>> classFromPackage;
  try {
   classFromPackage = getClassFromPackage(packageName);
  } catch (ClassNotFoundException | IOException | URISyntaxException e) {
   return annotationResults;
  }

  if (classFromPackage == null) {
   return annotationResults;
  }

  if (classFromPackage != null)
   for (Class<?> c : classFromPackage) {
    List<Annotation> annotations = new ArrayList<>();
    Method[] methods = c.getMethods();
    if (methods != null) {
     for (Method m : methods) {
      Annotation methodAnnotation = m.getAnnotation(annotationClazz);
      if (methodAnnotation != null) {
       annotations.add(methodAnnotation);
      }
     }
    }
    Field[] fields = c.getFields();
    if (fields != null) {
     for (Field f : fields) {
      Annotation fieldAnnotation = f.getAnnotation(annotationClazz);
      if (fieldAnnotation != null) {
       annotations.add(fieldAnnotation);
      }
     }
    }

    Annotation classAnnotation = c.getAnnotation(annotationClazz);
    if (classAnnotation != null) {
     annotations.add(classAnnotation);
    }
    if (annotations != null && !annotations.isEmpty()) {
     AnnotationResult annotationResult = new AnnotationResult(c, annotations);
     annotationResults.add(annotationResult);
    }
   }
  return annotationResults;
 }

 private static List<Class<?>> getClassFromPackage(String packageName) throws IOException, ClassNotFoundException, URISyntaxException {
  ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  String path = packageName.replace('.', '/');
  Enumeration<URL> resources = classLoader.getResources(path);
  List<File> dirs = new ArrayList<File>();
  while (resources.hasMoreElements()) {
   URL resource = resources.nextElement();
   URI uri = new URI(resource.toString());
   dirs.add(new File(uri.getPath()));
  }
  List<Class<?>> classes = new ArrayList<Class<?>>();
  for (File directory : dirs) {
   classes.addAll(findClasses(directory, packageName));
  }
  return classes;
 }

 private static List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException {
  List<Class<?>> classes = new ArrayList<Class<?>>();
  if (!directory.exists()) {
   return classes;
  }
  File[] files = directory.listFiles();
  for (File file : files) {
   if (file.isDirectory()) {
    classes.addAll(findClasses(file, packageName + "." + file.getName()));
   } else if (file.getName().endsWith(".class")) {
    classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
   }
  }
  return classes;
 }
}

Logger.java

The class Logger in package "it.boomerang.test" having Deprecated annotation used both at method and at class level.

package it.boomerang.test;

@Deprecated
public interface Logger {

 @Deprecated
 public void log(String msg);
}


Test.java


public class Test {

 public static void main(String[] args) {
  List findAnnotation = AnnotationResolver.findAnnotation("it.boomerang.test", Deprecated.class);
  System.out.println(findAnnotation);
 }
}

output


[AnnotationResult [clazz=interface it.boomerang.test.Logger, annotations=[@java.lang.Deprecated(), @java.lang.Deprecated()]]]


Thursday, January 19, 2017

Example of Mongo DB Client

An Example of a simple client that uses the java library of MongoDB. Here the library to include in your pom.xml

pom.xml

...
<dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongo-java-driver</artifactId>
      <version>3.0.2</version>
</dependency>


MongoDBConnection.java

...

import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;

public class MongoDBConnection {

 private MongoClient mongo;

 private String database;

 public MongoDBConnection(String database, String hostname, int port) {
  this.database = database;
                mongo = new MongoClient(hostname, port);
 }

 public void saveOrUpdate(String json, String identity, String collection) {
  MongoDatabase db = mongo.getDatabase(database);
  MongoCollection mongoCollection = db.getCollection(collection);
  Document document = Document.parse(json);
  UpdateOptions updateOptions = new UpdateOptions();
  updateOptions.upsert(true);
  long count = mongoCollection.count(new Document(identity, document.get(identity)));
  if (count == 0) {
   mongoCollection.insertOne(document);
  } else {
   mongoCollection.replaceOne(new Document(identity, document.get(identity)), document, updateOptions);
  }
 }

         public void close() {
  mongo.close();
 }

 
}

Example of Controller Spring Portlet MVC

Example of Controlle Portlet MVC

...

import javax.portlet.RenderResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import org.springframework.web.portlet.bind.annotation.ResourceMapping;

@RequestMapping(value = "VIEW")
@Controller
public class HelloPortletController {

 
 @RenderMapping
 public String renderPage(RenderResponse response) {
     return "view";
 }

 
 @ActionMapping(params = "myaction=sayHello")
 public void actionMethod(@RequestParam("nome") String nome, @RequestParam("cognome") String cognome) {
     System.out.println("actionMethod() - start");
     System.out.println("nome:" + nome);
     System.out.println("nome:" + cognome);
     System.out.println("actionMethod() - end ");
 }

 @ResourceMapping(value = "refresh")
 public String refresh() {
     return "ajax";
 }

}


Wednesday, January 18, 2017

Android Preferences Example


Preference Fragment Example



package com.example.myapp.preference;

import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;

import com.example.myapp.R;


public class MyPreferenceFragment extends PreferenceFragment {

 
     @Override
     public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       PreferenceManager manager = getPreferenceManager();
       manager.setSharedPreferencesName("Preference");
       addPreferencesFromResource(R.xml.settings);
     }

     @Override
     public void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode, resultCode, data);
     }
}


res/xml/settings.xml


settings.xml

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <PreferenceCategory android:title="@string/pref_user_profile">
       
        <com.example.myapp.activity.preference.NamePreference
            android:key="prefUserName"
            android:summary="@string/pref_user_name_summary"
            android:title="@string/pref_user_name_title" 
            />
        
    </PreferenceCategory>
   

</PreferenceScreen>




Simple XSLT Transformation

XSLT Transformation

...

import java.io.File;
import java.io.FileOutputStream;
import java.net.MalformedURLException;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.xml.sax.SAXException;


public class SampleXSLT {
 

 public void transform(String input, String output,String xsltPath){
      ...
     TransformerFactory tFactory = TransformerFactory.newInstance();
     Transformer transformer = tFactory.newTransformer(new StreamSource(xsltPath));
     transformer.transform(new StreamSource(input), new StreamResult(new FileOutputStream(output)));
      ...
}


Tuesday, January 17, 2017

Dialog Android

Dialog Example

...

import android.app.AlertDialog;
import android.content.DialogInterface;

import com.example.myapp.R;

public class NotificationDialog {

 public static void dialog(android.content.Context activity, int title, int message) {
 
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);

    builder = builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
       
                public void onClick(DialogInterface dialog, int id) {
                       dialog.cancel();
                  }
            });
 
    builder = builder.setTitle(title).setMessage(message).setIcon(R.drawable.dialogo_alert);

    builder.create().show();
 }

}

Handler Android

Example of Handler


import android.os.Handler;
....

Runnable runnable= new Runnable() {

   @Override
   public void run() {
 ....    
   }

};
....

new Handler().postDelayed(runnable, TIMEOUT);

...


Monday, January 16, 2017

Service Provider Interface ( JAVA SPI) Example


Provider Interface


SimpleServiceProvider.java

package it.sample;

public interface SimpleServiceProvider{

     public void simpleService();
}


Provider Implementation


SimpleServiceProviderImpl.java

package it.sample.impl;

public class SimpleServiceProviderImpl interface SimpleServiceProvider{

     public void simpleService(){
    
  }
}


Provider Implementation Descriptor :


META-INF/services/it.sample.SimpleServiceProvider

it.sample.impl.SimpleServiceProviderImpl


Service Loader


ServiceLoader.java

import java.util.*;

package it.sample.client;

public class ServiceLoader {

     public Iterator loadSimpleServiceProvider(){
      ServiceLoader loader = ServiceLoader.load(SimpleServiceProvider.class);
      return loader.iterator();  

  }
}

Sunday, January 15, 2017

Domain Driven Development Introduction - Ubiquitous Language

Ubiquitous Language

In order to introduce this topic is, first of all, necessary to remember a very common practice of development. 

Sometimes functionalities of a program and its delivery are essential. Instead, one of the aims of Domain Driven Development is to influence a Development Team in his way of approaching software development and the way the outcome is communicated outside.

The Domain Driven Development starts from the essential concept of Ubiquitous Language that is a way to allow a Development Team to speak a single language, not just Java or C ++ programming languages, but the language of concepts.

The language within a Developement Team is one of the most important way for sharing knowledge and making a virtuous process. 

A common mistake for the Management, is to consider technology as the common denominator of a team.

We should remember that we use a different language depending on the context (formal, colloquial, private); DDD (Domain Driven Development) introduces the concept of Ubiquitous Language as an essential attitude of a team. 

The team should speak using a common terminology: a Product Language or Project Language. This practice requires methodologies as for testing, day by day the vocabolary must be enriched associating a specific meaning to a term and this term has to be used for the communication.


Reasons for Ubiquitous Language

The reasons for a Common Language are: allow a team to converge on a terminology and allow the development of a language abstraction purged of vices and features used to express a Software Requirements.

The effort in achieving a Common Language requires a constant updating of terms and their implications. Software should take into account Concepts rather than Algorithms and Solutions. The software that uses concepts is better because it relies on relationships between concepts and responsibilities.

Not least a Common Language should be used to be expanded, not only to the Development Team but also to other IT sectors which can base relations and marketing campaigns on a shared language.


Friday, January 13, 2017

OkHttp NetworkOnMainThreadException

OkHttp Code
    RequestBody body = RequestBody.create(JSON, jsonString); 
    Request request = new Request.Builder().url(url).post(body).build();
    Response response = client.newCall(request).execute();
    response.body().string();
If you have this problem:
android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
        at com.android.org.conscrypt.OpenSSLSocketImpl.close(OpenSSLSocketImpl.java:1009)
        at com.squareup.okhttp.Connection.closeIfOwnedBy(Connection.java:136)
        at com.squareup.okhttp.OkHttpClient$1.closeIfOwnedBy(OkHttpClient.java:70)
        at com.squareup.okhttp.internal.http.HttpConnection.closeIfOwnedBy(HttpConnection.java:134)
Possible solution:

    private class AsyncExample extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
               RequestBody body = RequestBody.create(JSON, jsonString); 
               Request request = new Request.Builder().url(url).post(body).build();
               Response response = client.newCall(request).execute();
               response.body().string();
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }

Saturday, January 7, 2017

Java Annotation

State.java

package it.boomerang.statemachine.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface State {
 
  int value();
  
  int timeout() default -1;
  
}

Transition.java

package it.boomerang.statemachine.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Transition {
 
  State from();
  
  State to();
  
}

Transitions.java

package it.boomerang.statemachine.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Transitions {
 
 Transition[] transitions();

}

StateConfiguration .java

package it.boomerang.statemachine.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public abstract @interface StateConfiguration {
 
  State initialState();
  
  Transitions transitions();
  
  boolean sameStateAllowed() default false;
  
}


Suggested Pages