Example usage for org.xml.sax.helpers XMLReaderFactory createXMLReader

List of usage examples for org.xml.sax.helpers XMLReaderFactory createXMLReader

Introduction

In this page you can find the example usage for org.xml.sax.helpers XMLReaderFactory createXMLReader.

Prototype

public static XMLReader createXMLReader() throws SAXException 

Source Link

Document

Obtains a new instance of a org.xml.sax.XMLReader .

Usage

From source file:io.milton.http.LockInfoSaxHandler.java

public static LockInfo parseLockInfo(Request request) throws IOException, FileNotFoundException, SAXException {
    InputStream in = request.getInputStream();

    XMLReader reader = XMLReaderFactory.createXMLReader();
    reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

    LockInfoSaxHandler handler = new LockInfoSaxHandler();
    reader.setContentHandler(handler);/*ww  w  .j ava 2s .c  om*/
    if (log.isDebugEnabled()) {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        IOUtils.copy(in, bout);
        byte[] bytes = bout.toByteArray();
        in = new ByteArrayInputStream(bytes);
        log.debug("LockInfo: " + bout.toString());
    }
    reader.parse(new InputSource(in));
    LockInfo info = handler.getInfo();
    info.depth = LockDepth.INFINITY; // todo
    if (info.lockedByUser == null) {
        if (request.getAuthorization() != null) {
            if (request.getAuthorization().getUser() != null) {
                info.lockedByUser = request.getAuthorization().getUser();
            } else {
                Object user = request.getAuthorization().getTag();
                if (user instanceof DiscretePrincipal) {
                    DiscretePrincipal dp = (DiscretePrincipal) user;
                    info.lockedByUser = dp.getPrincipalURL();
                }
            }

        }
    }
    if (info.lockedByUser == null) {
        log.warn("resource is being locked with a null user. This won't really be locked at all...");
    }
    return info;
}

From source file:com.janoz.tvapilib.support.XmlParsingObject.java

protected void parse(AbstractSaxParser parser, InputStream inputStream) {
    try {/*from w  w  w . j a  va 2s  . co  m*/
        InputSource input = new InputSource(inputStream);
        input.setPublicId("");
        input.setSystemId("");
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(parser);
        reader.parse(input);
    } catch (SAXException e) {
        LOG.info("Error parsing XML data.", e);
        throw new TvApiException(e.getMessage(), e);
    } catch (IOException e) {
        LOG.info("IO error while parsing XML data.", e);
        throw new TvApiException("IO error while parsing XML data.", e);
    }
}

From source file:net.sf.janos.model.xml.ResultParser.java

/**
 * @param controller//w w  w.j a v  a 2  s.  com
 * @param xml
 * @return zone group state from the given xml
 * @throws IOException
 * @throws SAXException
 */
public static ZoneGroupState getGroupStateFromResult(String xml) throws SAXException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    ZoneGroupStateHandler handler = new ZoneGroupStateHandler();
    reader.setContentHandler(handler);
    try {
        reader.parse(new InputSource(new StringReader(xml)));
    } catch (IOException e) {
        // This should never happen - we're not performing I/O!
        LOG.error("Could not parse group state: ", e);
    }

    return new ZoneGroupState(handler.getGroups());

}

From source file:nbxml.Base.java

public void parseXml(String resource, ContentHandler contentHandler) throws SAXException, IOException {
    InputStream inputStream = getResourceAsStream(resource);
    InputSource inputSource = new InputSource(inputStream);
    XMLReader xmlReader = XMLReaderFactory.createXMLReader();

    xmlReader.setContentHandler(contentHandler);
    xmlReader.parse(inputSource);//from  w w w.  j  ava  2 s  . co  m
}

From source file:net.sf.vfsjfilechooser.accessories.bookmarks.BookmarksReader.java

