Example usage for javax.xml.parsers SAXParserFactory newInstance

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

Introduction

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

Prototype


public static SAXParserFactory newInstance() 

Source Link

Document

Obtain a new instance of a SAXParserFactory .

Usage

From source file:com.git.original.common.config.XMLFileConfigDocument.java

protected ConfigNode doLoad(String configFilePath) throws Exception {
    InputStream in = null;//from  w ww.j  a v a 2  s .  c  om
    try {
        File confFile = new File(configFilePath);
        if (!confFile.isAbsolute()) {
            confFile = new File(this.getHmailHome(), configFilePath);
        }
        if (!confFile.exists()) {
            throw new FileNotFoundException("path:" + confFile);
        }

        String currentDigest = confFile.lastModified() + ";" + confFile.length();
        if (currentDigest.equals(this.configFileDigest)) {
            // ??, ?
            return null;
        }

        in = new FileInputStream(confFile);

        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        NodeBuilder nb = new NodeBuilder();
        parser.parse(in, nb);
        ConfigNode result = nb.getRootNode();

        if (result != null) {
            try {
                this.dbVersion = result.getAttribute(CONF_DOC_ATTRIBUTE_DB_VERSION);
            } catch (Exception ex) {
                this.dbVersion = null;
            }

            try {
                String str = result.getAttribute(CONF_DOC_ATTRIBUTE_IGNORE_DB);
                if (StringUtils.isEmpty(str)) {
                    this.ignoreDb = false;
                } else {
                    this.ignoreDb = Boolean.parseBoolean(str);
                }
            } catch (Exception ex) {
                this.ignoreDb = false;
            }

            try {
                String tmp = result.getAttribute(CONF_DOC_ATTRIBUTE_SCAN_PERIOD);
                if (StringUtils.isEmpty(tmp)) {
                    this.scanMillis = null;
                } else {
                    this.scanMillis = ConfigNode.textToNumericMillis(tmp.trim());
                }
            } catch (Exception ex) {
                this.scanMillis = null;
            }
        }

        LOG.debug("Load config from local dir success, file:{}", configFilePath);
        return result;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // ignore exception
            }
        }
    }
}

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

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

    try {//from ww w  . j a  v a2 s.com
        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:com.sshtools.daemon.configuration.PlatformConfiguration.java

/**
 *
 *
 * @param in//from   w w  w. jav  a  2s. c om
 *
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws IOException
 */
public void reload(InputStream in) throws SAXException, ParserConfigurationException, IOException {
    SAXParserFactory saxFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxFactory.newSAXParser();
    saxParser.parse(in, new PlatformConfigurationSAXHandler());
}

From source file:eu.project.ttc.test.unit.TestUtil.java

public static String getTeiTxt(String filename)
        throws ParserConfigurationException, SAXException, IOException, FileNotFoundException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);/*from w w  w . ja  v a  2s  .co  m*/
    spf.setValidating(false);
    spf.setFeature("http://xml.org/sax/features/namespaces", true);
    spf.setFeature("http://xml.org/sax/features/validation", false);
    spf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    SAXParser saxParser = spf.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    TeiToTxtSaxHandler handler = new TeiToTxtSaxHandler();
    xmlReader.setContentHandler(handler);
    xmlReader.parse(new InputSource(TestUtil.getInputStream(filename)));
    String text = handler.getText();
    return text;
}

From source file:net.sf.ehcache.config.Configurator.java

/**
 * Configures a bean from an XML file./*from   w  w  w. java  2s.  c o  m*/
 */
public void configure(final Object bean, final File file) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Configuring ehcache from file: " + file.toString());
    }
    final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    final BeanHandler handler = new BeanHandler(bean);
    parser.parse(file, handler);
}

From source file:mcp.tools.nmap.parser.NmapXmlParser.java

