Example usage for javax.xml.parsers SAXParserFactory newSAXParser

List of usage examples for javax.xml.parsers SAXParserFactory newSAXParser

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory newSAXParser.

Prototype


public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;

Source Link

Document

Creates a new instance of a SAXParser using the currently configured factory parameters.

Usage

From source file:cm.aptoide.pt.Aptoide.java

private void getRemoteServLst(String file) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {//from ww w  .  jav  a 2s  .com
        keepScreenOn.acquire();

        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        NewServerRssHandler handler = new NewServerRssHandler(this);
        xr.setContentHandler(handler);

        InputStreamReader isr = new FileReader(new File(file));
        InputSource is = new InputSource(isr);
        xr.parse(is);
        File xml_file = new File(file);
        xml_file.delete();
        server_lst = handler.getNewSrvs();
        get_apks = handler.getNewApks();

        keepScreenOn.release();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}

From source file:com.prowidesoftware.swift.io.parser.MxParser.java

/**
 * Non-namespace aware parse.<br />
 * Parses the complete message content into an {@link MxNode} tree structure.
 * The parser should be initialized with a valid source.
 *
 * @since 7.7/*from www.j a va 2 s. c  om*/
 */
public MxNode parse() {
    Validate.notNull(buffer, "the source must be initialized");
    try {
        final javax.xml.parsers.SAXParserFactory spf = javax.xml.parsers.SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        final javax.xml.parsers.SAXParser saxParser = spf.newSAXParser();
        final MxNodeContentHandler contentHandler = new MxNodeContentHandler();
        final org.xml.sax.XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setContentHandler(contentHandler);
        xmlReader.parse(new org.xml.sax.InputSource(new StringReader(this.buffer)));
        return contentHandler.getRootNode();
    } catch (final Exception e) {
        log.log(Level.SEVERE, "Error parsing: ", e);
    }
    return null;
}

From source file:com.centurylink.mdw.util.HttpHelper.java

/**
 * Use SAX for fastest parsing.// w  ww .  j  ava2s  .c  om
 */
private URL parseResponseForHtmlMetaEquiv(String response)
        throws IOException, SAXException, ParserConfigurationException {
    final StringBuffer urlBuf = new StringBuffer();
    InputStream xmlStream = new ByteArrayInputStream(response.getBytes());
    InputSource src = new InputSource(xmlStream);
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    SAXParser parser = parserFactory.newSAXParser();
    parser.parse(src, new DefaultHandler() {
        boolean inHtml;
        boolean inHead;
        boolean inMeta;

        public void startElement(String uri, String localName, String qName, Attributes attrs)
                throws SAXException {
            if (qName.equals("html"))
                inHtml = true;
            else if (qName.equals("head"))
                inHead = true;
            else if (qName.equals("meta"))
                inMeta = true;

            if (inHtml && inHead && inMeta) {
                if ("refresh".equals(attrs.getValue("http-equiv"))) {
                    String cAttr = attrs.getValue("content");
                    if (cAttr != null) {
                        int urlIdx = cAttr.indexOf("url=");
                        if (urlIdx >= 0)
                            urlBuf.append(cAttr.substring(urlIdx + 4));
                    }
                }
            }
        }

        public void endElement(String uri, String localName, String qName) throws SAXException {
            if (qName.equals("html"))
                inHtml = false;
            else if (qName.equals("head"))
                inHead = false;
            else if (qName.equals("meta"))
                inMeta = false;
        }
    });

    String str = urlBuf.toString().trim();
    if (str.isEmpty())
        return null;
    else
        return new URL(str);
}

From source file:de.tlabs.ssr.g1.client.XmlInputThread.java

