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:com.aionemu.gameserver.dataholders.loadingutils.XmlMerger.java

/**
 * Check for modifications of included files.
 *
 * @return <code>true</code> if at least one of included files has
 * modifications./* w  ww.  j  a va 2  s .  co  m*/
 * @throws IOException                  IO Error.
 * @throws SAXException                 Document parsing error.
 * @throws ParserConfigurationException if a SAX parser cannot be created
 *                                      which satisfies the requested configuration.
 */
private boolean checkFileModifications() throws Exception {
    long destFileTime = destFile.lastModified();

    if (sourceFile.lastModified() > destFileTime) {
        logger.debug("Source file was modified ");
        return true;
    }

    Properties metadata = restoreFileModifications(metaDataFile);

    if (metadata == null) // new file or smth else.
    {
        return true;
    }

    SAXParserFactory parserFactory = SAXParserFactory.newInstance();

    SAXParser parser = parserFactory.newSAXParser();

    TimeCheckerHandler handler = new TimeCheckerHandler(baseDir, metadata);

    parser.parse(sourceFile, handler);

    return handler.isModified();
}

From source file:se.lu.nateko.edca.svc.GetCapabilities.java

/**
 * Parses an XML response from a GetCapabilities request and stores available Layers
 * and options in the local SQLite database.
 * @param xmlResponse A reader wrapped around an InputStream containing the XML response from a GetCapabilities request.
 *///from   w w w . j a va  2s.c o  m
protected boolean parseXMLResponse(BufferedReader xmlResponse) {
    Log.d(TAG, "parseXMLResponse(Reader) called.");

    try {
        SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Make a SAXParser factory.
        spfactory.setValidating(false); // Tell the factory not to make validating parsers.
        SAXParser saxParser = spfactory.newSAXParser(); // Use the factory to make a SAXParser.
        XMLReader xmlReader = saxParser.getXMLReader(); // Get an XML reader from the parser, which will send event calls to its specified event handler.
        XMLEventHandler xmlEventHandler = new XMLEventHandler();
        xmlReader.setContentHandler(xmlEventHandler); // Set which event handler to use.
        xmlReader.setErrorHandler(xmlEventHandler); // Also set where to send error calls.
        InputSource source = new InputSource(xmlResponse); // Make an InputSource from the XML input to give to the reader.
        xmlReader.parse(source); // Start parsing the XML.
    } catch (Exception e) {
        Log.e(TAG, "XML parsing error: " + e.toString() + " - " + e.getMessage());
        return false;
    }
    return true;
}

From source file:crawlercommons.sitemaps.SiteMapParserSAX.java

/**
 * Parse the given XML content.//from   www.  j  a  va2 s .com
 * 
 * @param sitemapUrl
 *            a sitemap {@link java.net.URL}
 * @param is
 *            an {@link org.xml.sax.InputSource} backing the sitemap
 * @return the site map
 * @throws UnknownFormatException
 *             if there is an error parsing the
 *             {@link org.xml.sax.InputSource}
 */
protected AbstractSiteMap processXml(URL sitemapUrl, InputSource is) throws UnknownFormatException {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    DelegatorHandler handler = new DelegatorHandler(sitemapUrl, strict);
    try {
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(is, handler);
        AbstractSiteMap sitemap = handler.getSiteMap();
        if (sitemap == null) {
            throw new UnknownFormatException("Unknown XML format for: " + sitemapUrl);
        }
        return sitemap;
    } catch (IOException e) {
        LOG.warn("Error parsing sitemap {}: {}", sitemapUrl, e.getMessage());
        UnknownFormatException ufe = new UnknownFormatException("Failed to parse " + sitemapUrl);
        ufe.initCause(e);
        throw ufe;
    } catch (SAXException e) {
        LOG.warn("Error parsing sitemap {}: {}", sitemapUrl, e.getMessage());
        AbstractSiteMap sitemap = handler.getSiteMap();
        if (allowPartial && sitemap != null) {
            LOG.warn("Processed broken/partial sitemap for '" + sitemapUrl + "'");
            sitemap.setProcessed(true);
            return sitemap;
        } else {
            UnknownFormatException ufe = new UnknownFormatException("Failed to parse " + sitemapUrl);
            ufe.initCause(e);
            throw ufe;
        }
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException(e);
    }
}

