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:org.corpus_tools.pepper.core.PepperJobImpl.java

/**
 * {@inheritDoc PepperJob#load(URI)}//  ww  w.  j a  v  a  2 s.c o  m
 */
@Override
public void load(URI uri) {
    if (uri.isFile()) {
        File wdFile = new File(uri.toFileString());
        // set folder containing workflow description as base dir
        setBaseDir(uri.trimSegments(1));

        SAXParser parser;
        XMLReader xmlReader;
        SAXParserFactory factory = SAXParserFactory.newInstance();

        WorkflowDescriptionReader contentHandler = new WorkflowDescriptionReader();
        contentHandler.setPepperJob(this);
        contentHandler.setLocation(uri);

        // remove all existing steps
        clear();

        try {
            parser = factory.newSAXParser();
            xmlReader = parser.getXMLReader();
            xmlReader.setContentHandler(contentHandler);
        } catch (ParserConfigurationException e) {
            throw new PepperModuleXMLResourceException("Cannot load Pepper workflow description file '"
                    + wdFile.getAbsolutePath() + "': " + e.getMessage() + ". ", e);
        } catch (Exception e) {
            throw new PepperModuleXMLResourceException("Cannot load Pepper workflow description file '"
                    + wdFile.getAbsolutePath() + "': " + e.getMessage() + ". ", e);
        }
        try {
            InputStream inputStream = new FileInputStream(wdFile);
            Reader reader = new InputStreamReader(inputStream, "UTF-8");
            InputSource is = new InputSource(reader);
            is.setEncoding("UTF-8");
            xmlReader.parse(is);
        } catch (SAXException e) {
            try {
                parser = factory.newSAXParser();
                xmlReader = parser.getXMLReader();
                xmlReader.setContentHandler(contentHandler);
                xmlReader.parse(wdFile.getAbsolutePath());
            } catch (Exception e1) {
                throw new PepperModuleXMLResourceException("Cannot load Pepper workflow description file '"
                        + wdFile.getAbsolutePath() + "': " + e1.getMessage() + ". ", e1);
            }
        } catch (Exception e) {
            if (e instanceof PepperModuleException) {
                throw (PepperModuleException) e;
            } else {
                throw new PepperModuleXMLResourceException("Cannot load Pepper workflow description file'"
                        + wdFile + "', because of a nested exception: " + e.getMessage() + ". ", e);
            }
        }
    } else {
        throw new UnsupportedOperationException(
                "Currently Pepper can only load workflow description from local files.");
    }
}

From source file:org.corpus_tools.salt.util.SaltUtil.java

/**
 * Loads a list of root objects coming from a SaltXML (.{@link #FILE_ENDING_SALT_XML})
 * and returns it.// w  w  w  . ja  va2  s .c o  m
 * 
 * @param objectURI
 *            {@link URI} to SaltXML file containing the object
 * @return loaded objects
 */
public static List<Object> loadObjects(URI location) {
    if (location == null) {
        throw new SaltResourceException("Cannot load Salt object, because the given uri is null.");
    }
    File objectFile = new File(
            (location.toFileString() == null) ? location.toString() : location.toFileString());
    if (!objectFile.exists()) {
        throw new SaltResourceException("Cannot load Salt object, because the file '"
                + objectFile.getAbsolutePath() + "' does not exist.");
    }

    SAXParser parser;
    XMLReader xmlReader;
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SaltXML10Handler contentHandler = new SaltXML10Handler();

    try {
        parser = factory.newSAXParser();
        xmlReader = parser.getXMLReader();
        xmlReader.setContentHandler(contentHandler);
    } catch (ParserConfigurationException e) {
        throw new SaltResourceException(
                "Cannot load Salt object from file '" + objectFile.getAbsolutePath() + "'.", e);
    } catch (Exception e) {
        throw new SaltResourceException(
                "Cannot load Salt object from file '" + objectFile.getAbsolutePath() + "'.", e);
    }
    try {
        InputStream inputStream = new FileInputStream(objectFile);
        Reader reader = new InputStreamReader(inputStream, "UTF-8");
        InputSource is = new InputSource(reader);
        is.setEncoding("UTF-8");
        xmlReader.parse(is);
    } catch (SAXException e) {
        try {
            parser = factory.newSAXParser();
            xmlReader = parser.getXMLReader();
            xmlReader.setContentHandler(contentHandler);
            xmlReader.parse(objectFile.getAbsolutePath());
        } catch (Exception e1) {
            throw new SaltResourceException(
                    "Cannot load Salt object from file '" + objectFile.getAbsolutePath() + "'.", e1);
        }
    } catch (Exception e) {
        if (e instanceof SaltException) {
            throw (SaltException) e;
        } else {
            throw new SaltResourceException(
                    "Cannot load Salt object from file'" + objectFile + "', because of a nested exception. ",
                    e);
        }
    }
    return contentHandler.getRootObjects();
}

