Example usage for org.xml.sax XMLReader parse

List of usage examples for org.xml.sax XMLReader parse

Introduction

In this page you can find the example usage for org.xml.sax XMLReader parse.

Prototype

public void parse(String systemId) throws IOException, SAXException;

Source Link

Document

Parse an XML document from a system identifier (URI).

Usage

From source file:com.notesrender.templatej.TemplateProcessor.java

public void process(String filePath) {
    try {/*  w w w .j av a2  s  .  co m*/
        XMLReader rd = XMLReaderFactory.createXMLReader();
        rd.setContentHandler(this);
        rd.parse(new InputSource(new FileInputStream(filePath)));

        String fullFilePath = new File(filePath).getAbsolutePath();
        String dir = FilenameUtils.getFullPath(fullFilePath);
        String tplFullFilePath = new File(dir, _ref).getAbsolutePath();
        String outFullFilePath = new File(dir, _out).getAbsolutePath();

        _writer = new PrintWriter(new BufferedWriter(new FileWriter(outFullFilePath)));
        rd.parse(new InputSource(new FileInputStream(tplFullFilePath)));
        _writer.close();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:de.faustedition.tei.TeiValidator.java

public List<String> validate(FaustURI uri) throws SAXException, IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("Validating via RelaxNG: " + uri);
    }//from ww w. j a v a 2s  .co m
    final CustomErrorHandler errorHandler = new CustomErrorHandler();
    final Validator validator = schema
            .createValidator(errorHandler.configurationWithErrorHandler().toPropertyMap());

    final XMLReader xmlReader = XMLReaderFactory.createXMLReader();
    xmlReader.setContentHandler(validator.getContentHandler());
    xmlReader.parse(xml.getInputSource(uri));

    return errorHandler.getErrors();
}

From source file:it.openyoureyes.test.OpenCellId.java

private String parseImage(HttpEntity entity, DefaultHandler dd) throws IOException {
    String result = "";
    String line;//from  w  w  w .ja  v  a2  s.  c  o m

    try {

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        xr.setContentHandler(dd);

        /* Parse the xml-data from our URL. */
        xr.parse(new InputSource(entity.getContent()));

    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        entity.consumeContent();
    }
    return result;
}

From source file:com.badugi.game.logic.model.utils.common.XmlUtils.java

/**
 * Retrieve the text for a specific element (when we know there is only
 * one).//w  ww .  j  ava  2 s  .  c  om
 *
 * @param xmlAsString the xml response
 * @param element     the element to look for
 * @return the text value of the element.
 */
public static String getTextForElement(final String xmlAsString, final String element) {
    final XMLReader reader = getXmlReader();
    final StringBuilder builder = new StringBuilder();

    final DefaultHandler handler = new DefaultHandler() {

        private boolean foundElement = false;

        public void startElement(final String uri, final String localName, final String qName,
                final Attributes attributes) throws SAXException {
            if (localName.equals(element)) {
                this.foundElement = true;
            }
        }

        public void endElement(final String uri, final String localName, final String qName)
                throws SAXException {
            if (localName.equals(element)) {
                this.foundElement = false;
            }
        }

        public void characters(char[] ch, int start, int length) throws SAXException {
            if (this.foundElement) {
                builder.append(ch, start, length);
            }
        }
    };

    reader.setContentHandler(handler);
    reader.setErrorHandler(handler);

    try {
        reader.parse(new InputSource(new StringReader(xmlAsString)));
    } catch (final Exception e) {
        LOG.error(e, e);
        return null;
    }

    return builder.toString();
}

From source file:com.inferiorhumanorgans.WayToGo.Agency.BART.Station.StationTask.java

