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(String className) throws SAXException 

Source Link

Document

Attempt to create an XML reader from a class name.

Usage

From source file:com.kdmanalytics.toif.adaptor.FindbugsAdaptor.java

/**
 * the xml produced form the tool is parsed by a sax parser and our own content handler.
 * /*from   w ww. j  a  va 2  s  .c o m*/
 * @throws ToifException
 */
@Override
public ArrayList<Element> parse(java.io.File process, AdaptorOptions options, IFileResolver resolver,
        boolean[] validLines, boolean unknownCWE) throws ToifException {
    // InputStream inputStream = null;
    try {
        InputStream fis = null;
        String theString = "";
        try {
            fis = new FileInputStream(process);
            StringWriter writer = new StringWriter();
            IOUtils.copy(fis, writer, "UTF-8");
            theString = writer.toString();
        } finally {
            if (fis != null)
                fis.close();
        }

        // inputStream = new ByteArrayInputStream(theString.getBytes(StandardCharsets.UTF_8));
        // Thread stderr;
        final FindBugsParser parser = new FindBugsParser(getProperties(), resolver, getAdaptorName(),
                unknownCWE);

        // final ByteArrayOutputStream errStream = new ByteArrayOutputStream();

        /*
         * The two streams could probably be merged with redirectErrorStream(), that was we would only
         * have to deal with one stream.
         */

        // stderr = new Thread(new StreamGobbler(inputStream, errStream));
        //
        // stderr.start();
        // stderr.join();
        //
        // final byte[] data = errStream.toByteArray();
        // final ByteArrayInputStream in = new ByteArrayInputStream(data);

        final XMLReader rdr = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
        rdr.setContentHandler(parser);
        rdr.parse(new InputSource(new StringReader(theString)));

        // return the elements gathered during the parse.
        ArrayList<Element> elements = parser.getElements();

        return elements;

    } catch (final SAXException e) {

        final String msg = getAdaptorName()
                + ": Possibly the file the tool is run against is too large, the wrong kind of file, or not just one file.";
        LOG.error(msg, e);
        e.printStackTrace();
        throw new ToifException(msg);
    } catch (final IOException e) {
        final String msg = getAdaptorName()
                + ": Possibly the file the tool is run against is too large, the wrong kind of file, or not just one file.";

        LOG.error(msg, e);
        throw new ToifException(msg);

    }
    // finally
    // {
    // if(inputStream != null) {
    // try {
    // inputStream.close();
    // }
    // catch (IOException e) {
    // e.printStackTrace();
    // }
    // }
    // }
    // catch (final InterruptedException e) {
    // final String msg = getAdaptorName()
    // + ": Possibly the file the tool is run against is too large, the wrong kind of file, or not
    // just one file.";
    //
    // LOG.error(msg, e);
    // throw new ToifException(msg);
    //
    // }
}

From source file:info.magnolia.importexport.DataTransporterTest.java

@Test
public void testRemoveNs() throws Exception {
    InputStream input = getClass().getResourceAsStream("/test-unwantedns.xml");
    File outputFile = File.createTempFile("export-test-", ".xml");
    OutputStream outputStream = new FileOutputStream(outputFile);

    XMLReader reader = XMLReaderFactory.createXMLReader(org.apache.xerces.parsers.SAXParser.class.getName());

    DataTransporter.readFormatted(reader, input, outputStream);

    IOUtils.closeQuietly(outputStream);//w  w  w.  jav a  2 s .co  m

    String result = FileUtils.readFileToString(outputFile);
    outputFile.delete();

    assertFalse("'removeme' namespace still found in output file",
            StringUtils.contains(result, "xmlns:removeme"));
    assertTrue("'sv' namespace not found in output file", StringUtils.contains(result, "xmlns:sv"));
    assertTrue("'xsi' namespace not found in output file", StringUtils.contains(result, "xmlns:xsi"));
}

From source file:SAXTreeValidator.java

/**
 * <p>This handles building the Swing UI tree.</p>
 *
 * @param treeModel Swing component to build upon.
 * @param base tree node to build on.//  w  w  w. j  a  va  2  s .  c  o  m
 * @param xmlURI URI to build XML document from.
 * @throws <code>IOException</code> - when reading the XML URI fails.
 * @throws <code>SAXException</code> - when errors in parsing occur.
 */
