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.ibm.jaql.lang.expr.xml.XmlToJsonFn.java

@Override
public JsonValue eval(Context context) throws Exception {
    if (parser == null) {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        parser = factory.newSAXParser().getXMLReader();
        handler = new XmlToJsonHandler2();
        parser.setContentHandler(handler);
    }//from w ww.j  a  v  a2  s .c o  m

    JsonString s = (JsonString) exprs[0].eval(context);
    if (s == null) {
        return null;
    }
    parser.parse(new InputSource(new StringReader(s.toString())));
    return handler.result;
}

From source file:eionet.cr.util.xml.XmlAnalysis.java

/**
 *
 * @param inputStream//w  w  w  .ja  va 2  s. c  o m
 * @return
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws GDEMException
 * @throws SAXException
 * @throws IOException
 */
public void parse(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException {

    // set up the parser and reader
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    SAXParser parser = parserFactory.newSAXParser();
    XMLReader reader = parser.getXMLReader();

    // turn off validation against schema or dtd (we only need the document to be well-formed XML)
    parserFactory.setValidating(false);
    reader.setFeature("http://xml.org/sax/features/validation", false);
    reader.setFeature("http://apache.org/xml/features/validation/schema", false);
    reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    reader.setFeature("http://xml.org/sax/features/namespaces", true);

    // turn on dtd handling
    doctypeReader = new SAXDoctypeReader();
    try {
        parser.setProperty("http://xml.org/sax/properties/lexical-handler", doctypeReader);
    } catch (SAXNotRecognizedException e) {
        logger.warn("Installed XML parser does not provide lexical events", e);
    } catch (SAXNotSupportedException e) {
        logger.warn("Cannot turn on comment processing here", e);
    }

    // set the handler and do the parsing
    handler = new Handler();
    reader.setContentHandler(handler);
    try {
        reader.parse(new InputSource(inputStream));
    } catch (SAXException e) {
        Exception ee = e.getException();
        if (ee == null || !(ee instanceof CRException))
            throw e;
    }
}

From source file:eu.apenet.dpt.utils.util.Ead2EdmInformation.java

private void determineDaoInformation(File fileToRead)
        throws IOException, SAXException, ParserConfigurationException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();
    EadContentHandler myContentHandler = new EadContentHandler();
    xr.setContentHandler(myContentHandler);
    xr.parse(new InputSource(new InputStreamReader(new BOMInputStream(new FileInputStream(fileToRead)))));

    if (this.roleType == null) {
        this.roleType = "UNSPECIFIED";
    }/*from   w  w w.j a  v  a 2  s. c o  m*/
}

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

private void parse(String fileName, Locale locale) {
    //get a factory
    localizedHeading = "berschrift";//LocalizeUtil.getLocalizedTextFromApplicationResources(HEADING_KEY, locale);
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {// w  ww  . ja  v a 2  s.co  m
        //get a new instance of parser
        SAXParser sp = spf.newSAXParser();
        //spf.setValidating(true);
        XMLReader xmlReader = sp.getXMLReader();
        xmlReader.setErrorHandler(new MyErrorHandler(System.err));
        xmlReader.setContentHandler(this);
        //parse the file and also register this class for call backs
        //InputSource is=new InputSource(new StringReader(xml));
        xmlReader.parse(convertToFileURL(fileName));
    } catch (SAXException se) {
        LOGGER.error("Parsing the file " + fileName + " failed with " + se.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(se));
    } catch (ParserConfigurationException pce) {
        LOGGER.error("Parsing the file " + fileName + " failed with " + pce.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.error(ExceptionUtils.getStackTrace(pce));
        }
    } catch (IOException ie) {
        LOGGER.error("Reading the file " + fileName + " failed with " + ie.getMessage());
        LOGGER.error(ExceptionUtils.getStackTrace(ie));
    }

}

From source file:fedora.server.security.servletfilters.xmluserfile.ParserXmlUserfile.java

public ParserXmlUserfile(InputStream xmlStream) throws IOException {
    log.debug(this.getClass().getName() + ".init<> " + " begin");

    m_xmlStream = xmlStream;//from ww w .  j  av  a2s .  c  o m
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        log.debug(this.getClass().getName() + ".init<> " + " after newInstance");
        spf.setNamespaceAware(true);
        log.debug(this.getClass().getName() + ".init<> " + " after setNamespaceAware");
        m_parser = spf.newSAXParser();
        log.debug(this.getClass().getName() + ".init<> " + " after newSAXParser");
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException("Error getting XML parser: " + e.getMessage());
    } catch (Throwable t) {
        log.fatal(this.getClass().getName() + ".init<> " + " caught me throwable");
        t.printStackTrace();
        log.fatal(this.getClass().getName() + ".populateCacheElement() " + t);
        log.fatal(this.getClass().getName() + ".populateCacheElement() " + t.getMessage() + " "
                + (t.getCause() == null ? "" : t.getCause().getMessage()));
    }
}

From source file:fr.paris.lutece.plugins.dila.modules.solr.utils.parsers.DilaSolrPublicParser.java

/**
 * Initializes and launches the parsing of the public cards (public
 * constructor)//from   ww  w  .  j a v  a2 s . co  m
 */