From source file:org.dcm4che.tool.dcm2xml.Dcm2Xml.java

private static Attributes parseXML(String fname) throws Exception {
    Attributes attrs = new Attributes();
    ContentHandlerAdapter ch = new ContentHandlerAdapter(attrs);
    SAXParserFactory f = SAXParserFactory.newInstance();
    SAXParser p = f.newSAXParser();
    p.parse(new File(fname), ch);
    return attrs;
}

From source file:org.dcm4che.tool.xml2dcm.Xml2Dcm.java

private static void parseXML(String fname, ContentHandlerAdapter ch) throws Exception {
    SAXParserFactory f = SAXParserFactory.newInstance();
    SAXParser p = f.newSAXParser();
    if (fname.equals("-")) {
        p.parse(System.in, ch);/*from  w w w .  ja  v a 2s. c  om*/
    } else {
        p.parse(new File(fname), ch);
    }
}

From source file:org.dcm4che2.tool.chess3d.Chess3D.java

public void extrude(File xmlFile, int slices) throws IOException, ParserConfigurationException, SAXException {
    DicomObject obj = new BasicDicomObject();
    String fn;/*from   w  ww .  ja v a2  s  . c om*/
    File parent;
    if (xmlFile != null) {
        SAXParserFactory f = SAXParserFactory.newInstance();
        SAXParser p = f.newSAXParser();
        ContentHandlerAdapter ch = new ContentHandlerAdapter(obj);
        p.parse(xmlFile, ch);
        fn = obj.getString(Tag.PatientID);
        if (fn == null)
            fn = xmlFile.getName();
        parent = destDir == null ? xmlFile.getParentFile() : destDir;
    } else {
        fn = "test";
        parent = destDir == null ? null : destDir;
    }
    File oFile;
    String ext;
    int pos = fn.lastIndexOf('.');
    if (pos != -1) {
        ext = fn.substring(pos);//we want '.' too
        fn = fn.substring(0, pos);
    } else {
        ext = "";
    }
    fn += "_";
    obj = prepare(obj);
    prepareLineBuffer();
    int imageSize = lineLength * yRect * rectHeight;
    for (int z = 0; z < zRect; z++) {
        for (int i = 0; i < slices; i++) {
            System.out.print("*");
            chgAttributes(obj, i);
            oFile = new File(parent, fn + z + "_" + (i) + ext);
            DicomOutputStream dos = new DicomOutputStream(oFile);
            dos.writeDicomFile(obj);
            dos.writeHeader(Tag.PixelData, VR.OB, (imageSize + 1) & ~1);
            writePixelData(dos, z);
            if ((imageSize & 1) != 0)
                dos.write(0);
            dos.close();
        }
    }
}

From source file:org.dcm4che2.tool.xml2dcm.Xml2Dcm.java

private static void parseXML(String xmlFile, DicomObject dcmobj, String baseDir)
        throws FactoryConfigurationError, ParserConfigurationException, SAXException, IOException {
    SAXParserFactory f = SAXParserFactory.newInstance();
    SAXParser p = f.newSAXParser();
    ContentHandlerAdapter ch = new ContentHandlerAdapter(dcmobj);
    if (xmlFile != null) {
        p.parse(new File(xmlFile), ch);
    } else if (baseDir != null) {
        String uri = "file:" + new File(baseDir, "STDIN").getAbsolutePath();
        if (File.separatorChar == '\\') {
            uri = uri.replace('\\', '/');
        }/*from  ww w. j  a  v a 2s.co  m*/
        p.parse(System.in, ch, uri);
    } else {
        p.parse(System.in, ch);
    }
}