public void buildTree(DefaultTreeModel treeModel, DefaultMutableTreeNode base, String xmlURI)
        throws IOException, SAXException {

    // Create instances needed for parsing
    XMLReader reader = XMLReaderFactory.createXMLReader(vendorParserClass);
    ContentHandler jTreeContentHandler = new JValidatorContentHandler(treeModel, base);
    ErrorHandler jTreeErrorHandler = new JValidatorErrorHandler();

    // Register content handler
    reader.setContentHandler(jTreeContentHandler);

    // Register error handler
    reader.setErrorHandler(jTreeErrorHandler);

    // Turn on validation
    reader.setFeature("http://xml.org/sax/features/validation", true);
    reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);

    // Parse
    InputSource inputSource = new InputSource(xmlURI);
    reader.parse(inputSource);
}

From source file:edu.lternet.pasta.dml.dataquery.DataquerySpecification.java

/**
 * Set up the SAX parser for reading the XML serialized query
 *//*www .j a  va2  s  . c  o m*/
private XMLReader initializeParser() {
    XMLReader parser = null;

    // Set up the SAX document handlers for parsing
    try {

        // Get an instance of the parser
        parser = XMLReaderFactory.createXMLReader(parserName);

        // Set the ContentHandler to this instance
        parser.setContentHandler(this);

        // Set the error Handler to this instance
        parser.setErrorHandler(this);

    } catch (Exception e) {
        System.err.println("Error in QuerySpcecification.initializeParser " + e.toString());
    }

    return parser;
}

From source file:de.suse.swamp.core.util.BugzillaTools.java

private synchronized void xmlToData(String url) throws Exception {

    HttpState initialState = new HttpState();

    String authUsername = swamp.getProperty("BUGZILLA_AUTH_USERNAME");
    String authPassword = swamp.getProperty("BUGZILLA_AUTH_PWD");

    if (authUsername != null && authUsername.length() != 0) {
        Credentials defaultcreds = new UsernamePasswordCredentials(authUsername, authPassword);
        initialState.setCredentials(AuthScope.ANY, defaultcreds);
    } else {//from w  w  w. j av a2s .co m
        Cookie[] cookies = getCookies();
        for (int i = 0; i < cookies.length; i++) {
            initialState.addCookie(cookies[i]);
            Logger.DEBUG("Added Cookie: " + cookies[i].getName() + "=" + cookies[i].getValue(), log);
        }
    }
    HttpClient httpclient = new HttpClient();
    httpclient.setState(initialState);
    HttpMethod httpget = new GetMethod(url);
    try {
        httpclient.executeMethod(httpget);
    } catch (Exception e) {
        throw new Exception("Could not get URL " + url);
    }

    String content = httpget.getResponseBodyAsString();
    char[] chars = content.toCharArray();

    // removing illegal characters from bugzilla output.
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] < 32 && chars[i] != 9 && chars[i] != 10 && chars[i] != 13) {
            Logger.DEBUG("Removing illegal character: '" + chars[i] + "' on position " + i, log);
            chars[i] = ' ';
        }
    }
    Logger.DEBUG(String.valueOf(chars), log);
    CharArrayReader reader = new CharArrayReader(chars);
    XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    parser.setFeature("http://xml.org/sax/features/validation", false);
    // disable parsing of external dtd
    parser.setFeature("http://xml.org/sax/features/external-general-entities", false);
    parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    parser.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    // get XML File
    BugzillaReader handler = new BugzillaReader();
    parser.setContentHandler(handler);
    InputSource source = new InputSource();
    source.setCharacterStream(reader);
    source.setEncoding("utf-8");
    try {
        parser.parse(source);
    } catch (SAXParseException spe) {
        spe.printStackTrace();
        throw spe;
    }
    httpget.releaseConnection();
    if (errormsg != null) {
        throw new Exception(errormsg);
    }
}

From source file:Writer.java

