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.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  . jav a 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:ensen.controler.DBpediaLookupClient.java

public String getOneResource(String query, String classes, int numberOfRes) throws Exception {

    HttpClient client = new HttpClient();
    // client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
    String query2 = URLEncoder.encode(query, "utf-8");
    HttpMethod method = new GetMethod(
            gatway + "QueryString=" + query2 + "&QueryClass=" + classes + "&MaxHits=" + numberOfRes);
    // method.setFollowRedirects(true);
    try {//w  w  w .  j  a  v  a 2 s.  c  o  m
        client.executeMethod(method);
        InputStream ins = method.getResponseBodyAsStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser sax = factory.newSAXParser();
        sax.parse(ins, this);
    } catch (HttpException he) {
        System.out.println("Http error connecting to lookup.dbpedia.org");
    } catch (IOException ioe) {
        System.out.println("Unable to connect to lookup.dbpedia.org");
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }
    method.releaseConnection();

    String resource = "";
    int num_results = Results.size();
    if (num_results > 0) {
        for (DBpediaLookupResModel res : Results) {
            resource = URLDecoder.decode(res.uri);
            /*
             * if (res.uri.contains("http://")) { Resource O =
             * model.createResource(res.uri); Property P =
             * model.createProperty("http://ensen.org/data#has-a"); Literal
             * O1 = model.createLiteral(res.label + ""); Literal O2 =
             * model.createLiteral(res.desc + ""); Property P1 =
             * model.createProperty
             * ("http://www.w3.org/2000/01/rdf-schema#label"); Property P2 =
             * model.createProperty(
             * "http://www.w3.org/1999/02/22-rdf-syntax-ns#description");
             * O.addProperty(P1, O1); O.addProperty(P2, O2);
             * 
             * for (String cat : res.cats) { Resource OO =
             * model.createResource(cat); Property PP =
             * model.createProperty("http://purl.org/dc/terms/subject");
             * O.addProperty(PP, OO); } for (String c : res.classes) {
             * Resource OO = model.createResource(c); Property PP =
             * model.createProperty
             * ("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
             * O.addProperty(PP, OO); } core.addProperty(P, O);
             * 
             * }
             */
        }
    }

    return resource;
}

From source file:ensen.controler.DBpediaLookupClient.java

public Model qetEntities(String query, String classes, int numberOfRes) throws Exception {

    HttpClient client = new HttpClient();
    // client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
    String query2 = URLEncoder.encode(query, "utf-8");
    HttpMethod method = new GetMethod(
            gatway + "QueryString=" + query2 + "&QueryClass=" + classes + "&MaxHits=" + numberOfRes);
    // method.setFollowRedirects(true);
    try {//from ww w  . ja  va  2 s .c o  m
        client.executeMethod(method);
        InputStream ins = method.getResponseBodyAsStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser sax = factory.newSAXParser();
        sax.parse(ins, this);
    } catch (HttpException he) {
        System.out.println("Http error connecting to lookup.dbpedia.org");
    } catch (IOException ioe) {
        System.out.println("Unable to connect to lookup.dbpedia.org");
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }
    method.releaseConnection();

    Model model = ModelFactory.createDefaultModel();
    Resource core = model.createResource("http://ensen.org/data#q-" + query2);

    int num_results = Results.size();
    if (num_results > 0) {
        for (DBpediaLookupResModel res : Results) {
            // System.out.println("URI: " + res.uri);
            if (res.uri.contains("http://")) {
                Resource O = model.createResource(res.uri);
                Property P = model.createProperty("http://ensen.org/data#has-a");
                Literal O1 = model.createLiteral(res.label + "");
                Literal O2 = model.createLiteral(res.desc + "");
                Property P1 = model.createProperty("http://www.w3.org/2000/01/rdf-schema#label");
                Property P2 = model.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#description");
                O.addProperty(P1, O1);
                O.addProperty(P2, O2);

                for (String cat : res.cats) {
                    Resource OO = model.createResource(cat);
                    Property PP = model.createProperty("http://purl.org/dc/terms/subject");
                    O.addProperty(PP, OO);
                }
                for (String c : res.classes) {
                    Resource OO = model.createResource(c);
                    Property PP = model.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
                    O.addProperty(PP, OO);
                }
                core.addProperty(P, O);
            }
        }
    }

    return model;
}

From source file:com.zazuko.blv.outbreak.tools.SparqlClient.java