@Override
public void run() {
    Log.d(TAG, "(" + this.getId() + ") HELLO");

    try {//from w w w  . j  a  v a2s.c  om
        // create sax parser
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        // get an xml reader 
        XMLReader xr = sp.getXMLReader();

        // set up xml input source
        XMLChunkInputStream xmlChunkInputStream;
        synchronized (GlobalData.socketChannel) {
            xmlChunkInputStream = new XMLChunkInputStream(new ByteArrayBuffer(32 * 1024),
                    GlobalData.socketChannel.socket().getInputStream());
        }
        InputSource inputSource = new InputSource(xmlChunkInputStream);

        // create handler for scene description and assign it
        SceneDescrXMLHandler sceneDescrXMLHandler = new SceneDescrXMLHandler(GlobalData.audioScene);
        xr.setContentHandler(sceneDescrXMLHandler);

        // parse scene description
        //Log.d(TAG, "(" + this.getId() + ") parsing description...");
        //xmlChunkInputStream.printToLog = true;
        while (xmlChunkInputStream.bufferNextChunk() && !sceneDescrXMLHandler.receivedSceneDescr()) {
            // parse and process xml input
            xr.parse(inputSource);
        }
        //xmlChunkInputStream.printToLog = false;

        // signal that scene description was parsed
        //Log.d(TAG, "(" + this.getId() + ") sending SCENEPARSED_OK_MSG");
        GlobalData.sourcesMoverMsgHandler
                .sendMessage(GlobalData.sourcesMoverMsgHandler.obtainMessage(SourcesMover.SCENEPARSED_OK_MSG));

        // create handler for scene updates and assign it
        SceneUpdateXMLHandler sceneUpdateXMLHandler = new SceneUpdateXMLHandler(GlobalData.audioScene);
        xr.setContentHandler(sceneUpdateXMLHandler);

        // parse scene updates
        Log.d(TAG, "(" + this.getId() + ") starting xml input loop...");
        while (xmlChunkInputStream.bufferNextChunk()) {
            // parse and process xml input
            xr.parse(inputSource);

            // check if we should abort
            synchronized (abortFlag) {
                if (abortFlag == true) {
                    break;
                }
            }
        }
    } catch (Exception e) {
        Log.d(TAG, "(" + this.getId() + ") Exception " + e.toString() + ": " + e.getMessage());

        // check if this thread was aborted and/or stopped by a call to interrupt()
        if (Thread.interrupted() || abortFlag) {
            Log.d(TAG, "(" + this.getId() + ") interrupted/aborted");
        } else {
            GlobalData.sourcesMoverMsgHandler.sendMessage(GlobalData.sourcesMoverMsgHandler
                    .obtainMessage(SourcesMover.XMLINPUT_ERR_MSG, e.getMessage()));
            Log.d(TAG, "(" + this.getId() + ") sending XMLINPUT_ERR_MSG");
        }
    }

    Log.d(TAG, "(" + this.getId() + ") GOOD BYE");
}

From source file:fr.gouv.finances.dgfip.xemelios.importers.DefaultImporter.java

protected XmlSplitter splitFile(File fHeader, File fRef, File fFooter, File tmpDir, File fToImport,
        String fileEncoding)// www .  j  a va  2 s.  co m
        throws FileNotFoundException, UnsupportedEncodingException, SAXException, ParserConfigurationException {
    FileOutputStream fisHeader = new FileOutputStream(fHeader);
    FileOutputStream fisRef = new FileOutputStream(fRef);
    FileOutputStream fisFooter = new FileOutputStream(fFooter);
    XmlSplitter xs = new XmlSplitter(fisHeader, fisRef, fisFooter, tmpDir, dm, fileEncoding);
    xs.setImportLogPrintWriter(importTimingOS);
    xs.setSplittedFileName(fToImport.getName());
    SAXParserFactory sf = FactoryProvider.getSaxParserFactory();
    SAXParser parser = sf.newSAXParser();
    try {
        parser.parse(fToImport, xs);
    } catch (Exception ex) {
        ex.printStackTrace();
        String position = "line " + xs.getLocator().getLineNumber() + ": ";
        throw new SAXException(position + ex.getMessage(), ex);
    } finally {
        if (fisHeader != null) {
            try {
                fisHeader.flush();
                fisHeader.close();
            } catch (Throwable t) {
            }
        }
        if (fisRef != null) {
            try {
                fisRef.flush();
                fisRef.close();
            } catch (Throwable t) {
            }
        }
        if (fisFooter != null) {
            try {
                fisFooter.flush();
                fisFooter.close();
            } catch (Throwable t) {
            }
        }
    }
    return xs;
}

From source file:net.sbbi.upnp.messages.StateVariableMessage.java

/**
 * Executes the state variable query and retuns the UPNP device response, according to the UPNP specs,
 * this method could take up to 30 secs to process ( time allowed for a device to respond to a request )
 * @return a state variable response object containing the variable value
 * @throws IOException if some IOException occurs during message send and reception process
 * @throws UPNPResponseException if an UPNP error message is returned from the server
 *         or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message )
 */// w ww  .  j a v  a2s. c  o m
