Example usage for org.xml.sax XMLReader setFeature

List of usage examples for org.xml.sax XMLReader setFeature

Introduction

In this page you can find the example usage for org.xml.sax XMLReader setFeature.

Prototype

public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException;

Source Link

Document

Set the value of a feature flag.

Usage

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

/**
 * Imports XML stream into repository./* w  ww.j  a va2s  . co  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.wudaosoft.net.httpclient.SAXSourceResponseHandler.java

private SAXSource readSAXSource(InputStream body) throws IOException {
    try {/*from  w  w w  .  ja v a 2 s . 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:io.milton.http.webdav.DefaultPropPatchParser.java

private PropPatchParseResult parseContent(byte[] arr) throws IOException, SAXException {
    if (arr.length > 0) {
        log.debug("processing content");
        ByteArrayInputStream bin = new ByteArrayInputStream(arr);
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        PropPatchSaxHandler handler = new PropPatchSaxHandler();
        reader.setContentHandler(handler);
        reader.parse(new InputSource(bin));
        log.debug("toset: " + handler.getAttributesToSet().size());
        return new PropPatchParseResult(handler.getAttributesToSet(), handler.getAttributesToRemove().keySet());
    } else {//from   w w  w  .j ava2s. co m
        log.debug("empty content");
        return new PropPatchParseResult(new HashMap<QName, String>(), new HashSet<QName>());
    }

}

From source file:io.milton.http.webdav.DefaultPropFindRequestFieldParser.java

@Override
public PropertiesRequest getRequestedFields(InputStream in) {
    final Set<QName> set = new LinkedHashSet<QName>();
    try {/*  w w w.j  a v  a 2s.  com*/
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        StreamUtils.readTo(in, bout, false, true);
        byte[] arr = bout.toByteArray();
        if (arr.length > 1) {
            ByteArrayInputStream bin = new ByteArrayInputStream(arr);
            XMLReader reader = XMLReaderFactory.createXMLReader();
            reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
            PropFindSaxHandler handler = new PropFindSaxHandler();
            reader.setContentHandler(handler);
            try {
                reader.parse(new InputSource(bin));
                if (handler.isAllProp()) {
                    return new PropertiesRequest();
                } else {
                    set.addAll(handler.getAttributes().keySet());
                }
            } catch (IOException e) {
                log.warn("exception parsing request body", e);
                // ignore
            } catch (SAXException e) {
                log.warn("exception parsing request body", e);
                // ignore
            }
        }
    } catch (Exception ex) {
        // There's a report of an exception being thrown here by IT Hit Webdav client
        // Perhaps we can just log the error and return an empty set. Usually this
        // class is wrapped by the MsPropFindRequestFieldParser which will use a default
        // set of properties if this returns an empty set
        log.warn("Exception parsing PROPFIND request fields. Returning empty property set", ex);
        //throw new RuntimeException( ex );
    }
    return PropertiesRequest.toProperties(set);
}

From source file:com.webcohesion.ofx4j.client.impl.OFXHomeFIDataStore.java

private void initializeFIData() throws IOException, SAXException {
    URL url = new URL(getUrl());
    XMLReader xmlReader = new Parser();
    xmlReader.setFeature("http://xml.org/sax/features/namespaces", false);
    xmlReader.setFeature("http://xml.org/sax/features/validation", false);
    xmlReader.setContentHandler(new DirectoryContentHandler());
    xmlReader.parse(new InputSource(url.openStream()));
}

From source file:com.webcohesion.ofx4j.client.impl.OFXHomeFIDataStore.java

private BaseFinancialInstitutionData loadInstitutionData(String href) throws IOException, SAXException {
    if (LOG.isInfoEnabled()) {
        LOG.info("Loading institution data from: " + href);
    }// w w  w.  j a va  2 s .  c om

    URL url = new URL(href);
    XMLReader xmlReader = new Parser();
    xmlReader.setFeature("http://xml.org/sax/features/namespaces", false);
    xmlReader.setFeature("http://xml.org/sax/features/validation", false);
    InstitutionContentHandler institutionHandler = new InstitutionContentHandler();
    xmlReader.setContentHandler(institutionHandler);
    xmlReader.parse(new InputSource(url.openStream()));
    return institutionHandler.data;
}

From source file:Main.java

/** This sets the XML parser parameters.
 *///from  w  w  w  .j  a  va  2  s. c  om
