giovedì 29 marzo 2012

Linux Red Hat cluster commands


To view service packages status
clustat

es:
 ------- ----                                                     ----- ------                                                     -----
 service:srv_GFS_nodo1                                            site-hostbe1-priv                                              started
 service:srv_GFS_nodo2                                            site-hostbe2-priv                                              started
 service:srv_applications                                         site-hostbe1-priv                                              started    [Z]


To freeze a service package (i.e. named  "myservice"). Service is no more under test so - cluster doesn't start services if they are stopped.
clusvcadm -Z  "myservice"

To unfreeze a service package  (i.e. named  "myservice"). Service is  under test again - so cluster doesn't start services if they are not running.
clusvcadm -U  "myservice"

To start a single service wich belongs to a service package
General sintax: rg_test test /etc/cluster/cluster.conf   start  service [servicename]  where service may be a script or a ip address. (also stop/status options available)
For example:
rg_test test /etc/cluster/cluster.conf  start script CONF
rg_test test  /etc/cluster/cluster.conf   start   ip 127.0.0.1  (sample only)
rg_test test  /etc/cluster/cluster.conf   start   clusterfs GFSCONF 

where from cluster.conf file
 <script file="/usr/local/pathplat/current/heartbeat/scripts/conf_ctl_init" name="CONF"/>
<ip ref="127.0.0.1"/>
  
<clusterfs device="/dev/GFSBE/GFSCONF" force_unmount="1" fstype="gfs" mountpoint="/usr/local/pathcm/current/server/default/repository" name="GFSCONF" options=""/>
<service autostart="1" domain="Nodi_12" name="srv_applications">
                        <ip ref="127.0.0.1"/>
                        <script ref="CONF" __independent_subtree="1"/>
 "/>
 <service autostart="1" domain="Nodo2" name="srv_GFS_nodo2">
                        <clusterfs ref="GFSCONF"/>
                </service>

lunedì 26 marzo 2012

Remote debugging Jboss 4.2.x with Eclipse

Modify run.xx file adding remote debug enabled on 8787 port on server side and configure eclipse for remote connection debug.


JBOSS SETTINGS
Locate $jboss_home/bin directory .

According your S.O. you have to add an option in run.sh (Unix) or in run.bat (windows) file.

#enable remote debugging
JAVA_OPTS="${JAVA_OPTS} -Xdebug -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n"



Eclipse Settings

From menù named Debug Configuration…..
Choose Remote Java Application and add information about  your project and remote server ipaddress and listening port (8787 in this sample).

 

martedì 20 marzo 2012

JAXB-XJC: java.lang.IllegalArgumentException: Illegal pattern character 'o' at java.text.SimpleDateFormat.compile

When using xjc compiler (jaxb version 2.2.5) to generate java classes from xsd files class generation may fail with some error like this:

 Illegal pattern character 'o' at java.text.SimpleDateFormat.compile(SimpleDateFormat.java:769) at java.text.SimpleDateFormat.initialize(SimpleDateFormat.java:576) .....
(characted may be different - es. 'g' or other).
What is the problem?
Problem seems to be your locale setting because jaxb-xcj doen't support  locale different from US.

Solution 
Generate your classes with ant and introduce a javascript function to change your locale to US.

Sample ant file 

