venerdì 28 ottobre 2011

Jboss 4.0.5 problemi nel deploy EJB

Mi è capitato di incappare in un curioso problema, praticamente lanciando da Eclipse una workspace preesistente cou un Ear project da deployare su Jboss, avevo un errore di questo tipo:


org.jboss.deployment.DeploymentInfo@d6781bc5 {
url=file:/C:xxx.ear}
deployer: null
status: null
state: INIT_WAITING_DEPLOYER
watch: file:/C:xxx.ear
lastDeployed: 1103151946718
lastModified: 1103151948000
mbeans:

Dopo un pò di panico (era una vecchia applicazione che risiedeva su una macchina virtuale spenta da tempo).
ho trovato il problema: nella cartella default/deploy per motivi a me ignoti era stato cancellato il file ear-deployer.xml, un file di 1KB del quale ignoravo addirittura l'esistenza (ignoranza mia).
Praticamente me ne sono accorto soltanto una volta scaricata la nuova versione di Jboss e facendo una diff tra i file presenti (una domanda, perchè se c'è una cartella conf non si mettono lì tutti i file di configurazione????) ho notato la mancanza di questo file, che si presenta così:

<?xml version="1.0" encoding="UTF-8"?>

<!-- The JBoss service configuration file for the EAR deployer service.
$Id: ear-deployer.xml 23463 2004-09-05 15:50:37Z starksm $
-->
<server>
   <!-- EAR deployer, remove if you are not using ear deployments -->
   <mbean code="org.jboss.deployment.EARDeployer"
      name="jboss.j2ee:service=EARDeployer">
      <!-- A flag indicating if ear deployments should have their own scoped
      class loader to isolate their classes from other deployments.
      -->
      <attribute name="Isolated">false</attribute>
      <!-- A flag indicating if the ear components should have in VM call
      optimization disabled.
      -->
      <attribute name="CallByValue">false</attribute>
   </mbean>
</server>


Note sugli attributi:
ISOLATED se true fa in modo che tutti gli ear presenti abbiano un diverso classloader.
CALLBYVALUE se true disabilita l'impostazione del call by reference degli Ejb, praticamente mettendolo a true ogni chiamata ad un Ejb viene serializzata.

Questo è quello che ho trovato in merito sul sito di una community JBOSS( qui ):

The use of call by value and marshalling is very inefficient. It typically means
method invocations take 10 times the cpu. Why? Compare Call By Value with Call By Reference

Call By Reference

  1. caller does ejb.someMethod()
  2. invocation is passed through ejb container
  3. container does bean.someMethod()
  4. result is returned to the caller

Call By Value

  1. caller does ejb.someMethod()
  2. invocation is marshalled - the parameters are turned into ObjectStream (a byte[])
  3. container with a different classloader unmarshalls - byte[] -> java Objects - including classloading
  4. invocation is passed through ejb container
  5. container does bean.someMethod()
  6. result is marshalled - the return value is turned into ObjectStream
  7. result is unmarshalled using the caller's classloader - byte[] -> java Object
  8. result is return to the caller

The marshalling and unmarshalling uses a lot of cpu.

Con JBOSS 5 l'ear-deployer ha cambiato nome, si trova nella cartella defalut/deployers e si chiama ear-deployer-jboss-beans.xml,.
 

giovedì 27 ottobre 2011

Creare VPN in Windows XP

I passi da seguire sono:

  1. Pannello di Controllo/Connessioni Rete/Crea nuova Connessione;
  2. Nel Wizard scegliere "Connessione alla rete aziendale" quindi "Connessione VPN";
  3. Dare un nome alla connessione;
  4. Spuntare la casella "Non effettuare prima alcuna connessione";
  5. Digitare il nome server e/o indirizzo IP

mercoledì 26 ottobre 2011

Comandi Linux Utili

Per ottenere le informazioni sulla distribuzione che si sta utilizzando bisogna digitare

lsb_release -a

Per sapere in che directory ci si trova

pwd

Per verificare il valore di una variabile di sistema

echo $NOME_VARIABILE

Per ottenere informazioni complete sul sistema

uname -a

Per cancellare completamente il contenuto di una cartella (sottocartelle comprese)

rm -r nomeCartella

martedì 25 ottobre 2011

Esempio utilizzo java.util.Logging

La libreria java.util.Logging è molto utilizzata per il log delle applicazioni Java.
Il suo più grande vantaggio è che è uno standard incluso nella jdk.
E' possibile inoltre personalizzare i formati di output in modo da costruirsi a proprio piacimento il file di log.
Le categorie di log utilizzate, dalla più severa alla più lieve, sono:

  1. SEVERE
  2. WARNING
  3. INFO
  4. CONFIG
  5. FINE
  6. FINER
  7. FINEST
Di default il file di configurazione della classe di Logging si trova in [JAVA_HOME]/jre/lib e si chiama logging.properties.
Le proprietà di default sono di avere un solo handler java.util.logging.ConsoleHandler, quindi scrive soltanto su console, e come soglia INFO.

Per customizzare il comportamento bisogna fare in modo che la jvm prenda in considerazione all'avvio del nostro programma il nostro file di properties. Per fare questo all'avvio del pgm Java settiamo la proprietà di sistema -Djava.util.logging.config.file=log.properties.

Di seguito la console di lancio di Eclipse con questa opzione.


Il file di properties è così configurato:

############################################################
# Esempio 2 Logging Configuration File
############################################################
#due handler
handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandler
#livello globale
.level= FINEST
############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################
# specifico varie proprietà per il logging su File
java.util.logging.FileHandler.level= INFO
java.util.logging.FileHandler.pattern = log/java_%u.log
java.util.logging.FileHandler.limit = 50000
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter
# specifico varie proprietà per il logging su Console
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter


Abbiamo due handlers uno su file uno su console.

Nell'esempio (un semplice main), vediamo anche come sia possibile inserire un nuovo Handler che gestisca il logging su Excel.

public class LogInfo {
   
    static Logger log=Logger.getLogger(LogInfo.class.getName());

    /**
     * @param args
     * @throws IOException
     * @throws SecurityException
     */
    public static void main(String[] args) throws SecurityException, IOException {
       
        FileHandler f=new FileHandler("log/log.csv");
        Formatter formatterCSV = new MyCsvFormatter();
        f.setFormatter(formatterCSV);
        log.addHandler(f);

        log.warning("Test Valori Sistema");
        log.info( "----------------------------------------------------------------------------");
        log.info( "JRE: " + System.getProperty("java.runtime.name"));
        log.info("JRE Version: " + System.getProperty("java.vm.version"));
        log.info("JRE Vendor: " + System.getProperty("java.vm.vendor"));
        log.info("JRE Boot Path: " + System.getProperty("sun.boot.library.path"));
        log.info("User Country: " + System.getProperty("user.country"));
        log.info("User Language: " + System.getProperty("user.language"));
        log.info("Character Encoding: " + System.getProperty("file.encoding"));
        log.info("Massima memoria allocabile:" + (Runtime.getRuntime().maxMemory()/1024) + "Kb");
        log.info("Dimensione attuale Heap:" + (Runtime.getRuntime().totalMemory()/1024) + "Kb");
        log.info("----------------------------------------------------------------------------");

    }

}

Questa è la classe che si occupa di generare il csv:

import java.text.SimpleDateFormat;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
public class MyCsvFormatter extends Formatter {

    private static final String FORMAT_DATE="yyyy-MM-dd HH:mm:ss:SSS";
    @Override
    public String format(LogRecord record) {
        StringBuffer buf = new StringBuffer();
        if(record.getLevel().intValue()>=Level.WARNING.intValue()){
       
        buf.append(record.getLevel());
        buf.append(";");
        buf.append(formatDate(record.getMillis()));
        buf.append(";");
        buf.append(record.getMessage());
        buf.append("\n");
        }
        return buf.toString();
    }
    private String formatDate(long millis){
        SimpleDateFormat sdf=new SimpleDateFormat(FORMAT_DATE);
        return sdf.format(new java.util.Date(millis));
    }
  
}


Poichè il livello di logging scritto su csv è warning troveremo soltanto

WARNING;2011-10-25 17:07:34:093;Test Valori Sistema

Mentre sul txt e sulla console (poichè i livelli di soglia sono gli stessi):


25-ott-2011 17.07.34 it.test.LogInfo main
AVVERTENZA: Test Valori Sistema
25-ott-2011 17.07.34 it.test.LogInfo main
INFO: ----------------------------------------------------------------------------
25-ott-2011 17.07.34 it.test.LogInfo main
INFO: JRE: Java(TM) SE Runtime Environment
25-ott-2011 17.07.34 it.test.LogInfo main
INFO: JRE Version: 20.0-b11
25-ott-2011 17.07.34 it.test.LogInfo main
INFO: JRE Vendor: Sun Microsystems Inc.
25-ott-2011 17.07.34 it.test.LogInfo main
INFO: JRE Boot Path: C:\Programmi\Java\jre6\bin
25-ott-2011 17.07.34 it.test.LogInfo main
INFO: User Country: IT
25-ott-2011 17.07.34 it.test.LogInfo main
INFO: User Language: it
25-ott-2011 17.07.34 it.test.LogInfo main
INFO: Character Encoding: Cp1252
25-ott-2011 17.07.34 it.test.LogInfo main
INFO: Massima memoria allocabile:253440Kb
25-ott-2011 17.07.34 it.test.LogInfo main






Java verificare l'estensione di un file

Un semplice metodo per verificare l'estensione di un file

private String getEstensioneFile(String nomeFile){
        return nomeFile.substring(nomeFile.lastIndexOf("."));
    }

venerdì 21 ottobre 2011

Java inserimenti batch con JDBC


In questo post vediamo come effettuare inserimenti massivi su una semplice tabella anagrafica, utilizzando JDBC sia in modalità normale che in modalità batch.

Per gestire la modalità "batch" bisogna:
  • Per ogni inserimento (o update) chiamare il metodo addBatch;
  • Alla fine della lista eseguire il metodo executeBatch();
La modalità batch è in genere più veloce.
Il Db Server utilizzato è MySql 5.5.
La ddl della tabella è la seguente:

CREATE TABLE  `test`.`persona` (
  `ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nome` varchar(45) DEFAULT NULL,
  `cognome` varchar(45) DEFAULT NULL,
  `data_nascita` date DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB


La documentazione dettagliata per l'utilizzo è disponibile qui
Questi sono i risultati che ottenuto per varie casisitiche:
  • 10 insert, modalità classica: 31 millisecondi modalità batch: 16 millisecondi;
  • 100 insert,modalità classica: 109 millisecondi modalità batch: 63 millisecondi;
  • 1000 insert, modalità classica: 703 millisecondi modalità batch: 609 millisecondi;
  • 10000 insert, modalità classica: 6203millisecondi modalità batch: 7359 millisecondi;
  • 100000 insert, modalità classica: 74485 millisecondi modalità batch: 73875 millisecondi
Di seguito incollo il codice della classe utilizzata:

package it.test;
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
 class Elemento
{
    private String nome;
    private String cognome;
    private Date d;
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public String getCognome() {
        return cognome;
    }
    public void setCognome(String cognome) {
        this.cognome = cognome;
    }
    public Date getD() {
        return d;
    }
    public void setD(Date d) {
        this.d = d;
    }
   
    Elemento(String nome,String cognome,Date dataNascita){
        this.nome=nome;
        this.cognome=cognome;
        this.d=dataNascita;
    }
   
}
public class ModificheBatch {
    private Connection conn;
    private static final String INSERT="insert into test.persona(nome,cognome,data_nascita) values(?,?,?);";
    public ModificheBatch() throws Exception{
        Class.forName("com.mysql.jdbc.Driver");
        conn=DriverManager.getConnection(getUrlConnection());
    }
    private String getUrlConnection(){
        return "jdbc:mysql://localhost:3306/test?user=root&password=root";
    }
    private List<Elemento> generaListaPersone(int numero){
        List<Elemento> l=new ArrayList<Elemento>();
        for(int i=0;i<numero;i++){
            Elemento pers=new Elemento(generaNome(), generaCognome(), generaDataNascita());
            l.add(pers);
        }
        return l;
    }
    private String generaNome(){
        String[] nomi={"Mario","Paolo","Carlo","Gino","Pino"};
        //
        int rand=(int)Math.round(Math.random()*(nomi.length-1));
        return nomi[rand];
    }
    private String generaCognome(){
        String[] cognomi={"Rossi","Bianchi","Gialli","Verdi","Russo"};
        int rand=(int)Math.round(Math.random()*(cognomi.length-1));
        return cognomi[rand];
    }
    private Date generaDataNascita(){
        Date[] d={generaData(1, 1, 1978),generaData(20, 4, 1978),generaData(8, 7, 1987),generaData(15, 12, 1980),generaData(1, 4, 1970)};
        int rand=(int)Math.round(Math.random()*(d.length-1));
        return d[rand];
    }
    private Date generaData(int giorno,int mese,int anno){
        Calendar c=Calendar.getInstance();
        c.set(Calendar.YEAR, anno);
        c.set(Calendar.MONTH, mese-1);
        c.set(Calendar.DAY_OF_MONTH, giorno);
        return c.getTime();
    }
   
    public static void main(String[] args) throws Exception {
        ModificheBatch m=new ModificheBatch();
        int numeroInsert=100000;
        m.insertClassico(numeroInsert);
        m.insertBatch(numeroInsert);

    }
    public void insertClassico(int numeroInsert) throws Exception{
        System.out.println("******* INSERT CLASSICO *****");
        long time=System.currentTimeMillis();
        List<Elemento> lista=generaListaPersone(numeroInsert);
        PreparedStatement pst=conn.prepareStatement(INSERT);
        for(int i=0;i<lista.size();i++){
            Elemento el=lista.get(i);
            pst.setString(1, el.getNome());
            pst.setString(2, el.getCognome());
            pst.setDate(3, new java.sql.Date(el.getD().getTime()));
            pst.executeUpdate();
          
          
        }
        pst.close();
        long end=System.currentTimeMillis()-time;
        System.out.println("Millisecondi trascorsi "+ end);
        System.out.println("******* FINE INSERT CLASSICO *****");
    }
    public void insertBatch(int numeroInsert) throws Exception{
        System.out.println("******* INSERT BATCH *****");
        long time=System.currentTimeMillis();
        List<Elemento> lista=generaListaPersone(numeroInsert);
        PreparedStatement pst=conn.prepareStatement(INSERT);
        for(int i=0;i<lista.size();i++){
            Elemento el=lista.get(i);      
            pst.setString(1, el.getNome());
            pst.setString(2, el.getCognome());
            pst.setDate(3, new java.sql.Date(el.getD().getTime()));
            pst.addBatch();
          
        }
        pst.executeBatch();
        long end=System.currentTimeMillis()-time;
        System.out.println("Millisecondi trascorsi "+ end);
        System.out.println("******* FINE INSERT BATCH *****");
    }
}





giovedì 20 ottobre 2011

Java invio Mail con autenticazione

Di seguito un esempio di invio mail utilizzando Java e Gmail come account di posta.
Il codice utilizza le librerie di Java Mail, in particolare nel classpath sono presenti i seguenti jar:
  • dsn.jar;
  • imap.jar;
  • mailapi.jar;
  • pop3.jar;
  • smtp.jar.
 Per gestire l'autenticazione si estende la classe astratta javax.mail.Authenticator e si effettua l'override del metodo getPasswordAuthentication.
Da notare che il codice seguente non funziona se si ha la connessione ad internet intermediata da un proxy server.
Di seguito il codice


package it.test;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import java.util.Properties;
public class SimpleMail {

 private static final String SMTP_HOST_NAME = "smtp.gmail.com";
 private static final String SMTP_AUTH_USER = "xxxxxxxxxxxxx";
 private static final String SMTP_AUTH_PWD  = "yyyyyyyyyyyyy";
 private static final String PORT="587";

    public static void main(String[] args) throws Exception{
       new SimpleMail().test();
    }
    private Properties loadGmailProperties(){
      Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.starttls.enable", "true");
        return props;
    }
    public void test() throws Exception

{
       
  Authenticator auth = new SMTPAuthenticator();
  Session mailSession=Session.getDefaultInstance(loadGmailProperties(),auth);
  // con questo parametro settato a true sono inseriti
  // nello standar output i log dell'invio mail
  mailSession.setDebug(true);
  Transport transport = mailSession.getTransport();
  MimeMessage message = new MimeMessage(mailSession);
  message.setContent("Prova invio mail \n Non rispondere prego", "text/plain");
  message.setSubject("Invio di prova");
  message.setFrom(new InternetAddress("noreply@test.it"));
message.addRecipient(Message.RecipientType.TO,newInternetAddress("mailReceiver@test.it"));
  transport.connect();
  System.out.println("Invio....");
  transport.sendMessage(message,
  message.getRecipients(Message.RecipientType.TO));
  transport.close();
  System.out.println("Inviato....");
    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {
        public PasswordAuthentication getPasswordAuthentication() {
           String username = SMTP_AUTH_USER;
           String password = SMTP_AUTH_PWD;
           return new PasswordAuthentication(username, password);
        }
    }
}


domenica 16 ottobre 2011

Java Ajax e JSON

In questo post vediamo come realizzare una semplice applicazione web che gestisce entità di dati in visualizzazione come lista e come inserimento e dettaglio.
Per gestire al meglio i risultati in formato tabellare utilizziamo JSON.
Il contenuto del div può essere popolato dinamicamente lato Ajax con:
  • Codice HTML;
  • XML;
  • JSON.
In questo esempio, preso dall'articolo presente su HTML.it (link articolo), si può vedere come realizzare il servizio utilizzando JSON per la lettura dei dati.
Per generare lato server, dato l'oggetto Java, l'oggetto JSON corrispondente si utilizza la libreria jabsorb-1.3.1.jar .
Tale libreria va posta dentro la directory lib del progetto web assieme anche alle seguenti altre librerie ( altrimenti con compila perchè sono jar utilizzati da questa libreria):

commons-logging-1.1.1.jar       slf4j-jdk14-1.6.2.jar
jabsorb-1.3.1.jar               slf4j-jdk14-1.6.2-sources.jar
jul-to-slf4j-1.6.2.jar          slf4j-log4j12-1.6.2.jar
jul-to-slf4j-1.6.2-sources.jar  slf4j-log4j12-1.6.2-sources.ja
r
slf4j-api-1.6.2.jar             slf4j-migrator-1.6.2.jar
slf4j-api-1.6.2-sources.jar     slf4j-nop-1.6.2.jar
slf4j-ext-1.6.2.jar             slf4j-nop-1.6.2-sources.jar
slf4j-ext-1.6.2-sources.jar     slf4j-simple-1.6.2.jar
slf4j-jcl-1.6.2.jar             slf4j-simple-1.6.2-sources.jar
slf4j-jcl-1.6.2-sources.jar


Lato client invece si utilizzano le API native di Javascript in particolare la
JSON.parse (quindi gli esempi non funzionano con IE 7 e precedenti, per cui sarebbe necessario utilizzare la funzione eval di Javascript).
Ho trovato molto comodo lato js la lettura delle liste dati create in formato JSON lato server,il  viceversa invece molto meno.
Nell'esempio dell'articolo citato si invitava infatti ad utilizzare JSON anche come input al metodo di inserimento, in questo caso ho trovato molto più semplice inviare al server direttamente i parametri e poi inserirli per creare l'articolo piuttosto che creare l'oggetto JSON.

 Di seguito posto tutto il codice utilizzato.


L'entità dati trattata è l'oggetto Java Articolo così definito:

public class Articolo {
    private String articolo;
    private boolean pubblicato;
    private boolean interessante;
    private int [] data;
    private Info info;
.... getter e setter

L'oggetto Info è definito invece così:

public class Info {
private String autore;
... getter e setter
  }

Le operazioni da effettuare sull'entità sono definite dalla seguente interfaccia:


public interface ArticoloManager {
   
    public List<Articolo> getAllArticles();
    public Articolo getArticolo(String id);
    public void insertArticolo(Articolo a);

}
L'implementazione dell'interfaccia è così definita (per semplicita si evita di andare su db e si caricano i dati direttamente in RAM):



public class ArticoloManagerMockImpl implements ArticoloManager {
private static ArticoloManagerMockImpl istanza;
public static ArticoloManagerMockImpl getInstance(){
if(istanza==null)
{
istanza=new ArticoloManagerMockImpl();
}
return istanza;
}
private void caricaLista(){
l.add(generaArticolo("bianchi", "1", new int[]{12,4,1978}));
l.add(generaArticolo("rossi", "2", new int[]{12,4,1985}));
l.add(generaArticolo("verdi", "3", new int[]{10,4,1978}));
l.add(generaArticolo("viola", "4", new int[]{12,9,1978}));
l.add(generaArticolo("cutini", "5", new int[]{31,4,1920}));
}
private Articolo generaArticolo(String autore,String articolo,int[] dataN){
Articolo a=new Articolo();
Info a1=new Info();
a1.setAutore(autore);
a.setArticolo(articolo);
a.setData(dataN);
a.setInteressante(true);
a.setPubblicato(true);
a.setInfo(a1);
return a;
}
private ArticoloManagerMockImpl(){
caricaLista();
}
private List<Articolo> l=new ArrayList<Articolo>();
@Override
public List<Articolo> getAllArticles() {
// TODO Auto-generated method stub
return l;
}

@Override
public Articolo getArticolo(String id) {
Articolo ret=null;
for(Articolo a:l){
if(id.equals(a.getArticolo()))
{
ret=a;
break;
}
}
return ret;
}

@Override
public void insertArticolo(Articolo a) {
l.add(a);

}

}



JSP

Lato Web ho una semplice JSP così definita:


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/util.js"></script>
<title>Insert title here</title>
</head>
<body>
<form >
<table>
<tr><td>Articolo: </td><td><input type="text" name="txtArticolo" id="txtArticolo"/></td></tr>
<tr><td>Autore: </td><td><input type="text" name="txtAutore" id="txtAutore"/></td></tr>
<tr><td>Data: </td><td><input type="text" name="txtData" id="txtData"/></td></tr>
</table>
<input type="button" value="Visualizza Tutti" onclick="javascript:estraiTutti('${pageContext.request.contextPath}/Gestione')"/>
&nbsp;&nbsp;&nbsp;
<input type="button" value="Inserisci" onclick="javascript:insert('${pageContext.request.contextPath}/Gestione')"/>
&nbsp;&nbsp;&nbsp;
<input type="button" value="Cerca per Id Articolo" onclick="javascript:getById('${pageContext.request.contextPath}/Gestione')"/>

</form>
<div id="lista">
</div>
<div id="inserimento"></div>
<div id="dettaglio"></div>
</body>
</html>


I tre div lista inserimento e dettaglio servono a visualizzare o la lista risultati oppure il messaggio di inserimento ok oppure il dettaglio di una entità inserita (cerca per codice articolo).

Servlet

La servlet richiamata via Ajax è la seguente, Notare che alla fine ho utilizzato il metodo insertArticle invece di insertArticleJson suggerito dall'articolo di HTML.


public class Gestione extends HttpServlet {
private static final long serialVersionUID = 1L;
ArticoloManager interfaccia;
JSONSerializer serializer;
/**
* @see HttpServlet#HttpServlet()
*/
public Gestione() {
super();
// TODO Auto-generated constructor stub
}
public void init()
{
serializer = new JSONSerializer();
interfaccia = ArticoloManagerMockImpl.getInstance();
try
{
// inizializza i tipi serializzatori forniti
// di default con la libreria
serializer.registerDefaultSerializers();
}
catch (Exception e)
{
e.printStackTrace();
}
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
private void processRequest(HttpServletRequest request, HttpServletResponse response)
{
try
{
String op = request.getParameter("op");
if (op != null)
{
if (op.equalsIgnoreCase("listAllArticles")) listAllArticles(request, response);
else if (op.equalsIgnoreCase("listArticle")) listArticle(request, response);
else if (op.equalsIgnoreCase("insert")) insertArticle(request, response);
}
// op è null
}
catch(Exception ex){
}
}

private void listArticle(HttpServletRequest request, HttpServletResponse response)
throws NumberFormatException, IOException, MarshallException
{
String articoloId = request.getParameter("articolo");
// Usa la logica esistente per recuperare l'articolo
Articolo toRet = interfaccia.getArticolo(articoloId);
List<Articolo> l=new ArrayList<Articolo>();
l.add(toRet);
// restituisce l'articolo serializzato in JSON tramite
// l'oggetto serializer
response.getWriter().println(serializer.toJSON(l.toArray()));
}
private void listAllArticles(HttpServletRequest request, HttpServletResponse response)
throws NumberFormatException, IOException, MarshallException
{
// Recupera gli articoli con la logica esistente
List<Articolo> toRet = interfaccia.getAllArticles();
// returns a JSON
response.getWriter().println(serializer.toJSON(toRet.toArray()));
}
private String streamToString(InputStream in) throws IOException
{
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
return out.toString();
}
/*
* Restituisce un Articolo in formato JSON
*
* Parametri attesi: op, operazione
*/
private void insertArticleJson(HttpServletRequest request, HttpServletResponse response)
throws NumberFormatException, IOException, MarshallException, UnmarshallException
{
// riceve il messaggio JSON da POST
String json = streamToString(request.getInputStream());
// lo de-serializza
Articolo newArticle = (Articolo) serializer.fromJSON(json);
// inserisce l'articolo ricevuto nel DB
interfaccia.insertArticolo(newArticle);
response.getWriter().println("Ok inserito");
}
private void insertArticle(HttpServletRequest request, HttpServletResponse response)
throws NumberFormatException, IOException, MarshallException, UnmarshallException
{
String articolo=request.getParameter("articolo");
String autore=request.getParameter("autore");
String data=request.getParameter("txtData");
String[] dati=data.split("/");
int anno=Integer.valueOf(dati[2]);
int mese=Integer.valueOf(dati[1]);
int giorno=Integer.valueOf(dati[0]);
int[] arrData=new int[3];
arrData[0]=giorno;
arrData[1]=mese;
arrData[2]=anno;
Articolo art=new Articolo();
Info i=new Info();
i.setAutore(autore);
art.setArticolo(articolo);
art.setInfo(i);
art.setData(arrData);
art.setInteressante(true);
art.setPubblicato(true);
interfaccia.insertArticolo(art);
response.getWriter().println("Ok inserito");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

}

  JAVASCRIPT



function getXMLHttpRequest() {
try {

return new XMLHttpRequest();
} catch (e) {
try {

return new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {
try {
return new ActiveXObject('MSXML2.XMLHTTP.3.0');
} catch(e) {alert('errore');}
}
}
return null;
}
function getJsonResult(risultato)
{
var result="";
var i;
try
{
var my_JSON_object = JSON.parse(risultato);
result="<table border='1'><tr><td>Articolo</td><td>Autore</td><td>Data</td></tr>";
for( i=0;i<my_JSON_object.length;i++){
result+="<tr>";
result+="<td>";
result+=my_JSON_object[i].articolo;
result+="</td>";
result+="<td>";
result+=my_JSON_object[i].info.autore;
result+="</td>";
result+="<td>";
result+=my_JSON_object[i].data;
result+="</td>";
result+="</tr>";
}
result+="</table>";
return result;
}
catch(err){
alert(err);
}
}
function insert(url){
var xmlHttp=getXMLHttpRequest();
xmlHttp.onreadystatechange=function (){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200 || xmlHttp.status==0){
var risultatoTxt=xmlHttp.responseText;
var dett=document.getElementById("dettaglio");
var list=document.getElementById("lista");
var ins=document.getElementById("inserimento");
dett.innerHTML="";
list.innerHTML="";
ins.innerHTML="";
ins.innerHTML=risultatoTxt;
}
else
{
alert('Comunicazione fallita '+xmlHttp.status+" Motivo: "+xmlHttp.statusText);
}
}
};
xmlHttp.open("POST",url,false);
xmlHttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("connection", "close");
var txtArticolo=document.getElementById("txtArticolo").value;
var txtAutore=document.getElementById("txtAutore").value;
var txtData=document.getElementById("txtData").value;
xmlHttp.send("op=insert&articolo="+txtArticolo+"&autore="+txtAutore+"&txtData="+txtData);
}
function getById(url){
var xmlHttp=getXMLHttpRequest();
xmlHttp.onreadystatechange=function (){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200 || xmlHttp.status==0){
var risultatoTxt=xmlHttp.responseText;
var dett=document.getElementById("dettaglio");
var list=document.getElementById("lista");
var ins=document.getElementById("inserimento");
dett.innerHTML="";
list.innerHTML="";
ins.innerHTML="";
dett.innerHTML=getJsonResult(risultatoTxt);
}
else
{
alert('Comunicazione fallita '+xmlHttp.status+" Motivo: "+xmlHttp.statusText);
}
}
};
xmlHttp.open("POST",url,false);
xmlHttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("connection", "close");
var txtArticolo=document.getElementById("txtArticolo").value;
xmlHttp.send("op=listArticle&articolo="+txtArticolo);
}
function estraiTutti( url){
var xmlHttp=getXMLHttpRequest();
xmlHttp.onreadystatechange=function (){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200 || xmlHttp.status==0){
var risultatoTxt=xmlHttp.responseText;
var dett=document.getElementById("dettaglio");
var list=document.getElementById("lista");
var ins=document.getElementById("inserimento");
dett.innerHTML="";
list.innerHTML="";
ins.innerHTML="";
list.innerHTML="";
list.innerHTML=getJsonResult(risultatoTxt);
}
else
{
alert('Comunicazione fallita '+xmlHttp.status+" Motivo: "+xmlHttp.statusText);
}
}
};
xmlHttp.open("POST",url,false);
xmlHttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("connection", "close");
xmlHttp.send("op=listAllArticles");
}


Risultato finale