From source file:org.dspace.content.authority.LCNameAuthority.java

/**
 * Guts of the implementation, returns a complete Choices result, or
 * null for a failure./* w w w . java 2s  .com*/
 */
private Choices queryPerson(String text, int start, int limit) {
    // punt if there is no query text
    if (text == null || text.trim().length() == 0) {
        return new Choices(true);
    }

    // 1. build CQL query
    DCPersonName pn = new DCPersonName(text);
    StringBuilder query = new StringBuilder();
    query.append("local.FirstName = \"").append(pn.getFirstNames()).append("\" and local.FamilyName = \"")
            .append(pn.getLastName()).append("\"");

    // XXX arbitrary default limit - should be configurable?
    if (limit == 0) {
        limit = 50;
    }

    NameValuePair args[] = new NameValuePair[6];
    args[0] = new NameValuePair("operation", "searchRetrieve");
    args[1] = new NameValuePair("version", "1.1");
    args[2] = new NameValuePair("recordSchema", "info:srw/schema/1/marcxml-v1.1");
    args[3] = new NameValuePair("query", query.toString());
    args[4] = new NameValuePair("maximumRecords", String.valueOf(limit));
    args[5] = new NameValuePair("startRecord", String.valueOf(start + 1));
    HttpClient hc = new HttpClient();
    String srUrl = url + "?" + EncodingUtil.formUrlEncode(args, "UTF8");
    GetMethod get = new GetMethod(srUrl);

    log.debug("Trying SRU query, URL=" + srUrl);

    // 2. web request
    try {
        int status = hc.executeMethod(get);
        if (status == 200) {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            SRUHandler handler = new SRUHandler();

            // XXX FIXME: should turn off validation here explicitly, but
            //  it seems to be off by default.
            xr.setFeature("http://xml.org/sax/features/namespaces", true);
            xr.setContentHandler(handler);
            xr.setErrorHandler(handler);
            xr.parse(new InputSource(get.getResponseBodyAsStream()));

            // this probably just means more results available..
            if (handler.hits != handler.result.size()) {
                log.warn("Discrepency in results, result.length=" + handler.result.size()
                        + ", yet expected results=" + handler.hits);
            }
            boolean more = handler.hits > (start + handler.result.size());

            // XXX add non-auth option; perhaps the UI should do this?
            // XXX it's really a policy matter if they allow unauth result.
            // XXX good, stop it.
            // handler.result.add(new Choice("", text, "Non-Authority: \""+text+"\""));

            int confidence;
            if (handler.hits == 0) {
                confidence = Choices.CF_NOTFOUND;
            } else if (handler.hits == 1) {
                confidence = Choices.CF_UNCERTAIN;
            } else {
                confidence = Choices.CF_AMBIGUOUS;
            }
            return new Choices(handler.result.toArray(new Choice[handler.result.size()]), start, handler.hits,
                    confidence, more);
        }
    } catch (HttpException e) {
        log.error("SRU query failed: ", e);
        return new Choices(true);
    } catch (IOException e) {
        log.error("SRU query failed: ", e);
        return new Choices(true);
    } catch (ParserConfigurationException e) {
        log.warn("Failed parsing SRU result: ", e);
        return new Choices(true);
    } catch (SAXException e) {
        log.warn("Failed parsing SRU result: ", e);
        return new Choices(true);
    } finally {
        get.releaseConnection();
    }
    return new Choices(true);
}

From source file:org.dspace.content.authority.SHERPARoMEOProtocol.java