List<Map<String, RDFTerm>> queryResultSet(final String query) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(endpoint);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("query", query));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);

    try {//from ww  w  .j a v a 2  s  . c om
        HttpEntity entity2 = response2.getEntity();
        InputStream in = entity2.getContent();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        final SparqlsResultsHandler sparqlsResultsHandler = new SparqlsResultsHandler();
        xmlReader.setContentHandler(sparqlsResultsHandler);
        xmlReader.parse(new InputSource(in));
        /*
         for (int ch = in.read(); ch != -1; ch = in.read()) {
         System.out.print((char)ch);
         }
         */
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
        return sparqlsResultsHandler.getResults();
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException ex) {
        throw new RuntimeException(ex);
    } finally {
        response2.close();
    }

}

From source file:net.sourceforge.fenixedu.utilTests.ParseMetadata.java

public Vector<Element> parseMetadata(String metadataFile) throws ParseException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setValidating(true);//ww w.  j  a  v  a2 s  .c  o  m
    try {
        SAXParser saxParser = spf.newSAXParser();
        XMLReader reader = saxParser.getXMLReader();
        reader.setContentHandler(this);
        reader.setErrorHandler(this);
        StringReader sr = new StringReader(metadataFile);
        InputSource input = new InputSource(sr);
        MetadataResolver resolver = new MetadataResolver();
        reader.setEntityResolver(resolver);
        reader.parse(input);
    } catch (Exception e) {
        throw new ParseException();
    }

    setMembers(vector);
    return vector;
}

From source file:com.aurel.track.admin.customize.category.filter.tree.io.TreeFilterParser.java

private void parse(String xml) {
    //get a factory
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {/*from  w  ww  .j a  va  2s.  co  m*/
        //get a new instance of parser
        SAXParser sp = spf.newSAXParser();
        //parse the file and also register this class for call backs
        InputSource is = new InputSource(new StringReader(xml));
        sp.parse(is, this);
    } catch (SAXException se) {
        LOGGER.warn("Parsing expression: " + xml + " failed with " + se.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(se));
        }
    } catch (ParserConfigurationException pce) {
        LOGGER.warn("Parsing expression: " + xml + " failed with " + pce.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(pce));
        }
    } catch (IOException ie) {
        LOGGER.warn("Reading expression: " + xml + " failed with " + ie.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(ie));
    }
}

From source file:MockFedoraIT.java

private void parseIrodsFile(IrodsIFileSystem module, String testPath) throws LowlevelStorageException {
    InputStream is = module.read(new File(testPath));
    // initialize sax for this parse
    try {//w w w.j a  va2  s . c  om
        SAXParserFactory spf = SAXParserFactory.newInstance();
        // spf.setValidating(false);
        // spf.setNamespaceAware(true);
        SAXParser parser = spf.newSAXParser();
        parser.parse(is, new DefaultHandler());
    } catch (Exception e) {
        throw new RuntimeException("Error with SAX parser", e);
    }
}

From source file:com.opensymphony.xwork.util.DomHelper.java

/**
 * Creates a W3C Document that remembers the location of each element in
 * the source file. The location of element nodes can then be retrieved
 * using the {@link #getLocationObject(Element)} method.
 *
 * @param inputSource the inputSource to read the document from
 * @param dtdMappings a map of DTD names and public ids
 *///from w  ww .j  av a 2  s.c o  m
public static Document parse(InputSource inputSource, Map dtdMappings) {
    SAXParserFactory factory = null;
    String parserProp = System.getProperty("xwork.saxParserFactory");
    if (parserProp != null) {
        try {
            Class clazz = ObjectFactory.getObjectFactory().getClassInstance(parserProp);
            factory = (SAXParserFactory) clazz.newInstance();
        } catch (ClassNotFoundException e) {
            LOG.error("Unable to load saxParserFactory set by system property 'xwork.saxParserFactory': "
                    + parserProp, e);
        } catch (Exception e) {
            LOG.error("Unable to load saxParserFactory set by system property 'xwork.saxParserFactory': "
                    + parserProp, e);
        }
    }

    if (factory == null) {
        factory = SAXParserFactory.newInstance();
    }

    factory.setValidating((dtdMappings != null));
    factory.setNamespaceAware(true);

    SAXParser parser = null;
    try {
        parser = factory.newSAXParser();
    } catch (Exception ex) {
        throw new XworkException("Unable to create SAX parser", ex);
    }

    DOMBuilder builder = new DOMBuilder();

    // Enhance the sax stream with location information
    ContentHandler locationHandler = new LocationAttributes.Pipe(builder);

    try {
        parser.parse(inputSource, new StartHandler(locationHandler, dtdMappings));
    } catch (Exception ex) {
        throw new XworkException(ex);
    }

    return builder.getDocument();
}

