Visualizzazione post con etichetta java. Mostra tutti i post
Visualizzazione post con etichetta java. Mostra tutti i post

venerdì 20 aprile 2012

String equals in Java

Some remarkable samples about String equals vs == comparator in Java.
You may have different output if you use == comparator instead equals for String test.
 See sample code:


public class StringTest {

   
    public static void main (String [] args){
        testA();
       
        testB();
    }

   
    static void testA(){
        System.out.println (" testA");
        // good memory usage!!  RECOMENDED constructor
        String s1 = "a";
        String s2 = "a";
        System.out.println (" s1 = \"a\"");
        System.out.println (" s2 = \"a\"");
        if (s1 == s2 ){
            System.out.println (" s1 == s2 is true");
        } else {
            System.out.println (" s1 == s2 is false");
        }
        if (s1.equals(s2)  ){
            System.out.println (" s1.equals(s2) is true ");
        } else {
            System.out.println (" s1.equals(s2) is false ");
        }
    }
   
    static void testB(){
        System.out.println (" testB");
        // waste memory !! NOT RECOMENDED CONSTRUCTOR FOR STRINGS
        String s1 = new String ("a");
        String s2 = new String("a");
        System.out.println (" s1 = new String(\"a\")");
        System.out.println (" s2 = new String(\"a\")");
        if (s1 == s2 ){
            System.out.println (" s1 == s2");
        } else {
            System.out.println (" s1 == s2 is false");
        }
        if (s1.equals(s2)  ){
            System.out.println (" s1.equals(s2) is true ");
        } else {
            System.out.println (" s1.equals(s2) is false ");
        }
    }




   
This is code output:

 testA
 s1 = "a"
 s2 = "a"
 s1 == s2 is true
 s1.equals(s2) is true
 testB
 s1 = new String("a")
 s2 = new String("a")
 s1 == s2 is false
 s1.equals(s2) is true

 
  /**
     * Comments :
     * String offeres many constructors for Strings:
     *   in testA
     *   String s1 = "a"; create a literal "a" in pool memory ans s1 refers to it
     *   String s2 = "a"; s2 refers to same previous literal in pool.
     *  
     *   otherwise in testB     
     *    String s1 = new String("a") ;  because we use new keyword a new String object is created in not  pool memory (s1 refers to it) and  in addiction literal "a" is placed  in pool memory;
     *    String s2 = new String("a") ;  because we use new keyword a new String object is created in not  pool memory and (different from previous) s2 refers to it
     */
   
   
}


sabato 17 marzo 2012

Sorting java object with Comparable

A sample Price sorting sample  (by price and date) with comparable



import java.util.*;

public class InstrumentPricesSorter {

    static public List <InstrumentPrice> sortPrices (List <InstrumentPrice>  list2Sort){
        List  <InstrumentPrice>  result = new ArrayList  <InstrumentPrice>  ();
       
        Collections.sort(list2Sort);
        //Collections.reverse(list2Sort);
        // riordino la collezione in base al prezzo e alla data
       
        HashMap < String   , InstrumentPrice> myMap = new HashMap   < String   , InstrumentPrice>();
        for ( InstrumentPrice  price :  list2Sort )      {
             if ( ! myMap.containsKey(price.getInstrumentId())) {
           
             myMap.put(price.getInstrumentId() , price);
             }
        }
        Collection  <InstrumentPrice> collection =  myMap.values();
        result.addAll(collection);
       
        return result;
    }
   
   
   
   
    public static void main (String [] args ){
        List <InstrumentPrice> list = new ArrayList <InstrumentPrice> ();
        list.add(new InstrumentPrice ("ISIN001",  new Date(2012, 2, 1)  , 10 ));
        list.add(new InstrumentPrice ("ISIN001",  new Date(2012, 2, 2)  , 9 ));
        list.add(new InstrumentPrice ("ISIN001",  new Date(2012, 2, 3)  , 8 ));
        list.add(new InstrumentPrice ("ISIN002",  new Date(2012, 2, 1)  , 56 ));
        list.add(new InstrumentPrice ("ISIN002",  new Date(2012, 2, 2)  , 58 ));
        List <InstrumentPrice >  result = InstrumentPricesSorter.sortPrices(list);
        for ( InstrumentPrice item      : result ){
            System.out.println(item.getInstrumentId() + " " + item.getValue() +  "  " +  item.getDate() );
        }
    }
   
   
}




class InstrumentPrice  implements Comparable <InstrumentPrice>{
    private  String instrumentId;
    private Date date;
    private long value;
   

    public InstrumentPrice(String instrumentId, Date date, long value){
        this.instrumentId = instrumentId;
        this.date = date;
        this.value = value;
    }

    public String getInstrumentId (){
        return this.instrumentId;
    }
   
   
    public Date getDate (){
        return this.date;
    }
   
