Visualizzazione dei risultati da 1 a 2 su 2
  1. #1

    [Java] Connessione ad un web service e parsing dell'XML ricevuto, AIUTO !!!

    Ciao,
    stò letteralmente impazzendo con un progetto universitario. Praticamente ho un'applicazione Android che si deve connettere ad un WS da cui riceve un file XML (ma non vi preoccupate, si tratta di Java standard, anzi la parte della classe relativa ad Android non la pubblico neanche, questo codice potrebbe essere schiaffato identico in una qualsiasi normalissima applicazione Java).

    In pratica la classe GuidaSubActivity effettua una connessione ad un mio web service passandogli 3 parametri: una latitudine, una longitudine ed un range (che è stato scritto in Java Spring), il WS gli restituisce un file XML contenente dei dati che devono essere parsati. I dati in questione contenuti nell'XML rappresentano una lista di punti di interesse dove ogni punto di interesse ha determinati campi come: longitudine, latitudine, nome, descrizione.

    Il parsing consiste semplicemente nello scorrere questo file XML contenente questi punti di interesse, e di mettere i valori dei campi di ogni punto di interesse presenti nell'XML in un oggetto POI (che rappresenta un punto di interesse) al fine di creare una lista di POI

    Il WS funziona più che correttamente: posso invocarne il relativo metodo passandogli la latitudine, longitudine e range sia dal browser sia usando SoapUI e tutto funziona benone...

    Stò incontrando però grossissimi problemi però a creare la connessione con il WS ed a parsare l'XML ricevuto.

    Vi spiego cosa ho fatto:

    1) Nella classe GuidaSubActivity della mia applicazione ho il metodo getPois() che si connette al WS da cui ottiene la lista di punti di interesse, il codice di tale metodo è il seguente:

    codice:
    //metodo che chiama il WS
    	public List<Poi> getPois(String userLon, String userLat, String userRange){
    		
    		/* Loggo l'entrata nel metodo getPois() che effettua la chiamata al web service ed i parametri ricevuti */
    		Log.d("Sono appena entrato nel metodo getPois() ed i parametri passati sono, userLon:", userLon);
    		Log.d("userLon: ", userLon);
    		Log.d("userLat: ", userLat);
    		Log.d("userRange: ", userRange);
    		
    		List<Poi> pois = null;
    		//Log.d("pois punta a: ", pois.toString());
    		
        	Toast.makeText(this, "Loading POIs..", Toast.LENGTH_LONG).show();
        	
        	String soapRequest = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:exam=\"http://example\">\n" +
            "   <soapenv:Header/>\n" +
            "   <soapenv:Body>\n" +
            "      <exam:getRangePoi>\n" +
            "         <exam:lon>"+userLon+"</exam:lon>\n" +
            "         <exam:lat>"+userLat+"</exam:lat>\n" +
            "         <exam:range>"+userRange+"</exam:range>\n" +
            "      </exam:getRangePoi>\n" +
            "   </soapenv:Body>\n" +
            "</soapenv:Envelope>";
        	
        	Log.d("Ho messo il seguente XML con parametri dinamici nella variabile soapRequest", soapRequest);
        	
        	String soapAction = "";
        	Log.d("La soap action vale: ", soapAction.toString());
        	
        	StringBuffer buffer = sendSoapRequest(soapRequest, soapAction);
        	Log.d("Mette nel buffer il risultato restituito da sendSoapRequest: ", buffer.toString());
        	
        	try{
        		SAXParserFactory factory = SAXParserFactory.newInstance();
        		SAXParser parser = factory.newSAXParser();
        		Log.d("Crea il parser che punta all'oggetto con indirizzo: ", parser.toString());
    
        		// System.out.println(buffer.toString());	// Che è sta robba ?!?! booo pussa viaaa !!!
        		
        		
                StringReader sr = new StringReader(buffer.toString());
                Log.d("E' stato creato uno StringReader sr e passagli il contenuto del buffer in forma di stringa", sr.toString());
                InputSource is = new InputSource(sr);
                Log.d("E' stato creato un oggetto InputSource is a cui viene passato il riferimento all'oggetto sr ", is.toString());
    
                PoiSaxHandler handler = new PoiSaxHandler();
                Log.d("E' stato creato l'oggetto handler di tipo PoiSaxHandler", handler.toString());
                
                // ATTENZIONEEE NON EFFETTUA IL PARSING !!!
                parser.parse(is,handler);	
                Log.d("Passo al parser l'oggetto is che è:", is.toString());
                Log.d("Passo al pareser l'oggetto handler che è: ", handler.toString());
    
                pois = handler.getPois();		// NB: Variabile dichiarata all'inizio del metodo
                Log.d("Invoco il metodo getPois sull'oggetto handler", "suka");
                
                System.out.println("HttpClient.main pois "+pois.toString());
                       
        	}catch(Exception e){
        		
        	}
        	Log.d("MioProgramma", pois.toString());
        	return pois;
        }
    L'unica cosa relativa ad Android che c'è in questo codice è il metodo Log.d() che semplicemente consente di loggare le operazioni in un'apposita finestra di Eclipse, volendo potete sostituire Log.d con un banale println e fargli stampare la stessa cosa...il concetto è quello. Poi ci stà il metodo Toast che di fatto è un printf in Android (volendo basta toglierlo e non cambia nulla)

    Praticamente questo metodo: riceve come parametri di input la longitudine e la latitudine in cui si trova l'utente ed un certo range e deve restituire al chiamante una lista di oggetti Poi che contiene tutti i punti di interesse entro un certo range kilometrico centrato sulla posizione dell'utente, la lista viene restituita appunto dal WS.

    Come prima cosa dichiara una lista di generici oggetti Poi che punta inizialmente a null. Questa è la variabile che dovrà in fine essere restituita dal metodo in questione.

    Poi dichiaro una variabile di tipo String chiamata soapRequest che contiene appunto la richiesta soap generata con soapUI. La richiesta soap è in forma XML ed ho fatto in modo da rendere dinamici i parametri userLon, userLat ed userRange. Dovrebbe essere correttissima !!! Infatti la loggo e mi pare di vederla corretta nei Log di Android (eventualmente basta fare un println)

    Poi ho definito una variabile soapAction vuota perchè in questa richiesta al WS non ho bisogno di una Soap Action.

    Poi creo una variabile StringBuffer buffer in cui metto il risultato ritornato dal metodo sendSoapRequest che come parametri prende la soapRequest e la soapAction precedentemente create e restituisce credo l'XML da parsare ricevuto dal WS, ecco quì il risultato loggato (non fate caso ai valori messi...hanno nome a cavolo perchè nel DB ho inserito punti con nomi e dati a cavolo ma mi pare essere corretto)

    codice:
    10-29 17:51:03.547: DEBUG/Mette nel buffer il risultato restituito da sendSoapRequest:(322): <?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><getRangePoiResponse xmlns="http://example"><getRangePoiReturn><getRangePoiReturn xsi:type="ns1:Map" xmlns:ns1="http://xml.apache.org/xml-soap"><item xmlns=""><key xsi:type="xsd:string">WikiLink</key><value xsi:type="xsd:string">link 2</value></item><item xmlns=""><key xsi:type="xsd:string">Alt</key><value xsi:type="xsd:float">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Tipologia</key><value xsi:type="xsd:int">0</value></item><item xmlns=""><key xsi:type="xsd:string">Distance</key><value xsi:type="xsd:double">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Lat</key><value xsi:type="xsd:float">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Id</key><value xsi:type="xsd:int">3</value></item><item xmlns=""><key xsi:type="xsd:string">Lon</key><value xsi:type="xsd:float">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Nome</key><value xsi:type="xsd:string">test 2</value></item></getRangePoiReturn><getRangePoiReturn xsi:type="ns2:Map" xmlns:ns2="http://xml.apache.org/xml-soap"><item xmlns=""><key xsi:type="xsd:string">WikiLink</key><value xsi:type="xsd:string">lll</value></item><item xmlns=""><key xsi:type="xsd:string">Alt</key><value xsi:type="xsd:float">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Tipologia</key><value xsi:type="xsd:int">0</value></item><item xmlns=""><key xsi:type="xsd:string">Distance</key><value xsi:type="xsd:double">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Lat</key><value xsi:type="xsd:float">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Id</key><value xsi:type="xsd:int">13</value></item><item xmlns=""><key xsi:type="xsd:string">Lon</key><value xsi:type="xsd:float">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Nome</key><value xsi:type="xsd:string">aaab</value></item></getRangePoiReturn><getRangePoiReturn xsi:type="ns3:Map" xmlns:ns3="http://xml.apache.org/xml-soap"><item xmlns=""><key xsi:type="xsd:string">WikiLink</key><value xsi:type="xsd:string">lll</value></item><item xmlns=""><key xsi:type="xsd:string">Alt</key><value xsi:type="xsd:float">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Tipologia</key><value xsi:type="xsd:int">0</value></item><item xmlns=""><key xsi:type="xsd:string">Distance</key><value xsi:type="xsd:double">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Lat</key><value xsi:type="xsd:float">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Id</key><value xsi:type="xsd:int">12</value></item><item xmlns=""><key xsi:type="xsd:string">Lon</key><value xsi:type="xsd:float">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Nome</key><value xsi:type="xsd:string">jiji</value></item></getRangePoiReturn><getRangePoiReturn xsi:type="ns4:Map" xmlns:ns4="http://xml.apache.org/xml-soap"><item xmlns=""><key xsi:type="xsd:string">WikiLink</key><value xsi:type="xsd:string"></value></item><item xmlns=""><key xsi:type="xsd:string">Alt</key><value xsi:type="xsd:float">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Tipologia</key><value xsi:type="xsd:int">0</value></item><item xmlns=""><key xsi:type="xsd:string">Distance</key><value xsi:type="xsd:double">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Lat</key><value xsi:type="xsd:float">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Id</key><value xsi:type="xsd:int">11</value></item><item xmlns=""><key xsi:type="xsd:string">Lon</key><value xsi:type="xsd:float">0.0</value></item><item xmlns=""><key xsi:type="xsd:string">Nome</key><value xsi:type="xsd:string">POITest222</value></item></getRangePoiReturn><getRangePoiReturn xsi:type="ns5:Map" xmlns:ns5="http://xml.apache.org/xml-soap"><item xmlns=""><key xsi:type="xsd:string">WikiLink</key><value xsi:type="x
    Poi crea un SaxParser che credo sia l'oggetto che mi servirà a parsare quell'XML brutto brutto che ho ricevuto. Anche quà loggo l'oggetto parser appena creato e pare che venga creato correttamente!!!

    Poi creo gli oggetti StringReader sr ed InputSource is ed anche questi li loggo e dovrebbero essere ok

    Con la seguente riga di codice creo il mio handler personale che dovrebbe essere l'oggetto che contiene le regole per parsare il mio XML (almeno da quanto ho capito...mi date conferma? non ho fatto tutto io, è un progetto di gruppo)

    codice:
    PoiSaxHandler handler = new PoiSaxHandler();
    Infine parserizzo l'oggetto con questa riga e quì si inchioda !!! Non riesce a terminare questo metodo:

    codice:
    parser.parse(is,handler);
    Il metodo parse invocato sul parser passandogli l'input source e l'handler che gli dice come parserizzare non termina !!!

    In realtà appaiono dei messaggi di log che ho fatto nel codice dell'handler...quindi pare che in qualche modo l'handler faccia qualcosa e pare evidente che si vada ad inchiodare da qualche parte dentro l'handler.

  2. #2
    Il codice della classe PoiSaxHandler è il seguente:

    codice:
    package mieapplicazioni.Http;
    
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    
    import android.util.Log;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public final class PoiSaxHandler extends DefaultHandler {
    
    
        private boolean isId;
        private boolean isLat;
        private boolean isLon;
        private boolean isAlt;
        private boolean isTipologia;
        private boolean isWiki;
        private boolean isPoiId;
        private boolean isNome;
        private int cicle=0;
    
        // invoked when document-parsing is started:
        public void startDocument() throws SAXException {
            System.out.println("Document processing started");
        }
        private Poi p = null;
        private List<Poi> pois=new ArrayList<Poi>();
        
        private String currentElement = null;
     
        // notifies about finish of parsing:
        public void endDocument() throws SAXException {
            pois.add(p);
            System.out.println("Document processing finished");
        }
    
        // we enter to element 'qName':
        public void startElement(String uri, String localName,
                                 String qName, Attributes attrs) throws SAXException {
    
            String key="";
            if (qName.equals("soapenv:Envelope")) {
                currentElement=qName;
            } else if (qName.equals("soapenv:Body")) {
                currentElement=qName;
                System.out.println("SimpleSaxHandler$SaxHandler.startElement body");
    
            } else if (qName.equals("listPoiReturn"))
            {
                currentElement=qName;
                //System.out.println("SimpleSaxHandler$SaxHandler.startElement listPois");
            }
            else if(qName.equals("getRangePoiResponse"))
            {
                currentElement=qName;
            }
            else if(qName.equals("getRangePoiReturn"))
            {
                currentElement=qName;
                System.out.println("PoiSaxHandler.startElement "+attrs.getLocalName(0));
                if(attrs.getLocalName(0)!=null&&attrs.getLocalName(0).equals("xsi:type"))
                {
                    //System.out.println("SimpleSaxHandler$SaxHandler.startElement nuovo pois");
    
                    if(cicle==0)
                        p=new Poi();
                    else{
                        pois.add(p);
                        p=new Poi();
                    }
                    cicle++;
                }
            }
            else if (qName.equals("item"))
            {
                currentElement=qName;
    
    
            }
            else if (qName.equals("key"))
            {
                currentElement=qName;
                //System.out.println("SimpleSaxHandler$SaxHandler "+currentElement);
    
                //System.out.println("SimpleSaxHandler$SaxHandler.startElement key  "+key);
            }
            else if (qName.equals("value"))
            {
                currentElement=qName;
    
                //System.out.println("SimpleSaxHandler$SaxHandler.startElement value di "+key+" -->"+attrs.getQName(0));
            }
    
            else {
                throw new IllegalArgumentException("Element '" +
                        qName + "' is not allowed here");
            }
        }
    
    
    
    
        // we leave element 'qName' without any actions:
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
    
            //System.out.println("SimpleSaxHandler$SaxHandler.endElement "+qName);
    
    
    
        }
    
        public void characters(char ch[], int start, int length)
                throws SAXException {
    
    
            if(currentElement.equals("key")&&(new String(ch, start, length).equals("Id")))
                isId=true;
            else if(currentElement.equals("key")&&(new String(ch, start, length).equals("Lat")))
                isLat=true;
            else if(currentElement.equals("key")&&(new String(ch, start, length).equals("Lon")))
                isLon=true;
            else if(currentElement.equals("key")&&(new String(ch, start, length).equals("Alt")))
                isAlt=true;
            else if(currentElement.equals("key")&&(new String(ch, start, length).equals("Tipologia")))
                isTipologia=true;
            else if(currentElement.equals("key")&&(new String(ch, start, length).equals("Nome")))
                isNome=true;
            else if(currentElement.equals("key")&&(new String(ch, start, length).equals("Wikilink")))
                isWiki=true;
            else if(currentElement.equals("key")&&(new String(ch, start, length).equals("Distance")))
                isPoiId=true;
            //System.out.println("currentElement: "+currentElement+" -->"+ new String(ch, start, length));
            if (isId&&currentElement.equals("value")) {
                p.setId(Long.parseLong(new String(ch, start, length)));
                System.out.println("id: "
                        + new String(ch, start, length));
                isId=false;
            }else if (isLat&&currentElement.equals("value")) {
                p.setLat(Float.parseFloat(new String(ch, start, length)));
                System.out.println("lat: "
                        + new String(ch, start, length));
                isLat=false;
            }else if (isLon&&currentElement.equals("value")) {
                p.setLon(Float.parseFloat(new String(ch, start, length)));
                System.out.println("lon: "
                        + new String(ch, start, length));
                isLon=false;
            }
            else if(currentElement.equals("value")&&(isAlt))
            {
                p.setAlt(Float.parseFloat(new String(ch, start, length)));
                System.out.println("alt: "
                        + new String(ch, start, length));
                isAlt=false;;
            }
            else if(currentElement.equals("value")&&(isTipologia))
            {
                String sTipologia=new String(ch, start, length);
                int tipologia=0;
                if(sTipologia!=null&&!sTipologia.equals(""))
                    tipologia=Integer.parseInt(sTipologia);
    
                p.setTipologia(tipologia);
                System.out.println("Tipologia: "
                        + new String(ch, start, length));
                isTipologia=false;
    
            }
            else if(currentElement.equals("value")&&(isNome))
            {
                p.setNome(new String(ch, start, length));
                System.out.println("Nome: "
                        + new String(ch, start, length));
                isNome=false;
    
            }
            else if(currentElement.equals("value")&&(isWiki))
            {
                p.setWikilynk(new String(ch, start, length));
                System.out.println("Wiki: "
                        + new String(ch, start, length));
                isWiki=false;
    
            }
            else if(currentElement.equals("value")&&(isPoiId))
            {
                String sPoiId=new String(ch, start, length);
                Long poiId=0L;
                //if(sPoiId!=null&&!sPoiId.trim().equals(""))
                //poiId=Long.parseLong(sPoiId);
                p.setPoiId(sPoiId);
                System.out.println("PoiId: "
                        + new String(ch, start, length));
                isPoiId=false;
    
            }
        }
    
        public List<Poi> getPois() {
        	//Log.d("Sono entranto nel metodo getPois dentro la classe PoiSaxHandler", "1");
        	// Log.d("getPoisHandler", pois.toString());
            return pois;
        }
        // do nothing;
    }
    I messaggi di log che si visualizzano sono i seguenti:

    codice:
    10-29 17:51:03.571: INFO/System.out(322): Document processing started
    10-29 17:51:03.571: INFO/System.out(322): SimpleSaxHandler$SaxHandler.startElement body
    10-29 17:51:03.571: INFO/System.out(322): PoiSaxHandler.startElement null
    10-29 17:51:03.571: INFO/System.out(322): PoiSaxHandler.startElement type
    10-29 17:51:03.571: DEBUG/AndroidRuntime(322): Shutting down VM
    Questa volta non sono stati creati con il metodo log ma più banalmente con println e si può vedere che il primo viene stampato quando parte il metodo startDocument() e gli altri sempre in altri punti dell'handler dove arriva...quindi pare probabile che il problema sia da ricercare in questa classe dell'handler che non riesce a fare qualcosa !!!


    Grazie mille

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.