public StateVariableResponse service() throws IOException, UPNPResponseException {
    StateVariableResponse rtrVal = null;
    UPNPResponseException upnpEx = null;
    IOException ioEx = null;
    StringBuffer body = new StringBuffer(256);

    body.append("<?xml version=\"1.0\"?>\r\n");
    body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"");
    body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
    body.append("<s:Body>");
    body.append("<u:QueryStateVariable xmlns:u=\"urn:schemas-upnp-org:control-1-0\">");
    body.append("<u:varName>").append(serviceStateVar.getName()).append("</u:varName>");
    body.append("</u:QueryStateVariable>");
    body.append("</s:Body>");
    body.append("</s:Envelope>");

    if (log.isDebugEnabled())
        log.debug("POST prepared for URL " + service.getControlURL());
    URL url = new URL(service.getControlURL().toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    HttpURLConnection.setFollowRedirects(false);
    //conn.setConnectTimeout( 30000 );
    conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort());
    conn.setRequestProperty("SOAPACTION", "\"urn:schemas-upnp-org:control-1-0#QueryStateVariable\"");
    conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
    conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length()));
    OutputStream out = conn.getOutputStream();
    out.write(body.toString().getBytes());
    out.flush();
    conn.connect();
    InputStream input = null;

    if (log.isDebugEnabled())
        log.debug("executing query :\n" + body);
    try {
        input = conn.getInputStream();
    } catch (IOException ex) {
        // java can throw an exception if he error code is 500 or 404 or something else than 200
        // but the device sends 500 error message with content that is required
        // this content is accessible with the getErrorStream
        input = conn.getErrorStream();
    }

    if (input != null) {
        int response = conn.getResponseCode();
        String responseBody = getResponseBody(input);
        if (log.isDebugEnabled())
            log.debug("received response :\n" + responseBody);
        SAXParserFactory saxParFact = SAXParserFactory.newInstance();
        saxParFact.setValidating(false);
        saxParFact.setNamespaceAware(true);
        StateVariableResponseParser msgParser = new StateVariableResponseParser(serviceStateVar);
        StringReader stringReader = new StringReader(responseBody);
        InputSource src = new InputSource(stringReader);
        try {
            SAXParser parser = saxParFact.newSAXParser();
            parser.parse(src, msgParser);
        } catch (ParserConfigurationException confEx) {
            // should never happen
            // we throw a runtimeException to notify the env problem
            throw new RuntimeException(
                    "ParserConfigurationException during SAX parser creation, please check your env settings:"
                            + confEx.getMessage());
        } catch (SAXException saxEx) {
            // kind of tricky but better than nothing..
            upnpEx = new UPNPResponseException(899, saxEx.getMessage());
        } finally {
            try {
                input.close();
            } catch (IOException ex) {
                // ignoring
            }
        }
        if (upnpEx == null) {
            if (response == HttpURLConnection.HTTP_OK) {
                rtrVal = msgParser.getStateVariableResponse();
            } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                upnpEx = msgParser.getUPNPResponseException();
            } else {
                ioEx = new IOException("Unexpected server HTTP response:" + response);
            }
        }
    }
    try {
        out.close();
    } catch (IOException ex) {
        // ignore
    }
    conn.disconnect();
    if (upnpEx != null) {
        throw upnpEx;
    }
    if (rtrVal == null && ioEx == null) {
        ioEx = new IOException("Unable to receive a response from the UPNP device");
    }
    if (ioEx != null) {
        throw ioEx;
    }
    return rtrVal;
}

From source file:com.aurel.track.exchange.docx.importer.HTMLParser.java