    public long getValue (){
        return this.value;
    }
   
    public boolean equals (Object obj){
        if ( (obj instanceof  InstrumentPrice)   &&  (   ((InstrumentPrice)obj).instrumentId.equals( this.instrumentId) )   &&  ((InstrumentPrice)obj).date.equals( this.date)  &&   ((InstrumentPrice)obj).getValue() == this.value) {
            return true;
        } else {
            return false;
        }
    }
   
    public int hashCode (){
        return this.instrumentId.hashCode() + this.date.hashCode() + Double.toString(this.value).hashCode() ;
    }
   

    @Override
    public int compareTo(InstrumentPrice o) {
        //TODO verify compare
        int idCompare = this.instrumentId.compareTo(o.instrumentId);
        if ( idCompare != 0 ){
            return idCompare;
        } else  {
            // ho trovato si riferiscono stesso id
            int valueCompare =   Double.compare(this.value, o.value);
            if (valueCompare != 0){
                return  valueCompare * -1 ;
            } else {
                // si riferiscono anche stesso prezzo
                int dateCompare = this.date.compareTo(o.date);
                return dateCompare;
            }
        }   
    }
   
   
   
}

venerdì 16 marzo 2012

Composite Pattern (Generics version)

import java.util.*;

public abstract class Component <T>  {
   
    public Component( T instance){
        this.instance = instance;
    }
   
    private T instance;
   
    protected Integer ID;
   
    public Integer getId(){
        return this.ID;
    }
   
   
    public boolean hasChildren(){
        return false;
    }
   
    public int getNumChildren (){
        return 0;
    }
   
    public  void addChild(Component <T> aChild){
       
    }
   
    public  void removeChild(Component <T> aChild){
       
    }
   
    public  Component <T> getChildAt(int index){
        return null;
    }


    public static void main (String [] args ){
        Component <Integer> root = new Composite <Integer>((new Integer(1)));
        root.addChild(new Leaf <Integer>(new Integer(1)) );
        root.addChild(new Composite <Integer>(new Integer(1)));   
        root.addChild(new Composite<Integer>(new Integer(1)));
        root.addChild(new Composite<Integer>(new Integer(1)));   
        root.addChild(new Composite<Integer>(new Integer(1)));   
        System.out.println(root.getNumChildren());
    }
   
   

}


class Composite <T> extends Component <T>{

    public Composite(T instance) {
        super(instance);
        // TODO Auto-generated constructor stub
    }

    private LinkedHashSet <Component <T>> childrenList  = new LinkedHashSet <Component<T>> ();
   
    @Override
    public void addChild(Component <T> aChild) {
        Random pippo = new Random();
        //pippo.setSeed(10);
        aChild.ID = pippo.nextInt();
        this.childrenList.add(aChild);
    }

   
    public void removeChild (Component <T>  aComponent) {
        Component <T>itemToRemove = null;
        for (Component <T> item : this.childrenList){
            if (item.getId() == aComponent.getId() ){
                itemToRemove = item;
                break;
            }
        }
        if (itemToRemove != null){
            this.childrenList.remove(itemToRemove);   
        }
       
    }

    public int getNumChildren (){
        return this.childrenList.size();
    }
   
   
    public Component <T> getChildById(int id) {
        Component <T> requestedItem = null;
        for (Component <T> item : this.childrenList){
            if (item.getId() == id ){
                requestedItem = item;
                break;
            }
        }

        return requestedItem;
    }
   
    @SuppressWarnings("unchecked")
    public boolean equals (Object anObj){
        if ( (anObj instanceof Composite ) && ((Composite <T>)anObj).getId().equals( this.ID ) ){
            return true;
        } else {
        return false;
        }
    }
   
    public int  hashCode (){
        return this.ID.hashCode();
    }
}



class Leaf <T> extends Component <T>{
    public Leaf(T instance) {
        super(instance);
        // TODO Auto-generated constructor stub
    }

    @SuppressWarnings("unchecked")
    public boolean equals (Object anObj){
        if ( (anObj instanceof Leaf) && ((Leaf  <T>)anObj).getId().equals( this.ID ) ){
            return true;
        } else {
        return false;
        }
    }
   
    public int  hashCode (){
        return this.ID.hashCode();
    }

   
}

Singleton pattern



/**
 * Test client class for Singleton
 * @author bacco
 *
 */
public class SingletonClientClass implements Runnable {
    MySingletonClass singleton = MySingletonClass.getInstance();
   
   
    public static void main (String []  args){
        SingletonClientClass clinetClass = new SingletonClientClass();
        Thread t1 = new Thread(clinetClass);
        t1.setName("Thread1");
        Thread t2 = new Thread(clinetClass);
        t1.setName("Thread2");
        t1.start();
        t2.start();
   
    }