From source file:es.rczone.tutoriales.gmaps.MainActivity.java

private void cargarKML(String ruta) {
    try {//from  w  w w .j  a v  a  2  s. c  o  m
        InputStream is_kml = getResources().getAssets().open(ruta);

        // create the factory
        SAXParserFactory factory = SAXParserFactory.newInstance();
        // create a parser
        SAXParser parser;
        parser = factory.newSAXParser();

        // create the reader (scanner)
        XMLReader xmlreader = parser.getXMLReader();
        // instantiate our handler
        NavigationSaxHandler navSaxHandler = new NavigationSaxHandler();
        // assign our handler
        xmlreader.setContentHandler(navSaxHandler);
        // get our data via the url class
        InputSource is = new InputSource(is_kml);
        // perform the synchronous parse           
        xmlreader.parse(is);

        // get the results - should be a fully populated RSSFeed instance, or null on error
        NavigationDataSet ds = navSaxHandler.getParsedData();

        Placemark place = ds.getPlacemarks().get(0);

        ArrayList<String> lista_coordenadas = place.getCoordinates();

        LatLng locationToCamera = null;

        for (String coordenadas : lista_coordenadas) {
            locationToCamera = draw(coordenadas);
        }

        CameraPosition camPos = new CameraPosition.Builder().target(locationToCamera) //Centramos el mapa en Madrid
                .zoom(9) //Establecemos el zoom en 19
                .build();

        CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);

        map.animateCamera(camUpd3);

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

From source file:no.uis.service.studinfo.commons.StudinfoValidator.java

protected List<String> validate(String studieinfoXml, StudinfoType infoType, int year, FsSemester semester,
        String language) throws Exception {

    // save xml/*from  w w  w  .ja  va  2 s  . c  om*/
    File outFile = new File("target/out", infoType.toString() + year + semester + language + ".xml");
    if (outFile.exists()) {
        outFile.delete();
    } else {
        outFile.getParentFile().mkdirs();
    }
    File outBackup = new File("target/out", infoType.toString() + year + semester + language + "_orig.xml");
    Writer backupWriter = new OutputStreamWriter(new FileOutputStream(outBackup), IOUtils.UTF8_CHARSET);
    backupWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    IOUtils.copy(new StringReader(studieinfoXml), backupWriter, IOBUFFER_SIZE);
    backupWriter.flush();
    backupWriter.close();

    TransformerFactory trFactory = TransformerFactory.newInstance();
    Source schemaSource = new StreamSource(getClass().getResourceAsStream("/fspreprocess.xsl"));
    Transformer stylesheet = trFactory.newTransformer(schemaSource);

    Source input = new StreamSource(new StringReader(studieinfoXml));

    Result result = new StreamResult(outFile);
    stylesheet.transform(input, result);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(true);

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = schemaFactory
            .newSchema(new Source[] { new StreamSource(new File("src/main/xsd/studinfo.xsd")) });

    factory.setSchema(schema);

    SAXParser parser = factory.newSAXParser();

    XMLReader reader = parser.getXMLReader();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler(infoType, year, semester, language);
    reader.setErrorHandler(errorHandler);
    reader.setContentHandler(errorHandler);
    try {
        reader.parse(
                new InputSource(new InputStreamReader(new FileInputStream(outFile), IOUtils.UTF8_CHARSET)));
    } catch (SAXException ex) {
        // do nothing. The error is handled in the error handler
    }
    return errorHandler.getMessages();
}

From source file:com.vkassin.mtrade.Common.java

public static String generalWebServiceCall(String urlStr, ContentHandler handler) {

    String errorMsg = "";

    try {//from w  ww  . j a v a 2  s. c  o m
        URL url = new URL(urlStr);

        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("User-Agent", "Android Application: aMTrade");
        urlc.setRequestProperty("Connection", "close");
        // urlc.setRequestProperty("Accept-Charset", "windows-1251");
        // urlc.setRequestProperty("Accept-Charset",
        // "windows-1251,utf-8;q=0.7,*;q=0.7");
        urlc.setRequestProperty("Accept-Charset", "utf-8");

        urlc.setConnectTimeout(1000 * 5); // mTimeout is in seconds
        urlc.setDoInput(true);
        urlc.connect();

        if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // Get a SAXParser from the SAXPArserFactory.
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();

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

            // Apply the handler to the XML-Reader
            xr.setContentHandler(handler);

            // Parse the XML-data from our URL.
            InputStream is = urlc.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(500);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }
            ByteArrayInputStream bais = new ByteArrayInputStream(baf.toByteArray());
            // Reader isr = new InputStreamReader(bais, "windows-1251");
            Reader isr = new InputStreamReader(bais, "utf-8");
            InputSource ist = new InputSource();
            // ist.setEncoding("UTF-8");
            ist.setCharacterStream(isr);
            xr.parse(ist);
            // Parsing has finished.

            bis.close();
            baf.clear();
            bais.close();
            is.close();
        }

        urlc.disconnect();

    } catch (SAXException e) {
        // All is OK :)
    } catch (MalformedURLException e) {
        Log.e(TAG, errorMsg = "MalformedURLException");
    } catch (IOException e) {
        Log.e(TAG, errorMsg = "IOException");
    } catch (ParserConfigurationException e) {
        Log.e(TAG, errorMsg = "ParserConfigurationException");
    } catch (ArrayIndexOutOfBoundsException e) {
        Log.e(TAG, errorMsg = "ArrayIndexOutOfBoundsException");
    }

    return errorMsg;
}