@Override
protected Void doInBackground(BARTAgency... someAgencies) {
    Assert.assertEquals(1, someAgencies.length);
    super.doInBackground(someAgencies);

    Log.i(LOG_NAME, "Trying to get BART station list.");

    InputStream content = null;/* w  w w.j a va2  s  .c  o  m*/
    ClientConnectionManager connman = new ThreadSafeClientConnManager(params, registry);
    DefaultHttpClient hc = new DefaultHttpClient(connman, params);

    Log.i(LOG_NAME, "Fetching basic station info from: " + BART_URL + BARTAgency.API_KEY);
    HttpGet getRequest = new HttpGet(BART_URL + BARTAgency.API_KEY);
    try {
        content = hc.execute(getRequest).getEntity().getContent();
    } catch (ClientProtocolException ex) {
        Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex);
    }
    Log.i(LOG_NAME, "Put the station list in the background.");

    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        XMLReader xr = sp.getXMLReader();

        xr.setContentHandler(dataHandler);

        xr.parse(new InputSource(content));

    } catch (ParserConfigurationException pce) {
        Log.e(LOG_NAME + " SAX XML", "sax parse error", pce);
    } catch (AbortXMLParsingException abrt) {
        Log.i(LOG_NAME + " AsyncXML", "Cancelled!!!!!");
        return null; // Pass on some exception to the caller?
    } catch (SAXException se) {
        Log.e(LOG_NAME + " SAX XML", "sax error", se);
    } catch (IOException ioe) {
        Log.e(LOG_NAME + " SAX XML", "sax parse io error", ioe);
    }
    Log.i(LOG_NAME + " SAX XML", "Done parsing BART station XML");

    final DetailXMLHandler detailDataHandler = new DetailXMLHandler(this);

    for (String aStationTag : theStations.keySet()) {
        getRequest = new HttpGet(BART_DETAIL_URL + BARTAgency.API_KEY + "&orig=" + aStationTag);
        try {
            content = hc.execute(getRequest).getEntity().getContent();
        } catch (ClientProtocolException ex) {
            Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex);
        }
        Log.i(LOG_NAME, "Put the station detail for " + aStationTag + " in the background.");

        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();

            XMLReader xr = sp.getXMLReader();

            xr.setContentHandler(detailDataHandler);

            xr.parse(new InputSource(content));

        } catch (ParserConfigurationException pce) {
            Log.e(LOG_NAME + " SAX XML", "sax parse error", pce);
        } catch (AbortXMLParsingException abrt) {
            Log.i(LOG_NAME + " AsyncXML", "Cancelled!!!!!");
        } catch (SAXException se) {
            Log.e(LOG_NAME + " SAX XML", "sax error", se);
        } catch (IOException ioe) {
            Log.e(LOG_NAME + " SAX XML", "sax parse io error", ioe);
        }
        Log.i(LOG_NAME + " SAX XML", "Done parsing BART station XML");
    }

    return null;
}

From source file:com.bradmcevoy.http.webdav.DefaultPropFindRequestFieldParser.java