/** Main program entry point. */
public static void main(String argv[]) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();//from ww  w. jav a  2  s. c  o  m
        System.exit(1);
    }

    // variables
    Writer writer = null;
    XMLReader parser = null;
    boolean namespaces = DEFAULT_NAMESPACES;
    boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES;
    boolean validation = DEFAULT_VALIDATION;
    boolean externalDTD = DEFAULT_LOAD_EXTERNAL_DTD;
    boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
    boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION;
    boolean xincludeProcessing = DEFAULT_XINCLUDE;
    boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS;
    boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE;
    boolean canonical = DEFAULT_CANONICAL;

    // process arguments
    for (int i = 0; i < argv.length; i++) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                }
                String parserName = argv[i];

                // create parser
                try {
                    parser = XMLReaderFactory.createXMLReader(parserName);
                } catch (Exception e) {
                    try {
                        Parser sax1Parser = ParserFactory.makeParser(parserName);
                        parser = new ParserAdapter(sax1Parser);
                        System.err.println("warning: Features and properties not supported on SAX1 parsers.");
                    } catch (Exception ex) {
                        parser = null;
                        System.err.println("error: Unable to instantiate parser (" + parserName + ")");
                        e.printStackTrace(System.err);
                    }
                }
                continue;
            }
            if (option.equalsIgnoreCase("n")) {
                namespaces = option.equals("n");
                continue;
            }
            if (option.equalsIgnoreCase("np")) {
                namespacePrefixes = option.equals("np");
                continue;
            }
            if (option.equalsIgnoreCase("v")) {
                validation = option.equals("v");
                continue;
            }
            if (option.equalsIgnoreCase("xd")) {
                externalDTD = option.equals("xd");
                continue;
            }
            if (option.equalsIgnoreCase("s")) {
                schemaValidation = option.equals("s");
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("ga")) {
                generateSyntheticAnnotations = option.equals("ga");
                continue;
            }
            if (option.equalsIgnoreCase("dv")) {
                dynamicValidation = option.equals("dv");
                continue;
            }
            if (option.equalsIgnoreCase("xi")) {
                xincludeProcessing = option.equals("xi");
                continue;
            }
            if (option.equalsIgnoreCase("xb")) {
                xincludeFixupBaseURIs = option.equals("xb");
                continue;
            }
            if (option.equalsIgnoreCase("xl")) {
                xincludeFixupLanguage = option.equals("xl");
                continue;
            }
            if (option.equalsIgnoreCase("c")) {
                canonical = option.equals("c");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
        }

        // use default parser?
        if (parser == null) {

            // create parser
            try {
                parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
            } catch (Exception e) {
                System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
                e.printStackTrace(System.err);
                continue;
            }
        }

        // set parser features
        try {
            parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + NAMESPACE_PREFIXES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(VALIDATION_FEATURE_ID, validation);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(LOAD_EXTERNAL_DTD_FEATURE_ID, externalDTD);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err
                    .println("warning: Parser does not support feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err
                    .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Parser does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            parser.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }
        try {
            parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Parser does not recognize feature (" + XINCLUDE_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        }

        // setup writer
        if (writer == null) {
            writer = new Writer();
            try {
                writer.setOutput(System.out, "UTF8");
            } catch (UnsupportedEncodingException e) {
                System.err.println("error: Unable to set output. Exiting.");
                System.exit(1);
            }
        }

        // set parser
        parser.setContentHandler(writer);
        parser.setErrorHandler(writer);
        try {
            parser.setProperty(LEXICAL_HANDLER_PROPERTY_ID, writer);
        } catch (SAXException e) {
            // ignore
        }

        // parse file
        writer.setCanonical(canonical);
        try {
            parser.parse(arg);
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            System.err.println("error: Parse error occurred - " + e.getMessage());
            if (e instanceof SAXException) {
                Exception nested = ((SAXException) e).getException();
                if (nested != null) {
                    e = nested;
                }
            }
            e.printStackTrace(System.err);
        }
    }

}

From source file:info.magnolia.importexport.DataTransporter.java

/**
 * Imports XML stream into repository./*from   w  ww  .  java  2s  .c  o m*/
 * XML is filtered by <code>MagnoliaV2Filter</code>, <code>VersionFilter</code> and <code>ImportXmlRootFilter</code>
 * if <code>keepVersionHistory</code> is set to <code>false</code>
 * @param xmlStream XML stream to import
 * @param repositoryName selected repository
 * @param basepath base path in repository
 * @param name (absolute path of <code>File</code>)
 * @param keepVersionHistory if <code>false</code> version info will be stripped before importing the document
 * @param importMode a valid value for ImportUUIDBehavior
 * @param saveAfterImport
 * @param createBasepathIfNotExist
 * @throws IOException
 * @see ImportUUIDBehavior
 * @see ImportXmlRootFilter
 * @see VersionFilter
 * @see MagnoliaV2Filter
 */
public static synchronized void importXmlStream(InputStream xmlStream, String repositoryName, String basepath,
        String name, boolean keepVersionHistory, int importMode, boolean saveAfterImport,
        boolean createBasepathIfNotExist) throws IOException {

    // TODO hopefully this will be fixed with a more useful message with the Bootstrapper refactoring
    if (xmlStream == null) {
        throw new IOException("Can't import a null stream into repository: " + repositoryName + ", basepath: "
                + basepath + ", name: " + name);
    }

    HierarchyManager hm = MgnlContext.getHierarchyManager(repositoryName);
    if (hm == null) {
        throw new IllegalStateException(
                "Can't import " + name + " since repository " + repositoryName + " does not exist.");
    }
    Workspace ws = hm.getWorkspace();

    if (log.isDebugEnabled()) {
        log.debug("Importing content into repository: [{}] from: [{}] into path: [{}]",
                new Object[] { repositoryName, name, basepath });
    }

    if (!hm.isExist(basepath) && createBasepathIfNotExist) {
        try {
            ContentUtil.createPath(hm, basepath, ItemType.CONTENT);
        } catch (RepositoryException e) {
            log.error("can't create path [{}]", basepath);
        }
    }

    Session session = ws.getSession();

    try {

        // Collects a list with all nodes at the basepath before import so we can see exactly which nodes were imported afterwards
        List<Node> nodesBeforeImport = NodeUtil
                .asList(NodeUtil.asIterable(session.getNode(basepath).getNodes()));

        if (keepVersionHistory) {
            // do not manipulate
            session.importXML(basepath, xmlStream, importMode);
        } else {
            // create readers/filters and chain
            XMLReader initialReader = XMLReaderFactory
                    .createXMLReader(org.apache.xerces.parsers.SAXParser.class.getName());
            try {
                initialReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            } catch (SAXException e) {
                log.error("could not set parser feature");
            }

            XMLFilter magnoliaV2Filter = null;

            // if stream is from regular file, test for belonging XSL file to apply XSL transformation to XML
            if (new File(name).isFile()) {
                InputStream xslStream = getXslStreamForXmlFile(new File(name));
                if (xslStream != null) {
                    Source xslSource = new StreamSource(xslStream);
                    SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory) SAXTransformerFactory
                            .newInstance();
                    XMLFilter xslFilter = saxTransformerFactory.newXMLFilter(xslSource);
                    magnoliaV2Filter = new MagnoliaV2Filter(xslFilter);
                }
            }

            if (magnoliaV2Filter == null) {
                magnoliaV2Filter = new MagnoliaV2Filter(initialReader);
            }

            XMLFilter versionFilter = new VersionFilter(magnoliaV2Filter);

            // enable this to strip useless "name" properties from dialogs
            // versionFilter = new UselessNameFilter(versionFilter);

            // enable this to strip mix:versionable from pre 3.6 xml files
            versionFilter = new RemoveMixversionableFilter(versionFilter);

            XMLReader finalReader = new ImportXmlRootFilter(versionFilter);

            ContentHandler handler = session.getImportContentHandler(basepath, importMode);
            finalReader.setContentHandler(handler);

            // parse XML, import is done by handler from session
            try {
                finalReader.parse(new InputSource(xmlStream));
            } finally {
                IOUtils.closeQuietly(xmlStream);
            }

            if (((ImportXmlRootFilter) finalReader).rootNodeFound) {
                String path = basepath;
                if (!path.endsWith(SLASH)) {
                    path += SLASH;
                }

                Node dummyRoot = (Node) session.getItem(path + JCR_ROOT);
                for (Iterator iter = dummyRoot.getNodes(); iter.hasNext();) {
                    Node child = (Node) iter.next();
                    // move childs to real root

                    if (session.itemExists(path + child.getName())) {
                        session.getItem(path + child.getName()).remove();
                    }

                    session.move(child.getPath(), path + child.getName());
                }
                // delete the dummy node
                dummyRoot.remove();
            }

            // Post process all nodes that were imported
            NodeIterator nodesAfterImport = session.getNode(basepath).getNodes();
            while (nodesAfterImport.hasNext()) {
                Node nodeAfterImport = nodesAfterImport.nextNode();
                boolean existedBeforeImport = false;
                for (Node nodeBeforeImport : nodesBeforeImport) {
                    if (NodeUtil.isSame(nodeAfterImport, nodeBeforeImport)) {
                        existedBeforeImport = true;
                        break;
                    }
                }
                if (!existedBeforeImport) {
                    postProcessAfterImport(nodeAfterImport);
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Error importing " + name + ": " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(xmlStream);
    }

    try {
        if (saveAfterImport) {
            session.save();
        }
    } catch (RepositoryException e) {
        log.error(MessageFormat.format(
                "Unable to save changes to the [{0}] repository due to a {1} Exception: {2}.",
                new Object[] { repositoryName, e.getClass().getName(), e.getMessage() }), e);
        throw new IOException(e.getMessage());
    }
}

From source file:com.frostwire.gui.updates.UpdateMessageReader.java

public void readUpdateFile() {
    HttpURLConnection connection = null;
    InputSource src = null;//from  www .j a v  a  2s  . c om

    try {
        String userAgent = "FrostWire/" + OSUtils.getOS() + "-" + OSUtils.getArchitecture() + "/"
                + FrostWireUtils.getFrostWireVersion();
        connection = (HttpURLConnection) (new URL(getUpdateURL())).openConnection();
        String url = getUpdateURL();
        System.out.println("Reading update file from " + url);
        connection.setRequestProperty("User-Agent", userAgent);
        connection.setRequestProperty("Connection", "close");
        connection.setReadTimeout(10000); // 10 secs timeout

        if (connection.getResponseCode() >= 400) {
            // invalid URL for sure
            connection.disconnect();
            return;
        }

        src = new InputSource(connection.getInputStream());

        XMLReader rdr = XMLReaderFactory
                .createXMLReader("com.sun.org.apache.xerces.internal.parsers.SAXParser");
        rdr.setContentHandler(this);

        rdr.parse(src);
        connection.getInputStream().close();
        connection.disconnect();
    } catch (java.net.SocketTimeoutException e3) {
        System.out.println("UpdateMessageReadre.readUpdateFile() Socket Timeout Exeception " + e3.toString());
    } catch (IOException e) {
        System.out.println("UpdateMessageReader.readUpdateFile() IO exception " + e.toString());
    } catch (SAXException e2) {
        System.out.println("UpdateMessageReader.readUpdateFile() SAX exception " + e2.toString());
    }
}

From source file:DocumentTracer.java

/** Main. */
public static void main(String[] argv) throws Exception {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();//from   ww w .  j av a 2s . co m
        System.exit(1);
    }

    // variables
    DocumentTracer tracer = new DocumentTracer();
    PrintWriter out = new PrintWriter(System.out);
    XMLReader parser = null;
    boolean namespaces = DEFAULT_NAMESPACES;
    boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES;
    boolean validation = DEFAULT_VALIDATION;
    boolean externalDTD = DEFAULT_LOAD_EXTERNAL_DTD;
    boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION;
    boolean xincludeProcessing = DEFAULT_XINCLUDE;
    boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS;
    boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE;

    // process arguments
    for (int i = 0; i < argv.length; i++) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                }
                String parserName = argv[i];

                // create parser
                try {
                    parser = XMLReaderFactory.createXMLReader(parserName);
                } catch (Exception e) {
                    try {
                        Parser sax1Parser = ParserFactory.makeParser(parserName);
                        parser = new ParserAdapter(sax1Parser);
                        System.err.println("warning: Features and properties not supported on SAX1 parsers.");
                    } catch (Exception ex) {
                        parser = null;
                        System.err.println("error: Unable to instantiate parser (" + parserName + ")");
                    }
                }
                continue;
            }
            if (option.equalsIgnoreCase("n")) {
                namespaces = option.equals("n");
                continue;
            }
            if (option.equalsIgnoreCase("np")) {
                namespacePrefixes = option.equals("np");
                continue;
            }
            if (option.equalsIgnoreCase("v")) {
                validation = option.equals("v");
                continue;
            }
            if (option.equalsIgnoreCase("xd")) {
                externalDTD = option.equals("xd");
                continue;
            }
            if (option.equalsIgnoreCase("s")) {
                schemaValidation = option.equals("s");
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("dv")) {
                dynamicValidation = option.equals("dv");
                continue;
            }
            if (option.equalsIgnoreCase("xi")) {
                xincludeProcessing = option.equals("xi");
                continue;
            }
            if (option.equalsIgnoreCase("xb")) {
                xincludeFixupBaseURIs = option.equals("xb");
                continue;
            }
            if (option.equalsIgnoreCase("xl")) {
                xincludeFixupLanguage = option.equals("xl");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
        }

        // use default parser?
        if (parser == null) {

            // create parser
            try {
                parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
            } catch (Exception e) {
                System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
                continue;
            }
        }

        // set parser features
        try {
            parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + NAMESPACE_PREFIXES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(VALIDATION_FEATURE_ID, validation);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(LOAD_EXTERNAL_DTD_FEATURE_ID, externalDTD);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err
                    .println("warning: Parser does not support feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err
                    .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Parser does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Parser does not recognize feature (" + XINCLUDE_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        }

        // set handlers
        parser.setDTDHandler(tracer);
        parser.setErrorHandler(tracer);
        if (parser instanceof XMLReader) {
            parser.setContentHandler(tracer);
            try {
                parser.setProperty("http://xml.org/sax/properties/declaration-handler", tracer);
            } catch (SAXException e) {
                e.printStackTrace(System.err);
            }
            try {
                parser.setProperty("http://xml.org/sax/properties/lexical-handler", tracer);
            } catch (SAXException e) {
                e.printStackTrace(System.err);
            }
        } else {
            ((Parser) parser).setDocumentHandler(tracer);
        }

        // parse file
        try {
            parser.parse(arg);
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            System.err.println("error: Parse error occurred - " + e.getMessage());
            if (e instanceof SAXException) {
                Exception nested = ((SAXException) e).getException();
                if (nested != null) {
                    e = nested;
                }
            }
            e.printStackTrace(System.err);
        }
    }

}

From source file:info.magnolia.importexport.DataTransporter.java

public static void executeExport(OutputStream baseOutputStream, boolean keepVersionHistory, boolean format,
        Session session, String basepath, String repository, String ext) throws IOException {
    OutputStream outputStream = baseOutputStream;
    if (ext.endsWith(ZIP)) {
        outputStream = new ZipOutputStream(baseOutputStream);
    } else if (ext.endsWith(GZ)) {
        outputStream = new GZIPOutputStream(baseOutputStream);
    }/*  w w w  .  j  a  v  a 2  s.co m*/

    try {
        if (keepVersionHistory) {
            // use exportSystemView in order to preserve property types
            // http://issues.apache.org/jira/browse/JCR-115
            if (!format) {
                session.exportSystemView(basepath, outputStream, false, false);
            } else {
                parseAndFormat(outputStream, null, repository, basepath, session, false);
            }
        } else {
            // use XMLSerializer and a SAXFilter in order to rewrite the
            // file
            XMLReader reader = new VersionFilter(
                    XMLReaderFactory.createXMLReader(org.apache.xerces.parsers.SAXParser.class.getName()));
            parseAndFormat(outputStream, reader, repository, basepath, session, false);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (RepositoryException e) {
        throw new RuntimeException(e);
    }

    // finish the stream properly if zip stream
    // this is not done by the IOUtils
    if (outputStream instanceof DeflaterOutputStream) {
        ((DeflaterOutputStream) outputStream).finish();
    }

    baseOutputStream.flush();
    IOUtils.closeQuietly(baseOutputStream);
}