    @Override
    public void run() {
        long init = System.currentTimeMillis();
        System.out.println (System.currentTimeMillis()  - init);
        System.out.println( Thread.currentThread().getName() + "setting name  ");
        singleton.setName(Thread.currentThread().getName());
        for (int i =0; i < 5 ; i++) {
        try {
            System.out.println (System.currentTimeMillis() - init );
            System.out.println (Thread.currentThread().getName() + "stopping ");
            Thread.currentThread().sleep(3000);
            System.out.println (System.currentTimeMillis() - init);
            System.out.println (Thread.currentThread().getName() + "setting name");
            singleton.setName(Thread.currentThread().getName());
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // TODO Auto-generated method stub
        }
    }   
}


/**
 * Singleton class
 * @author bacco
 *
 */
class MySingletonClass {
   
    private static MySingletonClass instance;
   
    private String name;
   
    /*
     * serve ad inibire il costruttore
     */
    private MySingletonClass (){
       
    }
   
    public static synchronized MySingletonClass getInstance(){
        if (instance == null ){
            instance = new MySingletonClass();
        }
        return instance;
    }
   
     public synchronized void  setName(String name) {
        instance.name = name;
        System.out.println("Singleton Instance " + this.toString() + " Named "  + this.name );
    }



}



Here sample output
0
0
Thread2setting name 
Thread-1setting name 
Singleton Instance MySingletonClass@6bbc4459 Named Thread2
2
Singleton Instance MySingletonClass@6bbc4459 Named Thread-1
1
Thread2stopping
Thread-1stopping
3002
3001
Thread-1setting name
Singleton Instance MySingletonClass@6bbc4459 Named Thread-1
3001
Thread-1stopping
Thread2setting name
Singleton Instance MySingletonClass@6bbc4459 Named Thread2
3002
Thread2stopping
6001
Thread-1setting name
Singleton Instance MySingletonClass@6bbc4459 Named Thread-1
6001
Thread-1stopping
6002
Thread2setting name
Singleton Instance MySingletonClass@6bbc4459 Named Thread2
6002
Thread2stopping
9002
9001
Thread-1setting name
Singleton Instance MySingletonClass@6bbc4459 Named Thread-1
Thread2setting name
Singleton Instance MySingletonClass@6bbc4459 Named Thread2

java keystore PrivateKeyEntries vs trustedCertEntry

This is my first post about java ssl and keystores.

First of all a description about different entries in java key store :

trustedCertEntry = 3th parts  certificate with only public key    (certificates imported with  keytool - i command)  unsigned or signed by known CA

privateKeyEntries =   system's  own certificate with  private and  public key  (certificate generated by keytool - genkey command


Example of keytool entries from sample keystore :

keytool -list  -keystore mykeystore.jks
3 entries:
external system1 - self signed cert
server1-udb, Jul 25, 2011, trustedCertEntry,
Certificate fingerprint (MD5): 7B:93:06:E0:34:58:F4:75:27:FC:4C:E9:5C:9A:CB:79
my server certificate
myserver-conf, Jul 21, 2011, PrivateKeyEntry,
Certificate fingerprint (MD5): 21:6F:79:85:14:43:83:0C:96:A0:66:1E:8D:A7:49:F3
CA - certificate
myrootca, Jul 21, 2011, trustedCertEntry,
Certificate fingerprint (MD5): 5A:11:C7:CF:62:7C:3C:46:F4:4D:C3:38:BE:64:9C:7B

And detailed view  of certificates :
 keytool -list -v -keystore mykeystore.jks

Keystore type: JKS
Keystore provider: SUN
Your keystore contains 3 entries

SELF SIGNED CERTIFICATE
Alias name: server1-udb
Creation date: Jul 25, 2011
Entry type: trustedCertEntry
Owner: CN=OtherCompany, OU=., O=., L=., ST=., C=IT
Issuer: CN=OtherCompany, OU=., O=., L=., ST=., C=IT
Serial number: 0
Valid from: Thu Jul 17 12:32:08 CEST 2008 until: Sun Jul 15 12:32:08 CEST 2018
Certificate fingerprints:
         MD5:  7B:93:06:E0:34:58:F4:75:27:FC:4C:E9:5C:9A:CB:79
         SHA1: 57:F1:9E:D8:E6:8C:E0:47:A1:39:83:BD:AA:4A:E8:71:55:4D:3A:DB
         Signature algorithm name: SHA1withRSA
         Version: 3

*******************************************
*******************************************

My SERVER CERTIFICATE (SIGNED By myrootCA)
Alias name: myserver-conf
Creation date: Jul 21, 2011
Entry type: PrivateKeyEntry
Certificate chain length: 2Certificate[1]:
Owner: CN=myserver-conf, OU=myOU, O=CompanyO, C=IT
Issuer: CN=Company, OU=myOU, O=myorg, C=IT
Serial number: 14a67
Valid from: Thu Jul 21 16:57:39 CEST 2011 until: Fri Jul 20 16:57:39 CEST 2012
Certificate fingerprints:
         MD5:  21:6F:79:85:14:43:83:0C:96:A0:66:1E:8D:A7:49:F3
         SHA1: 2F:70:2B:E8:8B:F1:D8:00:C6:45:71:9F:23:F7:30:08:92:87:B8:FE
         Signature algorithm name: SHA1withRSA
         Version: 3
Extensions:
#1: ObjectId: 2.5.29.15 Criticality=false
KeyUsage [
  DigitalSignature
  Key_Encipherment
]
#2: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: F9 10 15 9E A4 FB 1D ED   D2 17 0F F7 61 02 86 03  ............a...
0010: C2 11 36 FC                                        ..6.
]
]
#3: ObjectId: 2.5.29.31 Criticality=false
CRLDistributionPoints [
  [DistributionPoint:
     [URIName: http://mywebL]
]]
#4: ObjectId: 2.5.29.37 Criticality=false
ExtendedKeyUsages [
  serverAuth
  clientAuth
]
#5: ObjectId: 2.5.29.19 Criticality=false
BasicConstraints:[
  CA:false
  PathLen: undefined
]
#6: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: 0B 5B 2F E9 D1 F6 BB F7   AA 6B E5 89 75 5C ED ED  .[/......k..u\..
0010: A4 BD 26 23                                        ..&#
]
]
Certificate[2]:
Owner: CN=Company, OU=myOU, O=myorg, C=IT
Issuer: CN=Company, OU=myOU, O=myorg, C=IT
Serial number: 1
Valid from: Wed Jan 05 15:12:14 CET 2005 until: Mon Jan 05 15:10:44 CET 2015
Certificate fingerprints:
         MD5:  46:9A:AA:1C:87:27:D4:D1:A2:F3:56:BB:4C:23:90:44
         SHA1: 55:FC:92:81:39:8A:42:1F:DC:94:62:BF:7A:42:56:CC:44:1D:45:4F
         Signature algorithm name: SHA1withRSA
         Version: 3