public static void parse(File xmlResultsFile, String scanDescription, String commandLine) {
    Pattern endTimePattern = Pattern.compile("<runstats><finished time=\"(\\d+)");
    String xmlResults;//from  ww w.  ja  va 2  s .c o  m
    try {
        xmlResults = FileUtils.readFileToString(xmlResultsFile);
    } catch (IOException e) {
        logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': "
                + e.getLocalizedMessage(), e);
        return;
    }

    Matcher m = endTimePattern.matcher(xmlResults);
    Instant scanTime = null;
    if (m.find()) {
        int t;
        try {
            t = Integer.parseInt(m.group(1));
            scanTime = Instant.ofEpochSecond(t);
        } catch (NumberFormatException e) {

        }
    }

    if (scanTime == null) {
        logger.debug("Failed to find scan completion time in nmap results. Using current time.");
        scanTime = Instant.now();
    }
    String path;
    try {
        path = xmlResultsFile.getCanonicalPath();
    } catch (IOException e1) {
        logger.debug("Why did the canonical path fail?");
        path = xmlResultsFile.getAbsolutePath();
    }

    NmapScanSource source = new NmapScanSourceImpl(path, scanDescription, commandLine);

    NMapXmlHandler nmxh = new NMapXmlHandler(scanTime, source);
    SAXParserFactory spf = SAXParserFactory.newInstance();

    SAXParser sp;
    try {
        sp = spf.newSAXParser();
    } catch (ParserConfigurationException e) {
        throw new UnexpectedException("This shouldn't have happened: " + e.getLocalizedMessage(), e);
    } catch (SAXException e) {
        throw new UnexpectedException("This shouldn't have happened: " + e.getLocalizedMessage(), e);
    }

    try {
        sp.parse(xmlResultsFile, nmxh);
    } catch (SAXException e) {
        logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': "
                + e.getLocalizedMessage(), e);
        return;
    } catch (IOException e) {
        logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': "
                + e.getLocalizedMessage(), e);
        return;
    }
}

From source file:importer.handler.post.annotate.HTMLConverter.java

/**
 * Turn XML note content for Harpur to HTML
 * @param xml the xml note// www . j  av a 2 s .  c o  m
 * @param config the JSON config to control the conversion
 * @return a HTML string
 */
String convert(String xml) throws HTMLException {
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        HTMLConverter conv = new HTMLConverter(patterns);
        spf.setNamespaceAware(true);
        SAXParser parser = spf.newSAXParser();
        XMLReader xmlReader = parser.getXMLReader();
        xmlReader.setContentHandler(conv);
        xmlReader.setErrorHandler(new MyErrorHandler(System.err));
        CharArrayReader car = new CharArrayReader(xml.toCharArray());
        InputSource input = new InputSource(car);
        xmlReader.parse(input);
        return conv.body.toString();
    } catch (Exception e) {
        throw new HTMLException(e);
    }
}

From source file:fr.ybo.transportsbordeaux.tbcapi.Keolis.java

/**
 * @param <ObjetKeolis> type d'objet Keolis.
 * @param url           url.//w w  w.j a  va  2  s . c  om
 * @param handler       handler.
 * @return liste d'objets Keolis.
 * @throws TbcErreurReseaux en cas d'erreur rseau.
 */
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);
    List<ObjetKeolis> answer;
    try {
        HttpResponse reponse = httpClient.execute(httpPost);
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        if (reponse == null || reponse.getEntity() == null) {
            throw new ErreurReseau("Erreur lors de la rcupration de la rponse http");
        }
        reponse.getEntity().writeTo(ostream);
        String contenu = new String(ostream.toByteArray(), "ISO-8859-1");
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        parser.parse(new ByteArrayInputStream(contenu.getBytes("UTF-8")), handler);
        answer = handler.getObjets();
    } 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) {
        throw new ErreurReseau("Erreur dans la rponse donnes par Keolis.");
    }
    long elapsedTime = System.nanoTime() / 1000 - startTime;
    LOG_YBO.debug("Rponse de Keolis en " + elapsedTime + "s");
    return answer;
}

From source file:egat.cli.neresponse.NEResponseCommandHandler.java

protected void processSymmetricGame(MutableSymmetricGame game) throws CommandProcessingException {

    InputStream inputStream = null;
    try {//  w w w  .  jav a 2 s. c  o m

        inputStream = new FileInputStream(profilePath);

    } catch (FileNotFoundException e) {

        throw new CommandProcessingException(e);

    }

    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();

        SAXParser parser = factory.newSAXParser();

        StrategyHandler handler = new StrategyHandler();

        parser.parse(inputStream, handler);

        Strategy strategy = handler.getStrategy();

        findNEResponse(strategy, game);
    } catch (NonexistentPayoffException e) {
        System.err.println(String.format("Could not calculate regret. %s", e.getMessage()));
    } catch (ParserConfigurationException e) {
        throw new CommandProcessingException(e);
    } catch (SAXException e) {
        throw new CommandProcessingException(e);
    } catch (IOException e) {
        throw new CommandProcessingException(e);
    }
}