private void parse(ByteArrayOutputStream byteArrayOutputStream, Locale locale) {
    localizedHeading = "berschrift";//LocalizeUtil.getLocalizedTextFromApplicationResources(HEADING_KEY, locale);
    SAXParserFactory spf = SAXParserFactory.newInstance();
    Reader fileReader = null;/*ww w  .  jav  a 2s .c o  m*/
    try {
        fileReader = new FileReader(new File("d:/docx/PN164_SC_Track.docx.html"));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
    try {
        //get a new instance of parser
        SAXParser sp = spf.newSAXParser();
        //InputSource is=new InputSource(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
        InputSource is = new InputSource(fileReader);
        sp.parse(is, this);
    } catch (SAXException se) {
        LOGGER.error("Parsing failed with " + se.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.error(ExceptionUtils.getStackTrace(se));
        }
    } catch (ParserConfigurationException pce) {
        LOGGER.error("Parsing failed with " + pce.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.error(ExceptionUtils.getStackTrace(pce));
        }
    } catch (IOException ie) {
        LOGGER.error("Reading failed with " + ie.getMessage());
        LOGGER.error(ExceptionUtils.getStackTrace(ie));
    }
}

From source file:sundroid.code.SundroidActivity.java

/** Called when the activity is first created. ***/
@Override// ww  w.j  a v a 2s.  c o m
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    this.chk_usecelsius = (CheckBox) findViewById(R.id.chk_usecelsius);
    Button cmd_submit = (Button) findViewById(R.id.cmd_submit);

    cmd_submit.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {

            try {

                ///////////////// Code to get weather conditions for entered place ///////////////////////////////////////////////////
                String cityParamString = ((EditText) findViewById(R.id.edit_input)).getText().toString();
                String queryString = "https://www.google.com/ig/api?weather=" + cityParamString;
                queryString = queryString.replace("#", "");

                /* Parsing the xml file*/
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();

                GoogleWeatherHandler gwh = new GoogleWeatherHandler();
                xr.setContentHandler(gwh);

                HttpClient httpclient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(queryString.replace(" ", "%20"));
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String responseBody = httpclient.execute(httpget, responseHandler);
                ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes());
                xr.parse(new InputSource(is));
                Log.d("Sundroid", "parse complete");

                WeatherSet ws = gwh.getWeatherSet();

                newupdateWeatherInfoView(R.id.weather_today, ws.getWeatherCurrentCondition(),
                        " " + cityParamString, "");

                ///////////////// Code to get weather conditions for entered place ends /////////////////////////////////////////////////// 

                ///////////////// Code to get latitude and longitude using zipcode starts ///////////////////////////////////////////////////

                String latlng_querystring = "http://maps.googleapis.com/maps/api/geocode/xml?address="
                        + cityParamString.replace(" ", "%20") + "&sensor=false";
                URL url_latlng = new URL(latlng_querystring);
                spf = SAXParserFactory.newInstance();
                sp = spf.newSAXParser();

                xr = sp.getXMLReader();
                xmlhandler_latlong xll = new xmlhandler_latlong();
                xr.setContentHandler(xll);
                xr.parse(new InputSource(url_latlng.openStream()));

                Latitude_longitude ll = xll.getLatlng_resultset();
                double selectedLat = ll.getLat_lng_pair().getLat();
                double selectedLng = ll.getLat_lng_pair().getLon();

                ///////////////// Code to get latitude and longitude using zipcode ends ///////////////////////////////////////////////////

                ///////////////// Code to get miles from text box & convert to meters for passing into the api link////////////////////////
                EditText edt = (EditText) findViewById(R.id.edit_miles);
                float miles = Float.valueOf(edt.getText().toString());
                float meters = (float) (miles * 1609.344);

                ///////////////// Code to get miles from text box & convert to meters for passing into the api link ends /////////////////

                ///////////////// Code to pass lat,long and radius and get destinations from places api starts////////// /////////////////
                URL queryString_1 = new URL("https://maps.googleapis.com/maps/api/place/search/xml?location="
                        + Double.toString(selectedLat) + "," + Double.toString(selectedLng) + "&radius="
                        + Float.toString(meters)
                        + "&types=park|types=aquarium|types=point_of_interest|types=establishment|types=museum&sensor=false&key=AIzaSyDmP0SB1SDMkAJ1ebxowsOjpAyeyiwHKQU");
                spf = SAXParserFactory.newInstance();
                sp = spf.newSAXParser();
                xr = sp.getXMLReader();
                xmlhandler_places xhp = new xmlhandler_places();
                xr.setContentHandler(xhp);
                xr.parse(new InputSource(queryString_1.openStream()));
                int arraysize = xhp.getVicinity_List().size();
                String[] place = new String[25];
                String[] place_name = new String[25];
                Double[] lat_pt = new Double[25];
                Double[] lng_pt = new Double[25];
                int i;
                //Getting name and vicinity tags from the xml file//
                for (i = 0; i < arraysize; i++) {
                    place[i] = xhp.getVicinity_List().get(i);
                    place_name[i] = xhp.getPlacename_List().get(i);
                    lat_pt[i] = xhp.getLatlist().get(i);
                    lng_pt[i] = xhp.getLonglist().get(i);
                    System.out.println("long -" + lng_pt[i]);
                    place[i] = place[i].replace("#", "");

                }

                ///////////////// Code to pass lat,long and radius and get destinations from places api ends////////// /////////////////

                //////////////////////while loop for getting top 5 from the array////////////////////////////////////////////////

                int count = 0;
                int while_ctr = 0;
                String str_weathercondition;
                str_weathercondition = "";
                WeatherCurrentCondition reftemp;
                //Places to visit if none of places in the given radius are sunny/clear/partly cloudy
                String[] rainy_place = { "Indoor Mall", "Watch a Movie", "Go to a Restaurant", "Shopping!" };
                double theDistance = 0;
                String str_dist = "";
                while (count < 5) {
                    //Checking if xml vicinity value is empty
                    while (place[while_ctr] == null || place[while_ctr].length() < 2) {
                        while_ctr = while_ctr + 1;
                    }
                    //First search for places that are sunny or clear 
                    if (while_ctr < i - 1) {
                        queryString = "https://www.google.com/ig/api?weather=" + place[while_ctr];
                        System.out.println("In while loop - " + queryString);
                        theDistance = (Math.sin(Math.toRadians(selectedLat))
                                * Math.sin(Math.toRadians(lat_pt[while_ctr]))
                                + Math.cos(Math.toRadians(selectedLat))
                                        * Math.cos(Math.toRadians(lat_pt[while_ctr]))
                                        * Math.cos(Math.toRadians(selectedLng - lng_pt[while_ctr])));
                        str_dist = new Double((Math.toDegrees(Math.acos(theDistance))) * 69.09).intValue()
                                + " miles";
                        System.out.println(str_dist);
                        spf = SAXParserFactory.newInstance();
                        sp = spf.newSAXParser();

                        xr = sp.getXMLReader();

                        gwh = new GoogleWeatherHandler();
                        xr.setContentHandler(gwh);
                        httpclient = new DefaultHttpClient();
                        httpget = new HttpGet(queryString.replace(" ", "%20"));
                        responseHandler = new BasicResponseHandler();
                        responseBody = httpclient.execute(httpget, responseHandler);
                        is = new ByteArrayInputStream(responseBody.getBytes());
                        xr.parse(new InputSource(is));
                        if (gwh.isIn_error_information()) {
                            System.out.println("Error Info flag set");
                        } else {
                            ws = gwh.getWeatherSet();

                            reftemp = ws.getWeatherCurrentCondition();
                            str_weathercondition = reftemp.getCondition();

                            //         Check if the condition is sunny or partly cloudy
                            if (str_weathercondition.equals("Sunny")
                                    || str_weathercondition.equals("Mostly Sunny")
                                    || str_weathercondition.equals("Clear")) {
                                System.out.println("Sunny Loop");

                                //  Increment the count 
                                ++count;

                                //   Disply the place on the widget 
                                if (count == 1) {
                                    newupdateWeatherInfoView(R.id.weather_1, reftemp, place_name[while_ctr],
                                            str_dist);
                                } else if (count == 2) {
                                    newupdateWeatherInfoView(R.id.weather_2, reftemp, place_name[while_ctr],
                                            str_dist);
                                } else if (count == 3) {
                                    newupdateWeatherInfoView(R.id.weather_3, reftemp, place_name[while_ctr],
                                            str_dist);
                                } else if (count == 4) {
                                    newupdateWeatherInfoView(R.id.weather_4, reftemp, place_name[while_ctr],
                                            str_dist);
                                } else if (count == 5) {
                                    newupdateWeatherInfoView(R.id.weather_5, reftemp, place_name[while_ctr],
                                            str_dist);
                                } else {
                                }
                            }
                        }
                    }

                    //  If Five sunny places not found then search for partly cloudy places 

                    else if (while_ctr >= i && while_ctr < i * 2) {
                        queryString = "https://www.google.com/ig/api?weather=" + place[while_ctr - i];
                        queryString = queryString.replace("  ", " ");

                        spf = SAXParserFactory.newInstance();
                        sp = spf.newSAXParser();

                        // Get the XMLReader of the SAXParser we created. 
                        xr = sp.getXMLReader();

                        gwh = new GoogleWeatherHandler();
                        xr.setContentHandler(gwh);

                        // Use HTTPClient to deal with the URL  
                        httpclient = new DefaultHttpClient();
                        httpget = new HttpGet(queryString.replace(" ", "%20"));
                        responseHandler = new BasicResponseHandler();
                        responseBody = httpclient.execute(httpget, responseHandler);
                        is = new ByteArrayInputStream(responseBody.getBytes());
                        xr.parse(new InputSource(is));
                        Log.d(DEBUG_TAG, "parse complete");

                        if (gwh.isIn_error_information()) {
                        } else {
                            ws = gwh.getWeatherSet();
                            reftemp = ws.getWeatherCurrentCondition();
                            str_weathercondition = reftemp.getCondition();

                            //    Check if the condition is sunny or partly cloudy
                            if (str_weathercondition.equals("Partly Cloudy")) {

                                count = count + 1;

                                //  Display the place 
                                if (count == 1) {
                                    newupdateWeatherInfoView(R.id.weather_1, reftemp, place_name[while_ctr - i],
                                            str_dist);
                                } else if (count == 2) {
                                    newupdateWeatherInfoView(R.id.weather_2, reftemp, place_name[while_ctr - i],
                                            str_dist);
                                } else if (count == 3) {
                                    newupdateWeatherInfoView(R.id.weather_3, reftemp, place_name[while_ctr - i],
                                            str_dist);
                                } else if (count == 4) {
                                    newupdateWeatherInfoView(R.id.weather_4, reftemp, place_name[while_ctr - i],
                                            str_dist);
                                } else if (count == 5) {
                                    newupdateWeatherInfoView(R.id.weather_5, reftemp, place_name[while_ctr - i],
                                            str_dist);
                                } else {
                                }
                            }
                        }
                    }
                    ////////////////////////////////  Give suggestions for a rainy day 
                    else {
                        queryString = "https://www.google.com/ig/api?weather=" + cityParamString;
                        queryString = queryString.replace("#", "");

                        spf = SAXParserFactory.newInstance();
                        sp = spf.newSAXParser();

                        // Get the XMLReader of the SAXParser we created. 
                        xr = sp.getXMLReader();
                        gwh = new GoogleWeatherHandler();
                        xr.setContentHandler(gwh);

                        httpclient = new DefaultHttpClient();

                        httpget = new HttpGet(queryString.replace(" ", "%20"));
                        // create a response handler 
                        responseHandler = new BasicResponseHandler();
                        responseBody = httpclient.execute(httpget, responseHandler);
                        is = new ByteArrayInputStream(responseBody.getBytes());
                        xr.parse(new InputSource(is));
                        if (gwh.isIn_error_information()) {
                        }

                        else {
                            ws = gwh.getWeatherSet();

                            reftemp = ws.getWeatherCurrentCondition();
                            str_weathercondition = reftemp.getCondition();

                            if (count == 0) {
                                newupdateWeatherInfoView(R.id.weather_1, reftemp, rainy_place[0], "");
                                newupdateWeatherInfoView(R.id.weather_2, reftemp, rainy_place[1], "");
                                newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], "");
                                newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[3], "");
                                newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], "");
                            } else if (count == 1) {
                                newupdateWeatherInfoView(R.id.weather_2, reftemp, rainy_place[1], "");
                                newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], "");
                                newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[3], "");
                                newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[0], "");
                            } else if (count == 2) {
                                newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], "");
                                newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[0], "");
                                newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], "");
                            } else if (count == 3) {
                                newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[0], "");
                                newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], "");
                            } else if (count == 4) {
                                newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], "");
                            } else {
                            }
                            count = 5;
                        }
                        count = 5;
                    }
                    while_ctr++;
                }

                /////////////Closing the soft keypad////////////////
                InputMethodManager iMethodMgr = (InputMethodManager) getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                iMethodMgr.hideSoftInputFromWindow(edt.getWindowToken(), 0);

            } catch (Exception e) {
                resetWeatherInfoViews();
                Log.e(DEBUG_TAG, "WeatherQueryError", e);
            }
        }
    });
}