public static void setDefaultParams(final XMLReader xmlReader, final boolean validateXml) throws SAXException {

    /** Default namespaces support (true). */
    final boolean DEFAULT_NAMESPACES = true;

    /** Default namespace prefixes (false). */
    final boolean DEFAULT_NAMESPACE_PREFIXES = false;

    /** Default validation support (false). */
    final boolean DEFAULT_VALIDATION = true;

    /** Default Schema validation support (false). */
    final boolean DEFAULT_SCHEMA_VALIDATION = true;

    /** Default Schema full checking support (false). */
    final boolean DEFAULT_SCHEMA_FULL_CHECKING = true;

    /** Default dynamic validation support (false). */
    final boolean DEFAULT_DYNAMIC_VALIDATION = true;

    boolean namespaces = DEFAULT_NAMESPACES;
    boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES;
    boolean validation = validateXml ? DEFAULT_VALIDATION : false;
    boolean schemaValidation = validateXml ? DEFAULT_SCHEMA_VALIDATION : false;
    boolean schemaFullChecking = validateXml ? DEFAULT_SCHEMA_FULL_CHECKING : false;
    boolean dynamicValidation = validateXml ? DEFAULT_DYNAMIC_VALIDATION : false;

    xmlReader.setFeature(NAMESPACES_FEATURE_ID, namespaces);
    xmlReader.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes);

    xmlReader.setFeature(VALIDATION_FEATURE_ID, validation);
    xmlReader.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);

    xmlReader.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);

    xmlReader.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation);
}

From source file:com.webcohesion.ofx4j.io.BaseOFXReader.java

/**
 * Parse an OFX version 2 stream from the first OFX element (defined by the {@link #getFirstElementStart() first element characters}).
 *
 * @param reader The reader./*www . j a  v  a2 s. com*/
 */
protected void parseV2FromFirstElement(Reader reader) throws IOException, OFXParseException {
    try {
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setFeature("http://xml.org/sax/features/namespaces", false);
        xmlReader.setContentHandler(new OFXV2ContentHandler(getContentHandler()));
        xmlReader.parse(new InputSource(reader));
    } catch (SAXException e) {
        if (e.getCause() instanceof OFXParseException) {
            throw (OFXParseException) e.getCause();
        }

        throw new OFXParseException(e);
    }
}

From source file:edu.wisc.my.portlets.dmp.tools.XmlMenuPublisher.java

/**
 * Publishes all the menus in the XML specified by the URL.
 * /*from ww  w . ja v  a  2s.  co  m*/
 * @param xmlSourceUrl URL to the menu XML.
 */
public void publishMenus(URL xmlSourceUrl) {
    LOG.info("Publishing menus from: " + xmlSourceUrl);

    try {
        //The XMLReader will read in the XML document
        final XMLReader reader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");

        try {
            reader.setFeature("http://apache.org/xml/features/validation/dynamic", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);

            final URL menuSchema = this.getClass().getResource("/menu.xsd");
            if (menuSchema == null) {
                throw new MissingResourceException("Could not load menu schema. '/menu.xsd'",
                        this.getClass().getName(), "/menu.xsd");
            }

            reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
                    menuSchema.toString());
        } catch (SAXNotRecognizedException snre) {
            LOG.warn("Could not enable XSD validation", snre);
        } catch (SAXNotSupportedException xnse) {
            LOG.warn("Could not enable XSD validation", xnse);
        }

        final MenuItemGeneratingHandler handler = new MenuItemGeneratingHandler();

        reader.setContentHandler(handler);
        reader.parse(new InputSource(xmlSourceUrl.openStream()));

        final Map menus = handler.getMenus();

        final BeanFactory factory = this.getFactory();
        final MenuDao dao = (MenuDao) factory.getBean("menuDao", MenuDao.class);

        for (final Iterator nameItr = menus.entrySet().iterator(); nameItr.hasNext();) {
            final Map.Entry entry = (Map.Entry) nameItr.next();
            final String menuName = (String) entry.getKey();
            final MenuItem rootItem = (MenuItem) entry.getValue();

            LOG.info("Publishing menu='" + menuName + "' item='" + rootItem + "'");
            dao.storeMenu(menuName, rootItem);
        }

        LOG.info("Published menus from: " + xmlSourceUrl);
    } catch (IOException ioe) {
        LOG.error("Error publishing menus", ioe);
    } catch (SAXException saxe) {
        LOG.error("Error publishing menus", saxe);
    }
}