<taskdef
name="xjc" classname="com.sun.tools.xjc.XJCTask">
<classpath>
<fileset dir="${basedir}/lib">
<include name="jaxb*.jar" />
<include name="xjc-*.jar" />
</fileset>
</classpath></taskdef>
<scriptdef
importClass(java.util.Locale);
actualDefault = Locale.getDefault();
project.setProperty("actual-default-locale", actualDefault);
Locale.setDefault(Locale.US);
]]>
name="setLocale" language="javascript"><![CDATA[
</scriptdef>

<target name="gen-oci-as" description="generates java classes from the OCISchemaAS.xsd">
<setLocale />
<xjc schema="${basedir}/xsd/OCISchemaAS.xsd" destdir="${basedir}/src" extension="true" removeOldOutput="true">
<produces dir="${basedir}/src" includes="**/*.java" />
<arg value="-verbose" />
<arg value="-npa" />
</xjc>
</target>

lunedì 19 marzo 2012

A simple log file with log4j

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="
http://jakarta.apache.org/log4j/" debug="false">  
  
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">         
        <layout class="org.apache.log4j.PatternLayout">           
        <param name="ConversionPattern"    value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{2}: %m%n" />           
        </layout>      
</appender>      
      
      
<appender name="FILE" class="org.apache.log4j.RollingFileAppender">             

 <param name="File" value="/path/output.log"/>            
 <param name="MaxFileSize" value="1MB"/>             
 <param name="MaxBackupIndex" value="100"/>         
 <layout class="org.apache.log4j.PatternLayout">               
        <param name="ConversionPattern"              
 value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{2}: %m%n" />       
 </layout>     
</appender>     

 <root>             
 <priority value="info"/>              
 <appender-ref ref="CONSOLE"/>  
<appender-ref ref="FILE"/>   
 </root>
 </log4j:configuration>

domenica 18 marzo 2012

A full sample about configuring https over jboss 4.2.x with java keytool

 See also this post about  java-keystore-entries

Step 1 create your server certificate
# keytool -genkey -keyalg RSA -keysize 1024 -keystore <mykeystorename.jks> -storepass <mykeystorepassword> -storetype JKS -dname "CN=hostname,OU=myOU,O=Company,C=IT"   -alias <myalias>

Step 2 estract certificate signigning request for CA
# keytool -certreq -keystore <mykeystorename.jks>  -alias <myalias>  -file <mycertsignrequest.csr> -storepass <mykeystorepassword>

Step 3 CA returns signed cert (es. signedcert.cer) and its certificate ( es.  CAcert.cer) - Note that file extension doensn't matter.

Step 4  Remove header section (if any) from signedcert.cer
# grep -A 200 -i 'begin certificate' signedcert.cer > signedcert.pem 

STEP 5  Import signed cer and CA cert in keystore (exactly the same used in step 1) ; import CA cert first !!!

# keytool -import -alias <rootca> -file <CAcert.cer> -keystore <mykeystorename.jks>
 Trust this certificate? [no]:  yes

(use exactly same alias as before otherwise your certificate will be not signed from CA)
keytool -import -keystore -keystore <mykeystorename.jks>  -alias <myalias>  -file <signedcert.pem >

JBOSS CONFIGURATION
-Step 1 edit  server.xml under your  <JBOSS_HOME>/server/default/deploy/jboss-web.deployer/
  
   <Connector port="8443"   address="${jboss.bind.address}" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150"  scheme="https"  secure="true"
  clientAuth="false"     sslProtocol="TLS" keystoreFile="/usr/local/pathconf/jboss-4.2.3GA/server/default/conf/ssl/snodo-conf.jks"        keystorePass="keystorepass"/>
   
Also    ou can choose also what PrivatekeyEntries to use adding parameter  keyAlias="myalias" otherwise java choose the first in your keystore


Step 2 edit run.conf under <JBOSS_HOME>/bin/
add row
JAVA_OPTS="$JAVA_OPTS -Djavax.net.ssl.trustStore=<JBOSS_HOME>/server/default/conf/mykeystorename.jks -Djavax.net.ssl.trustStorePassword=mykeystorepassword

Too many open files - Linux

When an application (server) opens many files (or network connections) on your system sometimes application log shows some file system failure with a message like 'Too Many Open Files'.
That means that user runnig your application open much more files/ connection than admitted.
To solve the problem (assure first that program also closes files correctly) follow this steps:

Count opened files and modify permission

Type

  1. lsof –u <your_user>   | wc -l
  2. lsof +p <your application process>  | wc -l
Default permittet size for opened file is usually about 1000. 
Find your system settings in cat /etc/security/limits.conf
You can modify these settings editing that file at your convenience. For example:

<your_user>       soft    nofile          2048
<your_user>      hard    nofile          8192

NOTE: modify /etc/security/limits.conf doesn't require system reboot. You probably have only to restart application which can't open more files . 

Jboss 4.2.3 remoting services not working with non RFC-952 compliant hostname

Jboss  Version 4.2.3 introduces a new version  (2.2.2 SP8) of   jboss-remoting.jar  involved for connecting remote server with :
o    Socket (SSL Socket)
o    RMI (SSL RMI)  (es. EJB remote invocation)
o    HTTP(S) (web and webServices)
o    Bisocket (SSL Bisocket)
o    Servlet (SSL Servlet)

This new library version checks remote hostname sintax according RFC-952  otherwise raise a generic I/O exception.
Usually hostname doesn't mach specs if contains some char as '_' (for example invalid_host_name is not RFC-952 compliant). 
If you can't modify hostname you have same choices:
- return to version 2.2.2.SP1 used in jboss-4.2.2 (doesn't check hostname sintax).
- try to configure your remote server  web container (es. tomcat based web contatiner) for a different binding. 

sabato 17 marzo 2012

XML in Webservice call


Today many web services offers flexible operation with  xml  input parameter.
This design strategy  offers very stable web service interface (but not very self explaining in input parameters)  at cost of no soap based request check on server side (server must implement other kind of xml validation).
If you use any client to test your web services (es. soap ui) you have to insert an XML in your request but you have to insert special CDATA signature as follows in this sample:

This is client request for myweb service (an spml based one) prototype generated with soap UI:
 
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.appif.app.company.com/">
   <soapenv:Header/>
   <soapenv:Body>
      <ws:provisioningRequest>
         <parameters>
            <spmlReq> 
</spmlReq>
            <responseUrl>?</responseUrl>
         </parameters>
      </ws:provisioningRequest>
   </soapenv:Body>
</soapenv:Envelope>
Basically my web service offers provisioningRequest operation with spmlReq parameter (XML goes there) and an optional responseUrl parameter (for asyncronous responses).

To insert XML put CDATA envelope as follows:



<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.appif.app.company.com/">
   <soapenv:Header/>
   <soapenv:Body>
      <ws:provisioningRequest>
         <parameters>
            <spmlReq> 
<![CDATA[<spml:searchRequest xmlns:spml='urn:oasis:names:tc:SPML:1:0' xmlns:dsml='urn:oasis:names:tc:DSML:2:0:core'>
                  <spml:identifier type='urn:oasis:names:tc:SPML:1:0#GUID'>
                    <spml:id>123456789</spml:id>
                  </spml:identifier>
                  <spml:attributes>
                    <dsml:attribute name='CountCallActiveSim'/>
                  </spml:attributes>
                </spml:searchRequest>
]]>

</spmlReq>
            <responseUrl>?</responseUrl>
         </parameters>
      </ws:provisioningRequest>
   </soapenv:Body>
</soapenv:Envelope>


Keep table and index in Memory - Oracle

Some useful commands to keep indexes or table in oracle buffer pool.
it may be useful for your application performance  if you have some key tables that are many and many times requestes  from your application.  

To keep tables in memory
alter table LOGICAL_AGGREGATION storage (buffer_pool keep);
alter table NGN_ENTITY_NODE storage (buffer_pool keep) ;

remember to keep table indexes also:
alter INDEX indexname storage (buffer_pool keep) ;

Web service invocation - default HostName verifier Error

When calling https based web service - some client implementation may launch an exception due invalid server certificate.
Infact according TLS specs client should verify that the  DN  in server certificate should match with and hostname present in web service url invocation.
For example if client calls a web service at https://myserver/mywebservice?wsdk then  my server certificate should present  DN=myserver.
If not client should launch an exception due invalid certificate.

To avoid this problem (if can't modify server certificate) you can skip that check on client side simply adding that piece of code:    

            System.getProperties().setProperty( "java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol" );
               javax.net.ssl.HostnameVerifier hv = new javax.net.ssl.HostnameVerifier() {
                   public boolean verify(String arg0, SSLSession arg1) {return true;}
               };
               javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier( hv );
          
 

oracle query explain plan

A useful sample of query explain plan with oracle; usefull to find how optimizer works with queries.

Here my table structure

CREATE TABLE "schema_REP"."LOGICAL_AGGREGATION"
  (
    "ID"                   NUMBER(19,0) NOT NULL ENABLE,
    "FULLQUALIFIED_NAME"   VARCHAR2(100 CHAR) NOT NULL ENABLE,
    "NAME"                 VARCHAR2(100 CHAR) NOT NULL ENABLE,
    "TYPE"                 VARCHAR2(100 CHAR),
    "SUB_TYPE"             VARCHAR2(100 CHAR),
    "FAMILY"               VARCHAR2(100 CHAR),
    "VERSION"              VARCHAR2(100 CHAR),
    "LOCATION"             VARCHAR2(100 CHAR),
    "STATO_AMMINISTRATIVO" VARCHAR2(100 CHAR),
    "SPEC_INFO"            VARCHAR2(255 CHAR),
    "MODEL"                VARCHAR2(50 CHAR),
    "VENDOR"               VARCHAR2(50 CHAR),
    "CREATING_STATUS"      VARCHAR2(50 CHAR),
    PRIMARY KEY ("ID") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "EMXDATA01" ENABLE,
    UNIQUE ("FULLQUALIFIED_NAME") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "EMXDATA01" ENABLE
  )


Here sample data :
1    sbc21102011    sbc21102011    SBC        ENTITY    4.2        ON        6.1.0    ACME    Finished
2    issw21102011    issw21102011    ISSW        ENTITY    22.20.64        OFF    issw21102011    ISSW    ITALTEL    Finished
3    MGX1    MGX1    MGX_Site        ENTITY    xx        OFF        MGX    CISCO    Under Configuration
4    CAT001    CAT001    CAT        ENTITY    12.1(14)        OFF        C3550    CISCO    Finished

Now connect as sys   user and type 1th query:

explain plan for (select * from schema_rep.logical_aggregation where fullqualified_name like '%SBC%')

> plan FOR riuscito/a.

And see PLAN_TABLE$ under sys expecially columns operation and optimizer cpu io

 You will find a full table scan .

if query changes as follow

explain plan for (select * from schema_rep.logical_aggregation where fullqualified_name = 'SBC')

You will find a index scan by row id (much faster)

Unix sample shell script - basic functions

esercise 1

#!/bin/bash

##programma esercitazione unix
echo "inseriti parametri numero parametri $#"

echo "prova esecuzione comando"

returncommand=$(ls | xargs )

echo " comando returncommand = $returncommand"

echo "exit code del comando =  $?"


echo "test ciclo for"
 for i
  do
    echo " $i"
  done


echo "test chiamata funzione"

printHello () {
 for j
  do
   echo "$j"
  done

}


printHello hello1 hello2 hello3


echo " test condizionali "

if [[   -n $returncommand ]]
then
  echo "variabile c'e'"
fi


if [[  -n vavavavav  ]]

then
  echo "secondo me va'"
fi

if [[ -n   $adesso_incazza ]]
then
  echo "qui non entra "
else
 echo "variable missing "
fi



echo "operands"

if [[ 1   -gt 0 ]]
then
   echo " 1 > 0 is true "
fi

echo "uguaglianza stringhe"


mystring="jdjdjdjdjjdjdjd"

if [[ "$mystring"  == "jdjdjdjdjjdjdjd"  ]]
then
 echo "so proprio uguali"
fi


echo "piccolo array"

array=(valore1 valore2 valore3);


for k in 0  1 2
do
  echo "   ${array[$k]}"
done



esercise 2 :

#!/bin/bash

##funzione di test argomenti
checkArgs () {
 if [[ -n  $1   ]]
  echo "variabile  $1   trovata "
  return 0
 then
  echo "variabile $1 non trovata "
  return 1
 fi

}

checkUser () {
 echo "$1"
 if [[  -n  "$1"   ]]
 then
 user=$( whoami | grep "$1" )
 if [[ "$user"  == "$1"     ]] 
 then
   echo "good user"
   return 0
 else
  echo "bad user"
  return 1
 fi
 else
   echo "user not passed "
   return 1
 fi


}




checkUser root 

#################################################

Other common usage commands examples

find +  exec  find . -name 'pippo.sh' -exec ls {} \;  Notare spaziatura tra parentesi e \ e l'uso di {} come place holder

 find  exec scp find . -name 'pippo.sh' -exec scp {} root@localhost:/usr  \; Nota che l'scp viene fatto n volte per quanti sono i file trovati dal find
 Nota che l'scp non funziona con xargs

find + xargs

 find . -name 'pippo.*' | xargs  ls
 find . -name 'pippo.*' | xargs  tar -cvf tarone.tar  | scp tarone.tar  root@localhost:/usr/


find $jboss_home/server/default/conf/servprov ! -name "spro_multiolb_issw_list.xml" ! -name "spro_adasif_properties.xml" ! -name "spro_properties.xml" | xargs -i cp -r {} $jboss_home/server/default/repository/links/servprov

Interactive installation script logging -
Use script command:
script -c ./installation_script.sh installation_log.txt

For session logging type script <logfilename>  and <ctrl+D> to stop logging

Xml file well formed check
To test if an xml file is wekll formed use:
xmllint <file_name>
If your xml file is well formed xmllint shows all file otherwise blocks with a parse error.

Check if program is running with bash shell script

 ps -ef | grep '[j]boss-4.2.3GA'
or
 ps -ef | grep   -v grep | grep   'jboss-4.2.3GA'
or
 ps -ef | grep [/j]boss-4.2.3

more on regexp
http://www.cyberciti.biz/faq/grep-regular-expressions/

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]

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

mercoledì 7 marzo 2012

Virtual box - Linux 5.2 64-bit installation - windows 7 pc(64 bit)

Linux 5.2 64-bit installation  over virtual BOX   windows 7 pc(64 bit)
Also Installed these Applications:
- Database oracle xe su pc win7 + INTERNET EXPLORER
- jboss AS and Oracle SQL Client on Linux  Virtual Machine

Scenario a) PC connected to network with DNS available
LINUX VIRTUAL MACHINE INSTALLATION
Step 1 - Virtual box per win 7 installed
Step 2Linux Virtual machine creation
- From virtual box console create new virtual machine namedredhat 64 bit;
 from network settings choose  scheda con bridge 
Step 3 - got file iso  CentOS (versione 64 bit)
CentOS-5.4-x86_64-bin-DVD
Step 4- set file iso  as installation source.
Step 5- installato CentOS sulla macchina virtuale (64 bit)
TASK COMPLETED

INSTALLATION SQL PLUS client on Linux
Step  1- created users sndadmin:users e oracle:oinstall
Step 2- installata jdk (rpm 64 ) su centos
Step 3
- installato istantclient Oracle  (rpm ) x sqlplus su centos
comando: rpn -hi .....
oracle-instantclient-basic-10.2.0.4-1.x86_64.rpm
oracle-instantclient-jdbc-10.2.0.4-1.x86_64.rpm
oracle-instantclient-sqlplus-10.2.0.4-1.x86_64.rpm
STEP 4To have  sqlplus and  tnsnames.ora (copied from dir  network/ADMIN in  oracle xe) working (assume tnsnames in oracle home directory)  set  new properties in oracle home  .bash_profile
PATH=$PATH:$HOME/bin:/usr/lib/oracle/10.2.0.4/client64/bin
export PATH
##aggiunta per utilizzo oracle
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/oracle/10.2.0.4/client64/lib
export LD_LIBRARY_PATH
SQLPATH=/usr/lib/oracle/10.2.0.4/client64/lib
export SQLPATH
TNS_ADMIN=/home/oracle
export TNS_ADMIN
TASK COMPLETED

CONNECTING ORACLE SQL PLUS CLIENT  (Linux) TO ORACLE RDBMS ON (Win7)
Step 1  
- Must define a rule on windows 7 firewall to allow connection from outside to port 1521 (oracle listener port).
Step 2
- As well manage linux iptables to allow http/https traffic to jboss (not recomanded ; step to repeat when restart linux)
[root@localhost log]# /etc/init.d/iptables save
Saving firewall rules to /etc/sysconfig/iptables:          [  OK  ]
[root@localhost log]# /etc/init.d/iptables stop
Flushing firewall rules:                                   [  OK  ]
Setting chains to policy ACCEPT: filter                    [  OK  ]
Unloading iptables modules:                                [  OK  ]
TASK COMPLETED

VIRTUAL BOX NETWORK CONFIGURATION FOR  no  Network Connection (see solution2 - that's better )
When pc has no network to have internal connection between windows pc and Linux Virtual change your Virtual machine network settings:
- Choose NAT mode
- define new port forwarding rules (es .  windows ipconnfig  command  shows  vbox ip= 192.168.56.1 while ifconfig from Linux shows ip = 10.0.2.15) as follows :
tcp 192.168.56.1 8888  10.0.2.15 8080  (per http)
tcp 192.168.56.1 8889  10.0.2.15 8443  (per https)
tcp 192.168.56.1 22      10.0.2.15 22      (per ssh)
tcp 192.168.56.1 8787  10.0.2.15 8787  (jboss remote debug)


VIRTUAL BOX NETWORK CONFIGURATION FOR  works also with No  Network Connection (solution2)
In virtual machine network settings choose Host  Only - Networking as showed in picture below.
You will need no extra - configuration;
however if you want a (optional )  different hostname from localhost.localdomain to a different name (es. vhost.vhostdomain) you have 2 extra configuration on virtual machine:

- edit  the file /etc/sysconfig/network
NETWORKING=yes
HOSTNAME="VBOXCENTOS"
GATEWAY="192.168.0.1"
GATEWAYDEV="eth0"
FORWARD_IPV4="yes"


- set your hostname in /etc/hosts 
127.0.0.1   localhost.localdomain localhost
192.168.56.101 VBOXCENTOS


Note: be sure to insert in your hosts file on windows  this entry
virtualbox_ip_address VBOXCENTOS







lunedì 5 marzo 2012

Axis 1.x client jsession management

Step 1: retrieving jsessionid from server first response
Sample code here:
//Create My serviceLocator recuperando l'interfaccia del service
BWProvisioningServiceServiceLocator serviceLocator =
new BWProvisioningServiceServiceLocator();//Set session enabled
serviceLocator.setMaintainSession(true);
BWProvisioningService service = serviceLocator.getProvisioningService();
//1th service Call
String result = service.processOCIMessage(request);
* recupero nonce x password
*
*/
/**
String nonce =
nonce = result.substring(result.indexOf(
"";"<nonce>")+ 7, result.indexOf("</nonce>"));/** retrieve of session id **/
Stub stub = (Stub) service;
org.apache.axis.client.Call call = stub._getCall();
org.apache.axis.MessageContext msgContext = call.getMessageContext();
String prp = (String)msgContext.getProperty(
String jSessionId = prp.substring(prp.indexOf(
System.
"Cookie");"=") + 1);out.println(jSessionId);/** end of jsessionid retrieve process**/


Step2:  setting jsession id for each  call
Sample code

// for each following request
((javax.xml.rpc.Stub)service)._setProperty( HTTPConstants.
HEADER_COOKIE, "JSESSIONID=" + jSessionId);//2th service Call
String result2 = service.processOCIMessage(loginRequest);