public BookmarksReader(File bookmarksFile) {
    entries = new ArrayList<TitledURLEntry>();
    Reader reader = null;/*w w  w.j  a v  a  2 s .  c  om*/
    try {
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setContentHandler(new BookmarksHandler());

        reader = new BufferedReader(new InputStreamReader(new FileInputStream(bookmarksFile), "UTF-8"));

        // read 1st 2 bytes to support multiple encryptions
        char[] code = new char[2];
        reader.read(code, 0, 2);
        LOGGER.debug("code=" + String.valueOf(code) + "=");
        if ((code[0] == 'b') && (code[1] == '1')) {
            LOGGER.debug("in encrypted code section");
            // read the encrypted file
            InputStream is = new FileInputStream(bookmarksFile);

            int the_length = (int) bookmarksFile.length() - 2;
            LOGGER.debug("raw_length=" + (the_length + 2));
            if (the_length <= 0)
                the_length = 1;
            LOGGER.debug("fixed_length=" + the_length);
            byte[] code2 = new byte[2];
            byte[] outhex = new byte[the_length];
            try {
                is.read(code2);
                is.read(outhex);
                // is.read(outhex,2,the_length);
                is.close();
            } catch (Exception e) {
                LOGGER.info("exception reading encrypted file" + e);
            } finally {
                IOUtils.closeQuietly(is);
            }

            byte[] out = Util.hexByteArrayToByteArray(outhex);

            // do the decryption

            byte[] raw = new byte[16];
            raw[0] = (byte) 1;
            raw[2] = (byte) 23;
            raw[3] = (byte) 24;
            raw[4] = (byte) 2;
            raw[5] = (byte) 99;
            raw[6] = (byte) 200;
            raw[7] = (byte) 202;
            raw[8] = (byte) 209;
            raw[9] = (byte) 199;
            raw[10] = (byte) 181;
            raw[11] = (byte) 255;
            raw[12] = (byte) 33;
            raw[13] = (byte) 210;
            raw[14] = (byte) 214;
            raw[15] = (byte) 216;

            SecretKeySpec skeyspec = new SecretKeySpec(raw, "Blowfish");
            Cipher cipher = Cipher.getInstance("Blowfish");
            cipher.init(Cipher.DECRYPT_MODE, skeyspec);
            byte[] decrypted = cipher.doFinal(out);

            // convert decrypted into a bytestream and parse it
            ByteArrayInputStream bstream = new ByteArrayInputStream(decrypted);

            InputSource inputSource = new InputSource(bstream);
            xmlReader.parse(inputSource);
            LOGGER.debug("leaving encrypted code section");
        } else {
            LOGGER.debug("in decrypted code section");
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(bookmarksFile), "UTF-8"));
            InputSource inputSource = new InputSource(reader);
            xmlReader.parse(inputSource);
            LOGGER.debug("leaving decrypted code section");
        }
    } catch (SAXParseException e) {
        StringBuilder sb = new StringBuilder();
        sb.append("Error parsing xml bookmarks file").append("\n").append(e.getLineNumber()).append(":")
                .append(e.getColumnNumber()).append("\n").append(e.getMessage());
        throw new RuntimeException(sb.toString(), e);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Bookmarks file doesn't exist!", e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ioe) {
                LOGGER.error("Unable to close bookmarks stream", ioe);
            }
        }
    }
}

From source file:net.sf.janos.model.xml.ResultParser.java

public static Map<RenderingControlEventHandler.RenderingControlEventType, String> parseRenderingControlEvent(
        String xml) throws SAXException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    RenderingControlEventHandler handler = new RenderingControlEventHandler();
    reader.setContentHandler(handler);//from   ww  w .  ja  v a2  s  . c om
    try {
        reader.parse(new InputSource(new StringReader(xml)));
    } catch (IOException e) {
        // This should never happen - we're not performing I/O!
        LOG.error("Could not parse Rendering Control event: ", e);
    }
    return handler.getChanges();
}

From source file:com.wudaosoft.net.httpclient.SAXSourceResponseHandler.java

private SAXSource readSAXSource(InputStream body) throws IOException {
    try {//from   w w w  . j av a2s .c  o  m
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
        reader.setEntityResolver(NO_OP_ENTITY_RESOLVER);
        return new SAXSource(reader, new InputSource(body));
    } catch (SAXException ex) {
        throw new ClientProtocolException("Could not parse document: " + ex.getMessage(), ex);
    }
}

From source file:com.textocat.textokit.commons.io.axml.AXMLReader.java

/**
 * Populate the specified CAS by a text and annotations from the specified
 * input assuming that it is formatted as described above.
 *
 * @param in  input Reader. It is a caller's responsibility to close this
 *            reader instance./*ww  w .j ava 2s . c om*/
 * @param cas CAS
 * @throws IOException
 * @throws SAXException
 */