From source file:com.google.code.docbook4j.renderer.BaseRenderer.java

public InputStream render() throws Docbook4JException {

    assertNotNull(xmlResource, "Value of the xml source should be not null!");

    FileObject xsltResult = null;
    FileObject xmlSourceFileObject = null;
    FileObject xslSourceFileObject = null;
    FileObject userConfigXmlSourceFileObject = null;

    try {/*from w  w  w  . j a  va  2  s . c  om*/

        xmlSourceFileObject = FileObjectUtils.resolveFile(xmlResource);
        if (xslResource != null) {
            xslSourceFileObject = FileObjectUtils.resolveFile(xslResource);
        } else {
            xslSourceFileObject = getDefaultXslStylesheet();
        }

        if (userConfigXmlResource != null) {
            userConfigXmlSourceFileObject = FileObjectUtils.resolveFile(userConfigXmlResource);
        }

        SAXParserFactory factory = createParserFactory();
        final XMLReader reader = factory.newSAXParser().getXMLReader();

        EntityResolver resolver = new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {

                log.debug("Resolving file {}", systemId);

                FileObject inc = FileObjectUtils.resolveFile(systemId);
                return new InputSource(inc.getContent().getInputStream());
            }
        };

        // prepare xml sax source
        ExpressionEvaluatingXMLReader piReader = new ExpressionEvaluatingXMLReader(reader, vars);
        piReader.setEntityResolver(resolver);

        SAXSource source = new SAXSource(piReader,
                new InputSource(xmlSourceFileObject.getContent().getInputStream()));
        source.setSystemId(xmlSourceFileObject.getURL().toExternalForm());

        // prepare xslt result
        xsltResult = FileObjectUtils.resolveFile("tmp://" + UUID.randomUUID().toString());
        xsltResult.createFile();

        // create transofrmer and do transformation
        final Transformer transformer = createTransformer(xmlSourceFileObject, xslSourceFileObject);
        transformer.transform(source, new StreamResult(xsltResult.getContent().getOutputStream()));

        // do post processing
        FileObject target = postProcess(xmlSourceFileObject, xslSourceFileObject, xsltResult,
                userConfigXmlSourceFileObject);

        FileObjectUtils.closeFileObjectQuietly(xsltResult);
        FileObjectUtils.closeFileObjectQuietly(target);
        return target.getContent().getInputStream();

    } catch (FileSystemException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (SAXException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (ParserConfigurationException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (TransformerException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (IOException e) {
        throw new Docbook4JException("Error transofrming xml !", e);
    } finally {
        FileObjectUtils.closeFileObjectQuietly(xmlSourceFileObject);
        FileObjectUtils.closeFileObjectQuietly(xslSourceFileObject);
    }

}

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * @throws IOException/*w w  w .  ja  v  a 2s.c  o m*/
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private static void initializeSchemas() throws IOException, SAXException, ParserConfigurationException {
    File[] schemaFiles = ResourceUtil.getFilenamesInDirectory("xsd/", TestBase.class.getClassLoader());
    schemas = new HashMap<String, Schema>();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    for (File file : schemaFiles) {
        try {
            Schema schema = sf.newSchema(file);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            DefaultHandler handler = new DefaultHandler() {
                private String nameSpace = null;
                private boolean found = false;

                public void startElement(String uri, String localName, String qName, Attributes attributes) {
                    if (!found) {
                        String tagName = null;
                        int ix = qName.indexOf(":");
                        if (ix >= 0) {
                            tagName = qName.substring(ix + 1);
                        } else {
                            tagName = qName;
                        }
                        if ("schema".equals(tagName)) {
                            nameSpace = attributes.getValue("targetNamespace");
                            found = true;
                        }
                    }
                }

                public String toString() {
                    return nameSpace;
                }
            };
            parser.parse(file, handler);
            if (handler.toString() != null) {
                schemas.put(handler.toString(), schema);
            } else {
                logger.warn("Error reading xml schema: " + file);
            }

        } catch (Exception e) {
            logger.warn("Invalid xml schema " + file);
            logger.debug("Stacktrace: ", e);
        }

    }
}