@Override
public PropertiesRequest getRequestedFields(InputStream in) {
    try {//from  w w  w .  j  av a  2 s .c  o m
        final Set<QName> set = new LinkedHashSet<QName>();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        StreamUtils.readTo(in, bout, false, true);
        byte[] arr = bout.toByteArray();
        if (arr.length > 1) {
            ByteArrayInputStream bin = new ByteArrayInputStream(arr);
            XMLReader reader = XMLReaderFactory.createXMLReader();
            PropFindSaxHandler handler = new PropFindSaxHandler();
            reader.setContentHandler(handler);
            try {
                reader.parse(new InputSource(bin));
                if (handler.isAllProp()) {
                    return new PropertiesRequest();
                } else {
                    set.addAll(handler.getAttributes().keySet());
                }
            } catch (IOException e) {
                log.warn("exception parsing request body", e);
                // ignore
            } catch (SAXException e) {
                log.warn("exception parsing request body", e);
                // ignore
            }
        }
        return PropertiesRequest.toProperties(set);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.edgenius.wiki.ext.textnut.NutParser.java

public Map<String, File> parseBPlist(InputStream bs) {

    try {/*from w  w  w  . ja  v a2  s  . c o  m*/
        NSObject obj = BinaryPropertyListParser.parse(bs);

        //parse BPList
        BPListParaserHandler handler = new BPListParaserHandler(new File(FileUtil.createTempDirectory("_nut")));
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setContentHandler(handler);

        //parse
        reader.parse(new org.xml.sax.InputSource(new StringReader(obj.toXML())));

        //all files - main HTML file key is "MAIN_RESOURCE_URL"
        return handler.getFiles();
    } catch (UnsupportedEncodingException e) {
        log.error("Unsupport encoding for BPList", e);
    } catch (Exception e) {
        log.error("Parase BPList error.", e);
    }
    return null;
}

From source file:net.ontopia.topicmaps.db2tm.RelationMapping.java

public static RelationMapping read(InputStream istream, File basedir) throws IOException {
    // Create new parser object
    XMLReader parser;
    try {/*from  w w  w . ja  va 2 s  .c  om*/
        parser = new DefaultXMLReaderFactory().createXMLReader();
    } catch (SAXException e) {
        throw new IOException("Problems occurred when creating SAX2 XMLReader: " + e.getMessage());
    }

    // Create content handler
    RelationMapping mapping = new RelationMapping();
    mapping.setBaseDirectory(basedir);
    ContentHandler vhandler = new ValidatingContentHandler(mapping, getRelaxNGSchema(), true);
    parser.setContentHandler(vhandler);

    try {
        // Parse input source
        parser.parse(new InputSource(istream));
    } catch (FileNotFoundException e) {
        log.error("Resource not found: {}", e.getMessage());
        throw e;
    } catch (SAXParseException e) {
        throw new OntopiaRuntimeException("XML parsing problem: " + e.toString() + " at: " + e.getSystemId()
                + ":" + e.getLineNumber() + ":" + e.getColumnNumber(), e);
    } catch (SAXException e) {
        if (e.getException() instanceof IOException)
            throw (IOException) e.getException();
        throw new OntopiaRuntimeException(e);
    }

    // Compile mapping
    mapping.compile();

    return mapping;
}

From source file:com.granule.json.utils.XML.java

/**
 * Method to do the transform from an XML input stream to a JSON stream.
 * Neither input nor output streams are closed.  Closure is left up to the caller.
 *
 * @param XMLStream The XML stream to convert to JSON
 * @param JSONStream The stream to write out JSON to.  The contents written to this stream are always in UTF-8 format.
 * @param verbose Flag to denote whether or not to render the JSON text in verbose (indented easy to read), or compact (not so easy to read, but smaller), format.
 *
 * @throws SAXException Thrown if a parse error occurs.
 * @throws IOException Thrown if an IO error occurs.
 *//* www. j  a va2s  .c om*/
public static void toJson(InputStream XMLStream, OutputStream JSONStream, boolean verbose)
        throws SAXException, IOException {
    if (logger.isLoggable(Level.FINER)) {
        logger.entering(className, "toJson(InputStream, OutputStream)");
    }

    if (XMLStream == null) {
        throw new NullPointerException("XMLStream cannot be null");
    } else if (JSONStream == null) {
        throw new NullPointerException("JSONStream cannot be null");
    } else {

        if (logger.isLoggable(Level.FINEST)) {
            logger.logp(Level.FINEST, className, "transform",
                    "Fetching a SAX parser for use with JSONSAXHandler");
        }

        try {
            /**
             * Get a parser.
             */
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            SAXParser sParser = factory.newSAXParser();
            XMLReader parser = sParser.getXMLReader();
            JSONSAXHandler jsonHandler = new JSONSAXHandler(JSONStream, verbose);
            parser.setContentHandler(jsonHandler);
            parser.setErrorHandler(jsonHandler);
            InputSource source = new InputSource(new BufferedInputStream(XMLStream));

            if (logger.isLoggable(Level.FINEST)) {
                logger.logp(Level.FINEST, className, "transform", "Parsing the XML content to JSON");
            }

            /** 
             * Parse it.
             */
            source.setEncoding("UTF-8");
            parser.parse(source);
            jsonHandler.flushBuffer();
        } catch (javax.xml.parsers.ParserConfigurationException pce) {
            throw new SAXException("Could not get a parser: " + pce.toString());
        }
    }

    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(className, "toJson(InputStream, OutputStream)");
    }
}

From source file:com.joshdrummond.webpasswordsafe.android.GetCurrentPassword.java

private String parseResponse(String responseSOAP) {
    String response = "";
    try {/*ww  w. j  av  a2s.  com*/
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        GetCurrentPasswordHandler handler = new GetCurrentPasswordHandler();
        xr.setContentHandler(handler);
        xr.parse(new InputSource(new StringReader(responseSOAP)));
        response = handler.getParsedData();
    } catch (Exception e) {
        response = "ERROR parsing: " + Arrays.deepToString(e.getStackTrace());
    }
    return response;
}