From source file:com.penbase.dma.Dalyo.HTTPConnection.DmaHttpClient.java

/**
 * Gets the resources of an application/*from  w  w w . j  av  a  2s.c  om*/
 */
public void getResource(String urlRequest) {
    if (mSendResource) {
        StringBuffer getResources = new StringBuffer("act=getresources");
        getResources.append(urlRequest);
        byte[] bytes = sendPost(getResources.toString());
        SAXParserFactory spFactory = SAXParserFactory.newInstance();
        SAXParser saxParser;
        try {
            saxParser = spFactory.newSAXParser();
            XMLReader xmlReader = saxParser.getXMLReader();
            EventsHandler eventsHandler = new EventsHandler(urlRequest);
            xmlReader.setContentHandler(eventsHandler);
            xmlReader.parse(new InputSource(new ByteArrayInputStream(bytes)));
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Common.streamToFile(bytes, mResources_XML, false);
    } else {
        SAXParserFactory spFactory = SAXParserFactory.newInstance();
        SAXParser saxParser;
        try {
            saxParser = spFactory.newSAXParser();
            XMLReader xmlReader = saxParser.getXMLReader();
            EventsHandler eventsHandler = new EventsHandler(urlRequest);
            xmlReader.setContentHandler(eventsHandler);
            xmlReader.parse(new InputSource(new FileInputStream(new File(mResources_XML))));
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.openbravo.pos.sales.JTicketLines.java

/** Creates new form JLinesTicket */
public JTicketLines(AppView app, String propertyRowHeight, String propertyFontsize, String ticketline) {
    this.m_App = app;
    initComponents();//from  w  w w  .jav a2 s. co m

    m_jTicketTable.m_App = app;
    m_jTicketTable.propertyRowHeight = propertyRowHeight;

    ColumnTicket[] acolumns = new ColumnTicket[0];

    if (ticketline != null) {
        try {
            if (m_sp == null) {
                SAXParserFactory spf = SAXParserFactory.newInstance();
                m_sp = spf.newSAXParser();
            }
            ColumnsHandler columnshandler = new ColumnsHandler();
            m_sp.parse(new InputSource(new StringReader(ticketline)), columnshandler);
            acolumns = columnshandler.getColumns();

        } catch (ParserConfigurationException ePC) {
            logger.log(Level.WARNING, LocalRes.getIntString("exception.parserconfig"), ePC);
        } catch (SAXException eSAX) {
            logger.log(Level.WARNING, LocalRes.getIntString("exception.xmlfile"), eSAX);
        } catch (IOException eIO) {
            logger.log(Level.WARNING, LocalRes.getIntString("exception.iofile"), eIO);
        }
    }

    Map<String, Integer> widths = PropertyUtil.getTicketLineWidths(m_App);
    for (ColumnTicket acolumn : acolumns) {
        Integer width = widths.get(acolumn.name);
        if (width == null) {
            continue;
        }
        acolumn.width = width;
    }

    m_jTableModel = new TicketTableModel(acolumns);
    m_jTicketTable.setModel(m_jTableModel);

    m_jTicketTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
    TableColumnModel jColumns = m_jTicketTable.getColumnModel();
    for (int i = 0; i < acolumns.length; i++) {
        jColumns.getColumn(i).setPreferredWidth(acolumns[i].width);
        jColumns.getColumn(i).setResizable(true);
    }

    PropertyUtil.ScaleScrollbar(m_App, m_jScrollTableTicket);

    m_jTicketTable.getTableHeader().setReorderingAllowed(false);
    // m_jTicketTable.setDefaultRenderer(Object.class, new
    // TicketCellRenderer(app, acolumns, propertyFontsize));
    m_jTicketTable.setDefaultRenderer(Object.class,
            new RowHeightCellRenderer(app, acolumns, propertyFontsize, propertyRowHeight));

    PropertyUtil.ScaleTableColumnFontsize(m_App, m_jTicketTable, "sales-tablecolumn-fontsize", "14");

    m_jTicketTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    m_jTicketTable.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent me) {
            JTable table = (JTable) me.getSource();
            Point p = me.getPoint();
            int row = table.rowAtPoint(p);
            if (me.getClickCount() == 2) {
                // your valueChanged overridden method
                listDoubleClickListener.valueChanged(new ListSelectionEvent(m_jTicketTable, row, row, false));
            }
        }
    });
    // reseteo la tabla...
    m_jTableModel.clear();
}