protected Choices query(String result, String label, String authority, NameValuePair[] args, int start,
        int limit) {
    HttpClient hc = new HttpClient();
    String srUrl = url + "?" + EncodingUtil.formUrlEncode(args, "UTF8");
    GetMethod get = new GetMethod(srUrl);

    log.debug("Trying SHERPA/RoMEO Query, URL=" + srUrl);

    try {//from   w  w  w. jav a 2  s  . c o m
        int status = hc.executeMethod(get);
        if (status == 200) {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            SRHandler handler = new SRHandler(result, label, authority);

            // XXX FIXME: should turn off validation here explicitly, but
            //  it seems to be off by default.
            xr.setFeature("http://xml.org/sax/features/namespaces", true);
            xr.setContentHandler(handler);
            xr.setErrorHandler(handler);
            xr.parse(new InputSource(get.getResponseBodyAsStream()));
            int confidence;
            if (handler.total == 0) {
                confidence = Choices.CF_NOTFOUND;
            } else if (handler.total == 1) {
                confidence = Choices.CF_UNCERTAIN;
            } else {
                confidence = Choices.CF_AMBIGUOUS;
            }
            return new Choices(handler.result, start, handler.total, confidence, false);
        }
    } catch (HttpException e) {
        log.error("SHERPA/RoMEO query failed: ", e);
        return null;
    } catch (IOException e) {
        log.error("SHERPA/RoMEO query failed: ", e);
        return null;
    } catch (ParserConfigurationException e) {
        log.warn("Failed parsing SHERPA/RoMEO result: ", e);
        return null;
    } catch (SAXException e) {
        log.warn("Failed parsing SHERPA/RoMEO result: ", e);
        return null;
    } finally {
        get.releaseConnection();
    }
    return null;
}

From source file:org.dspace.content.authority.SkylightAPIProtocol.java

protected Choices query(String result, String label, String authority, String args, int start, int limit)
        throws UnsupportedEncodingException {
    String encodedArgs = new String(args.getBytes("UTF-8"), "UTF-8");
    HttpClient hc = new HttpClient();
    String srUrl = url + "/search/" + encodedArgs + ".xml?field=" + label;
    GetMethod get = new GetMethod(srUrl);

    log.info("Trying Skylight Query, URL=" + srUrl);

    try {/*from  www . ja  v  a  2s  . co m*/
        int status = hc.executeMethod(get);
        log.info("Status" + status);
        if (status == 200) {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            SRHandler handler = new SRHandler(result, label, authority);

            // XXX FIXME: should turn off validation here explicitly, but
            //  it seems to be off by default.
            xr.setFeature("http://xml.org/sax/features/namespaces", true);
            xr.setContentHandler(handler);
            xr.setErrorHandler(handler);
            InputSource src = new InputSource(get.getResponseBodyAsStream());
            log.info("Source from sklightui :: " + src.toString());
            xr.parse(src);

            int confidence;
            if (handler.total == 0) {
                confidence = Choices.CF_NOTFOUND;
            } else if (handler.total == 1) {
                confidence = Choices.CF_UNCERTAIN;
            } else {
                confidence = Choices.CF_AMBIGUOUS;
            }
            return new Choices(handler.result, start, handler.total, confidence, false);
        }
    } catch (HttpException e) {
        log.error("Skylight query failed: ", e);
        return null;
    } catch (IOException e) {
        log.error("Skylight query failed: ", e);
        return null;
    } catch (ParserConfigurationException e) {
        log.warn("Failed parsing SHERPA/RoMEO result: ", e);
        return null;
    } catch (SAXException e) {
        log.warn("Failed parsing Skylight result: ", e);
        return null;
    } finally {
        get.releaseConnection();
    }
    return null;
}

From source file:org.dspace.testing.PubMedToImport.java

public static void main(String args[]) {
    Options options = new Options();

    options.addOption(new Option("s", "source", true, "Source xml"));
    options.addOption(new Option("o", "output", true, "Output directory"));

    try {/*w  w  w .ja va 2  s. co  m*/
        CommandLine cli = new PosixParser().parse(options, args);

        String source = cli.getOptionValue("s");
        String output = cli.getOptionValue("o");

        if (!new File(source).exists()) {
            throw new IllegalArgumentException("Source file does not exist");
        }

        outputDir = new File(output);
        if (outputDir.exists()) {
            if (outputDir.list().length > 0) {
                throw new IllegalStateException("Output directory must be empty");
            }
        } else {
            if (!outputDir.mkdirs()) {
                throw new IllegalStateException("Unable to create output directory");
            }
        }

        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();

        saxParser.parse(source, new PubMedHandler());

    } catch (Exception e) {

    }
}