public DilaSolrPublicParser() {
    // Gets the list of CDC index keys
    String strIndexKeys = AppPropertiesService
            .getProperty(PROPERTY_INDEXING_FRAGMENT + PROPERTY_LIST_INDEX_KEYS_FRAGMENT);

    // Initializes the Solr Item list
    _listSolrItems = new ArrayList<SolrItem>();

    // Initializes the indexing type
    _strType = AppPropertiesService.getProperty(PROPERTY_INDEXING_TYPE);

    // Initializes the site
    _strSite = AppPropertiesService.getProperty(PROPERTY_SITE);

    // Initializes the prod url
    _strProdUrl = SolrIndexerService.getBaseUrl();

    try {
        // Initializes the SAX parser
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();

        // Splits the list of CDC index keys
        String[] splitKeys = strIndexKeys.split(",");

        for (int i = 0; i < splitKeys.length; i++) {
            // Gets the XML index file path
            String strXmlDirectory = AppPropertiesService
                    .getProperty(splitKeys[i] + STRING_POINT + PROPERTY_INDEXING_XML_BASE_VAR);
            File xmlPath = new File(strXmlDirectory);
            // Launches the parsing of all files in this directory
            parseAllPublicCards(xmlPath, parser);
        }
    } catch (ParserConfigurationException e) {
        AppLogService.error(e.getMessage(), e);
    } catch (SAXException e) {
        AppLogService.error(e.getMessage(), e);
    }
}

From source file:net.sf.jabref.importer.fileformat.BibTeXMLImporter.java

@Override
public ParserResult importDatabase(BufferedReader reader) throws IOException {
    Objects.requireNonNull(reader);

    List<BibEntry> bibItems = new ArrayList<>();

    // Obtain a factory object for creating SAX parsers
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    // Configure the factory object to specify attributes of the parsers it
    // creates/* w  w w.java 2s.com*/
    // parserFactory.setValidating(true);
    parserFactory.setNamespaceAware(true);
    // Now create a SAXParser object

    try {
        SAXParser parser = parserFactory.newSAXParser(); //May throw exceptions
        BibTeXMLHandler handler = new BibTeXMLHandler();
        // Start the parser. It reads the file and calls methods of the handler.
        parser.parse(new InputSource(reader), handler);
        // When you're done, report the results stored by your handler object
        bibItems.addAll(handler.getItems());

    } catch (javax.xml.parsers.ParserConfigurationException e) {
        LOGGER.error("Error with XML parser configuration", e);
        return ParserResult.fromErrorMessage(e.getLocalizedMessage());
    } catch (org.xml.sax.SAXException e) {
        LOGGER.error("Error during XML parsing", e);
        return ParserResult.fromErrorMessage(e.getLocalizedMessage());
    } catch (IOException e) {
        LOGGER.error("Error during file import", e);
        return ParserResult.fromErrorMessage(e.getLocalizedMessage());
    }
    return new ParserResult(bibItems);
}

From source file:com.sshtools.daemon.configuration.PlatformConfiguration.java

/**
 *
 *
 * @param in/*from   ww w  .  j  a v  a 2s . co m*/
 *
 * @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:com.googlecode.l10nmavenplugin.validators.property.HtmlValidator.java

/**
 * Initialize using XML schema//from  w ww  .ja v  a2 s . c o  m
 * 
 * @param xhtmlSchema
 * @param logger
 */
public HtmlValidator(File xhtmlSchema, L10nValidatorLogger logger, L10nValidator<Property> spellCheckValidator,
        String[] htmlKeys, Formatter formattingParametersExtractor,
        InnerResourcesFormatter innerResourceFormatter) {
    super(logger, htmlKeys);
    this.spellCheckValidator = spellCheckValidator;
    this.formattingParametersExtractor = formattingParametersExtractor;
    this.innerResourceFormatter = innerResourceFormatter;

    try {
        // SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        // Need to use XERCES so that XHTML5 schema passes validation
        SchemaFactory factory = new XMLSchemaFactory();
        factory.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING, false);

        Schema schema = null;
        if (xhtmlSchema.exists()) {
            // Load custom schema
            schema = factory.newSchema(xhtmlSchema);
        } else {
            // Try to load a pre-defined schemas from classpath
            URL schemaURL = this.getClass().getClassLoader().getResource(xhtmlSchema.getName());

            if (schemaURL == null) {
                logger.getLogger()
                        .error("Could not load XML schema from file <" + xhtmlSchema.getAbsolutePath()
                                + "> and <" + xhtmlSchema.getName() + "> is not a default schema either ("
                                + Arrays.toString(PREDEFINED_XSD) + "), thus defaulting to "
                                + XHTML1_TRANSITIONAL.getName());
                schemaURL = this.getClass().getClassLoader().getResource(XHTML1_TRANSITIONAL.getName());
            }
            schema = factory.newSchema(schemaURL);
        }
        xhtmlValidator = schema.newValidator();

        // Initialize SAX parser
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        parser = saxParserFactory.newSAXParser();

    } catch (SAXException e) {
        logger.getLogger().error("Could not initialize HtmlValidator", e);

    } catch (ParserConfigurationException e) {
        logger.getLogger().error("Could not initialize HtmlValidator", e);
    }
}

From source file:com.typhoon.newsreader.engine.ChannelRefresh.java

public long syncDB(Handler h, long id, String rssurl) throws Exception {
    mHandler = h;//from   w w w  .  j av  a  2  s.c o  m
    mID = id;
    mRSSURL = rssurl;

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

    xr.setContentHandler(this);
    xr.setErrorHandler(this);

    URL url = new URL(mRSSURL);

    URLConnection c = url.openConnection();
    c.setRequestProperty("User-Agent", "Android/m3-rc37a");
    xr.parse(new InputSource(c.getInputStream()));

    return mID;
}