Extensions:
#1: ObjectId: 2.5.29.15 Criticality=true
KeyUsage [
  Key_CertSign
  Crl_Sign
]
#2: ObjectId: 2.5.29.19 Criticality=true
BasicConstraints:[
  CA:true
  PathLen:2147483647
]
#3: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 0B 5B 2F E9 D1 F6 BB F7   AA 6B E5 89 75 5C ED ED  .[/......k..u\..
0010: A4 BD 26 23                                        ..&#
]
]
#4: ObjectId: 2.5.29.32 Criticality=false
CertificatePolicies [
  [CertificatePolicyId: [1.3.76.12.1.1.4]
[PolicyQualifierInfo: [
  qualifierID: 1.3.6.1.5.5.7.2.1
  qualifier: 0000: 16 23 68 74 74 70 73 3A   2F 2F 77 77 77 2E 74 69  .#https://www.ti
0010: 70 6B 69 2E 63 6F 6D 2F   50 72 69 76 61 74 65 43  pki.com/PrivateC
0020: 41 2F 43 50 53                                     A/CPS
]]  ]
]
*******************************************
*******************************************

MY CA CERTIFICATE
Alias name: myrootca
Creation date: Jul 21, 2011
Entry type: trustedCertEntry
Owner: CN=Company, OU=myOU, O=myorg, C=IT
Issuer: CN=Company, OU=myOU, O=myorg, C=IT
Serial number: d9e97f4c4c1f581a
Valid from: Tue Nov 09 17:51:18 CET 2010 until: Fri Nov 06 17:51:18 CET 2020
Certificate fingerprints:
         MD5:  5A:11:C7:CF:62:7C:3C:46:F4:4D:C3:38:BE:64:9C:7B
         SHA1: 1C:2D:8C:4F:18:D5:6F:4B:24:0D:88:2C:12:8D:04:7D:29:8D:56:30
         Signature algorithm name: SHA1withRSA
         Version: 3
Extensions:
#1: ObjectId: 2.5.29.19 Criticality=true
BasicConstraints:[
  CA:true
  PathLen:2147483647
]
#2: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: D6 0C 73 BD A7 0B 47 01   98 F5 A8 1E 6A 73 73 EF  ..s...G.....jss.
0010: F2 B1 E8 6C                                        ...l
]
]
#3: ObjectId: 2.16.840.1.113730.1.1 Criticality=false
NetscapeCertType [
   SSL CA
   S/MIME CA
   Object Signing CA]

*******************************************
*******************************************