Example usage for javax.xml.parsers SAXParser parse

List of usage examples for javax.xml.parsers SAXParser parse

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParser parse.

Prototype

public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException 

Source Link

Document

Parse the content given org.xml.sax.InputSource as XML using the specified org.xml.sax.helpers.DefaultHandler .

Usage

From source file:de.mpg.escidoc.services.edoc.PubManImport.java

public void run() {

    XmlTransforming xmlTransforming = new XmlTransformingBean();

    try {//from w ww  . ja  va2  s.  c  om
        File file = new File(fileName);
        if (!file.exists()) {
            System.err.println("File \"" + file.getAbsolutePath() + "\" not found!");
            System.exit(1);
        }

        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        ImportHandler importHandler = new ImportHandler();
        parser.parse(new InputSource(new InputStreamReader(new FileInputStream(file))), importHandler);

        List<String> itemXmls = importHandler.getItems();

        for (String itemXml : itemXmls) {
            validateItem(itemXml);
            ItemVO itemVO = xmlTransforming.transformToItem(itemXml);
            System.out.println(itemVO);
        }

        // System.exit(0);

        for (String itemXml : itemXmls) {
            importItem(itemXml);
            //sleep(5000);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:io.onedecision.engine.decisions.model.dmn.validators.SchemaValidator.java

public void validate(InputStream obj, Errors errors) {
    InputStream is = (InputStream) obj;

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(new LocalResourceResolver());

    try {/*w  w  w  .  j  av  a  2s  .  c om*/
        schemaFactory.newSchema(new StreamSource(getResourceAsStreamWrapper("schema/dmn.xsd")));
    } catch (SAXException e1) {
        errors.reject("Cannot find / read schema", "Exception: " + e1.getMessage());
    }

    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    // parserFactory.setValidating(true);
    parserFactory.setNamespaceAware(true);
    // parserFactory.setSchema(schema);

    SAXParser parser = null;
    try {
        parser = parserFactory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setErrorHandler(this);

        try {
            parser.parse(new InputSource(is), (DefaultHandler) null);
        } catch (Exception e) {
            String msg = "Schema validation failed";
            LOGGER.error(msg, e);
            errors.reject(msg, "Exception: " + e.getMessage());
        }
        if (this.errors.size() > 0) {
            errors.reject("Schema validation failed", this.errors.toString());
        }
    } catch (ParserConfigurationException e1) {
        errors.reject("Cannot create parser", "Exception: " + e1.getMessage());
    } catch (SAXException e1) {
        errors.reject("Parser cannot be created", "Exception: " + e1.getMessage());
    }
}

From source file:com.vionto.vithesaurus.wikipedia.CommonsAudioDumper.java

private void run(InputStream is) throws IOException, SAXException, ParserConfigurationException {
    CommonsPageHandler handler = new CommonsPageHandler();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    saxParser.getXMLReader().setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",
            false);/*from   w  ww . j  a va2s. c o m*/
    System.out.println("SET NAMES utf8;");
    saxParser.parse(is, handler);
    System.err.println("Exported: " + handler.exported);
    System.err.println("Skipped: " + handler.skipped);
    System.err.println("Skipped " + handler.noLicense + " because of missing/undetected license");
}

From source file:com.zergiu.tvman.shows.search.AddShowFlowService.java

/**
 * @return/*w  ww  . j  a  va 2s. c om*/
 */
private void fillLanguagesTable() {
    log.debug("going to go to TVDB.com to get a list of languages");
    List<TVDBLanguage> languages = new ArrayList<TVDBLanguage>();
    URL url = null;
    try {
        url = new URL("http://www.thetvdb.com/api/CAC7D918A2D6A58F/languages.xml");
        InputStream in = url.openStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        SearchLanguagesHandler handler = new SearchLanguagesHandler(languages);
        parser.parse(in, handler);
        in.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
    tvdbLanguageService.addLanguages(languages);
}

From source file:fr.lemet.application.keolis.Keolis.java

/**
 * @param <ObjetKeolis> type d'objet Keolis.
 * @param url           url./*from   ww  w  .  jav a2 s . c  om*/
 * @param handler       handler.
 * @return liste d'objets Keolis.
 * @throws fr.lemet.transportscommun.util.ErreurReseau    en cas d'erreur rseau.
 * @throws KeolisException en cas d'erreur lors de l'appel aux API Keolis.
 */
@SuppressWarnings("unchecked")
private <ObjetKeolis> List<ObjetKeolis> appelKeolis(String url, KeolisHandler<ObjetKeolis> handler)
        throws ErreurReseau {
    LOG_YBO.debug("Appel d'une API Keolis sur l'url '" + url + '\'');
    long startTime = System.nanoTime() / 1000;
    HttpClient httpClient = HttpUtils.getHttpClient();
    HttpUriRequest httpPost = new HttpPost(url);
    Answer<?> answer;
    try {
        HttpResponse reponse = httpClient.execute(httpPost);
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        reponse.getEntity().writeTo(ostream);
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        parser.parse(new ByteArrayInputStream(ostream.toByteArray()), handler);
        answer = handler.getAnswer();
    } catch (IOException socketException) {
        throw new ErreurReseau(socketException);
    } catch (SAXException saxException) {
        throw new ErreurReseau(saxException);
    } catch (ParserConfigurationException exception) {
        throw new KeolisException("Erreur lors de l'appel  l'API keolis", exception);
    }
    if (answer == null || answer.getStatus() == null || !"0".equals(answer.getStatus().getCode())) {
        throw new ErreurReseau();
    }
    long elapsedTime = System.nanoTime() / 1000 - startTime;
    LOG_YBO.debug("Rponse de Keolis en " + elapsedTime + "s");
    return (List<ObjetKeolis>) answer.getData();
}

From source file:jp.gr.java_conf.petit_lycee.subsonico.MethodConstants.java

SubsonicResponse parseResponseXML(InputStream is)
        throws SubsonicException, IOException, SAXException, ParserConfigurationException {

    SubsonicXMLHandler handler = new SubsonicXMLHandler();
    SAXParserFactory factory = SAXParserFactory.newInstance();

    SAXParser parser = factory.newSAXParser();
    parser.parse(is, handler);
    if (handler.isError()) {
        throw handler.getException();
    }//ww w .  j  a v  a2 s  .c o  m
    return handler.getResponse();
}

From source file:org.qucosa.camel.component.fcrepo3.Fcrepo3APIAccess.java

private ValueCollector parseReturningValueCollector(HttpResponse response)
        throws ParserConfigurationException, SAXException, IOException {
    SAXParser saxParser = getOrCreateSaxParser();
    ValueCollector valueCollector = new ValueCollector("pid", "token");
    saxParser.parse(response.getEntity().getContent(), valueCollector);
    return valueCollector;
}

From source file:com.aurel.track.exchange.track.importer.ImporterDropdownParser.java

public SortedMap<String, List<ISerializableLabelBean>> parse(File xml, Map<Integer, Integer> fieldMatcher) {
    this.fieldMatcher = fieldMatcher;
    //get a factory
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {/*  w  w w  .ja va  2  s.c o  m*/
        //get a new instance of parser
        SAXParser sp = spf.newSAXParser();
        //parse the file and also register this class for call backs
        LOGGER.debug("Dropdown parser started...");
        sp.parse(xml, this);
        LOGGER.debug("Dropdown parser done");
        return externalDropdowns;
    } catch (SAXException se) {
        LOGGER.error(ExceptionUtils.getStackTrace(se));
    } catch (ParserConfigurationException pce) {
        LOGGER.error(ExceptionUtils.getStackTrace(pce));
    } catch (IOException ie) {
        LOGGER.error(ExceptionUtils.getStackTrace(ie));
    }
    return null;
}

From source file:net.sourceforge.fullsync.fs.connection.SyncFileBufferedConnection.java

protected void loadFromBuffer() throws IOException {
    File fsRoot = fs.getRoot();//ww  w .j  av  a2s.  c o  m
    File f = fsRoot.getChild(BUFFER_FILENAME);

    root = new AbstractBufferedFile(this, fsRoot, null, true, true);
    if ((null == f) || !f.exists() || f.isDirectory()) {
        if (isMonitoringFileSystem()) {
            updateFromFileSystem(root);
        }
        return;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream((int) f.getSize());
    try (InputStream in = new GZIPInputStream(f.getInputStream())) {
        int i;
        byte[] block = new byte[4096];
        while ((i = in.read(block)) > 0) {
            out.write(block, 0, i);
        }
    }
    try {
        SAXParser sax = SAXParserFactory.newInstance().newSAXParser();
        sax.parse(new ByteArrayInputStream(out.toByteArray()), new SyncFileDefaultHandler(this));
    } catch (SAXParseException spe) {
        StringBuilder sb = new StringBuilder(spe.toString());
        sb.append("\n Line number: " + spe.getLineNumber()); //$NON-NLS-1$
        sb.append("\n Column number: " + spe.getColumnNumber()); //$NON-NLS-1$
        sb.append("\n Public ID: " + spe.getPublicId()); //$NON-NLS-1$
        sb.append("\n System ID: " + spe.getSystemId() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        System.err.println(sb.toString());
    } catch (IOException | SAXException | ParserConfigurationException | FactoryConfigurationError e) {
        ExceptionHandler.reportException(e);
    }

    if (isMonitoringFileSystem()) {
        updateFromFileSystem(root);
    }
}

From source file:com.amalto.core.schema.validation.SkipAttributeDocumentBuilder.java

@Override
public Document parse(InputSource is) throws SAXException, IOException {
    SAXParser parser;
    try {/*w w  w . ja  va  2  s.  co m*/
        parser = getSaxParser();
    } catch (ParserConfigurationException e) {
        throw new SAXException(e);
    }
    try {
        Document document = newDocument();
        parser.parse(is, new SkipAttributeHandler(document, ignoreTalendNamespace));
        return document;
    } finally {
        parser.reset();
    }
}