public static void read(Reader in, final CAS cas) throws IOException, SAXException {
    XMLReader xmlReader = XMLReaderFactory.createXMLReader();
    AXMLContentHandler contentHandler = new AXMLContentHandler(cas.getTypeSystem());
    xmlReader.setContentHandler(contentHandler);
    InputSource inputSource = new InputSource(in);
    xmlReader.parse(inputSource);
    cas.setDocumentText(contentHandler.getText());
    // from axml ID to CAS FS
    final Map<Annotation, FeatureStructure> mapped = Maps.newHashMap();
    List<Runnable> delayedFeatureAssignments = Lists.newLinkedList();
    //
    for (Annotation _anno : contentHandler.getAnnotations()) {
        String typeName = _anno.getType();
        Type type = cas.getTypeSystem().getType(typeName);
        if (type == null) {
            throw new IllegalStateException(String.format("Unknown type: %s", typeName));
        }
        final AnnotationFS anno = cas.createAnnotation(type, _anno.getBegin(), _anno.getEnd());
        // set primitive features
        for (String featName : _anno.getFeatureNames()) {
            final Feature feat = type.getFeatureByBaseName(featName);
            if (feat == null)
                throw new IllegalStateException(
                        String.format("%s does not have feature %s", type.getName(), featName));
            if (feat.getRange().isPrimitive()) {
                String featValStr = _anno.getFeatureStringValue(featName);
                if (featValStr != null) {
                    anno.setFeatureValueFromString(feat, featValStr);
                }
            } else {
                if (feat.getRange().isArray()) {
                    final List<Annotation> srcFSes = _anno.getFeatureFSArrayValue(featName);
                    delayedFeatureAssignments.add(new Runnable() {
                        @Override
                        public void run() {
                            List<FeatureStructure> mappedFSes = Lists.transform(srcFSes,
                                    new Function<Annotation, FeatureStructure>() {
                                        @Override
                                        public FeatureStructure apply(Annotation srcFS) {
                                            FeatureStructure mappedFS = mapped.get(srcFS);
                                            if (mappedFS == null)
                                                throw new IllegalStateException();
                                            return mappedFS;
                                        }
                                    });
                            anno.setFeatureValue(feat, FSCollectionFactory.createArrayFS(cas, mappedFSes));
                        }
                    });
                } else {
                    final Annotation srcFS = _anno.getFeatureFSValue(featName);
                    delayedFeatureAssignments.add(new Runnable() {
                        @Override
                        public void run() {
                            FeatureStructure mappedFS = mapped.get(srcFS);
                            if (mappedFS == null)
                                throw new IllegalStateException();
                            anno.setFeatureValue(feat, mappedFS);
                        }
                    });
                }
            }
        }
        cas.addFsToIndexes(anno);
        mapped.put(_anno, anno);
    }
    // PHASE II -- set FS and FSArray features
    for (Runnable r : delayedFeatureAssignments) {
        r.run();
    }
}

From source file:net.i2cat.netconf.test.TransportContentparserTest.java

@Before
public void initParser() throws SAXException {
    queue = new MessageQueue();
    xmlHandler = new TransportContentParser();
    xmlHandler.setMessageQueue(queue);/*from www . j  ava  2 s  .co  m*/
    parser = XMLReaderFactory.createXMLReader();
    parser.setContentHandler(xmlHandler);
    parser.setErrorHandler(xmlHandler);
}

From source file:de.weltraumschaf.groundzero.transform.ReportReader.java

/**
 * Dedicated constructor.//from w  ww.  j  ava  2s.c o m
 *
 * Set up the XML reader with the SAX handler.
 *
 * @param handler must not be {@code null}
 * @throws CreateXmlReaderException if creation of XML reader fails
 */
ReportReader(final CheckstyleSaxHandler handler) throws CreateXmlReaderException {
    super();
    Validate.notNull(handler, "Parameter handler must not be null!");
    this.handler = handler;

    try {
        xmlReader = XMLReaderFactory.createXMLReader();
    } catch (final SAXException ex) {
        throw new CreateXmlReaderException(ex.getMessage(), ex);
    }

    xmlReader.setContentHandler(handler);
    xmlReader.setErrorHandler(handler);
}