From source file:fr.paris.lutece.plugins.calendar.web.CalendarStyleSheetJspBean.java

/**
 * Use parsing for validate the modify xsl file
 * /*from www .  java  2  s  . c om*/
 * @param baXslSource The XSL source
 * @return the message exception when the validation is false
 */
private String isValid(byte[] baXslSource) {
    String strError = null;

    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser analyzer = factory.newSAXParser();
        InputSource is = new InputSource(new ByteArrayInputStream(baXslSource));
        analyzer.getXMLReader().parse(is);
    } catch (Exception e) {
        strError = e.getMessage();
    }

    return strError;
}

From source file:immf.AppNotifications.java

private boolean auth() {
    boolean httpOk = false;
    while (!httpOk) {
        try {/*from   ww w.  j  a  v a2 s.c o m*/
            SAXParserFactory spfactory = SAXParserFactory.newInstance();
            SAXParser parser = spfactory.newSAXParser();
            byte[] xml = this.getCredentials();
            InputStream is = new ByteArrayInputStream(xml);
            parser.parse(is, this);
            httpOk = true;
        } catch (Exception e) {
            log.warn("5????", e);
            try {
                Thread.sleep(ReconnectInterval * ReconnectCount);
            } catch (Exception ee) {
            }
        }
    }
    if (!ok.equals("OK")) {
        ok = "";
        return false;
    }
    this.setCredentials();
    return true;
}

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

private void parseXmlString(String file) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {//from   www .j  a  va2s  .co m
        keepScreenOn.acquire();

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

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(file));
        xr.parse(is);
        server_lst = handler.getNewSrvs();
        get_apks = handler.getNewApks();

        keepScreenOn.release();

    } catch (IOException e) {
    } catch (SAXException e) {
    } catch (ParserConfigurationException e) {
    }
}