Example usage for javax.xml.parsers DocumentBuilderFactory setValidating

List of usage examples for javax.xml.parsers DocumentBuilderFactory setValidating

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setValidating.

Prototype


public void setValidating(boolean validating) 

Source Link

Document

Specifies that the parser produced by this code will validate documents as they are parsed.

Usage

From source file:com.naryx.tagfusion.cfm.document.cfDOCUMENT.java

public Document getDocument(String _renderedBody) throws cfmRunTimeException {
    try {/*from w  w  w .  ja va  2s.c o m*/
        DocumentBuilder builder;
        InputSource is = new InputSource(new StringReader(_renderedBody));
        Document doc;
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setValidating(false);
        builder = builderFactory.newDocumentBuilder();
        builder.setEntityResolver(new NoValidationResolver());
        doc = builder.parse(is);
        return doc;
    } catch (Exception e) {
        throw newRunTimeException("Failed to create valid xhtml document due to " + e.getClass().getName()
                + ": " + e.getMessage());
    }
}

From source file:com.zacwolf.commons.wbxcon.WBXCONorg.java

/**
 * Authenticates with the wapiAUTHURL, to pull a token and a server name
 * which is then used to populate the wapiURL and generate a cred used
 * by all subsequent REST calls//from  w w  w  .  j a  v a  2  s  .c o m
 * 
 * These queries are not added to the WAPIworker thread pool queue
 * 
 * @throws WBXCONexception
 */
final private synchronized void restapiDomainGetCredToken(final int retry) {
    Document dom = null;
    final List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("cmd", "getwebextoken"));
    params.add(new BasicNameValuePair("username", this.wapiUSER));
    params.add(new BasicNameValuePair("password", this.wapiPASS));
    params.add(new BasicNameValuePair("isp", "wbx"));
    try {
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setCoalescing(true);
        final DocumentBuilder db = factory.newDocumentBuilder();

        System.out.println("this.wapiAUTHURL : " + this.wapiAUTHURL);
        System.out.println("restapiDomainGetCredToken: 1 ");

        HttpPost httpPost = new HttpPost(this.wapiAUTHURL);
        System.out.println("restapiDomainGetCredToken: 2 ");
        httpPost.setEntity(new UrlEncodedFormEntity(params, org.apache.http.Consts.UTF_8));
        System.out.println("restapiDomainGetCredToken: 3 ");
        CloseableHttpResponse httpRes = HTTPSCLIENT.execute(httpPost, new BasicHttpContext());
        System.out.println("restapiDomainGetCredToken: 4 ");
        try {
            dom = db.parse(httpRes.getEntity().getContent());
            System.out.println("restapiDomainGetCredToken: 5 ");
        } finally {
            httpRes.close();
            System.out.println("restapiDomainGetCredToken: 6 ");
        }
        NodeList result = dom.getElementsByTagName("result");
        System.out.println("restapiDomainGetCredToken: 7 ");
        if (result == null || result.item(0) == null
                || !result.item(0).getTextContent().equalsIgnoreCase("success"))
            throw new WBXCONexception("restapiDomainGetCredToken(" + retry + "): [RESULT]:"
                    + result.item(0).getTextContent() + " [ERROR}:" + documentGetErrorString(dom));
        System.out.println("restapiDomainGetCredToken: 8 ");
        this.wapiURL = "https://" + dom.getElementsByTagName("serviceurl").item(0).getTextContent() + "/op.do";
        System.out.println("=======restapiDomainGetCredToken======= wapiURL :" + this.wapiURL);
        this.wapiREPORTURL = "https://" + dom.getElementsByTagName("serviceurl").item(0).getTextContent()
                + "/getfile.do";
        System.out.println("=======restapiDomainGetCredToken======= wapiREPORTURL :" + this.wapiREPORTURL);
        params.clear();
        params.add(new BasicNameValuePair("cmd", "login"));
        params.add(new BasicNameValuePair("username", this.wapiUSER));
        params.add(new BasicNameValuePair("isp", "wbx"));
        params.add(new BasicNameValuePair("autocommit", "true"));
        params.add(new BasicNameValuePair("token", dom.getElementsByTagName("token").item(0).getTextContent()));
        httpPost = new HttpPost(this.wapiURL);
        System.out.println("restapiDomainGetCredToken: 9 ");
        httpPost.setEntity(new UrlEncodedFormEntity(params, org.apache.http.Consts.UTF_8));
        System.out.println("restapiDomainGetCredToken: 10 ");
        httpRes = HTTPSCLIENT.execute(httpPost, new BasicHttpContext());
        System.out.println("restapiDomainGetCredToken: 11 ");
        try {
            dom = db.parse(httpRes.getEntity().getContent());
            System.out.println("restapiDomainGetCredToken: 12 ");
        } finally {
            httpRes.close();
        }
        result = dom.getElementsByTagName("result");
        if (result == null || result.item(0) == null
                || !result.item(0).getTextContent().equalsIgnoreCase("success"))
            throw new WBXCONexception(getMethodName(2) + ": [RESULT]:" + result.item(0).getTextContent()
                    + " [ERROR}:" + documentGetErrorString(dom));
        System.out.println("restapiDomainGetCredToken: 13 ");
        this.cred = dom.getElementsByTagName("cred").item(0).getTextContent();
        System.out.println("restapiDomainGetCredToken: 14 ");
        this.cred_generated = System.currentTimeMillis();
        System.out.println("restapiDomainGetCredToken: 15 ");
    } catch (final Exception e) {
        if (retry < 3) {
            //Retry generating a new cred three times before giving up
            restapiDomainGetCredToken(retry + 1);
        } else {
            this.wapiURL = null;
            System.err.println(getMethodName() + "(" + retry + ") for " + this.orgName
                    + " unable to generate CRED token.");
            e.printStackTrace();
            //System.exit(3);
        }
    }
}

From source file:com.amalto.workbench.utils.XSDGenerateHTML.java

/**
 * Read the markup from the .xml input.// www  .ja v a2 s  .  co  m
 * 
 * @param fileName the name of an XML file.
 */
public void readMarkup(String fileName) {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setValidating(false);
    try {
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(fileName);
        for (Node child = document.getDocumentElement().getFirstChild(); child != null; child = child
                .getNextSibling()) {
            if ("elementAnnotation".equals(child.getLocalName())) { //$NON-NLS-1$
                handleMarkup(elementDeclarationMarkupMap, (Element) child);
            } else if ("attributeAnnotation".equals(child.getLocalName())) { //$NON-NLS-1$
                handleMarkup(attributeDeclarationMarkupMap, (Element) child);
            } else if ("content".equals(child.getLocalName())) { //$NON-NLS-1$
                handleMarkup(contentDocumentationMap, (Element) child);
            } else if ("typeMap".equals(child.getLocalName())) { //$NON-NLS-1$
                Element markupElement = (Element) child;
                String schemaType = markupElement.getAttribute("schemaType"); //$NON-NLS-1$
                String javaClass = markupElement.getAttribute("javaClass"); //$NON-NLS-1$
                schemaTypeToJavaClassMap.put(schemaType, javaClass);
            }
        }
    } catch (Exception exception) {
        exception.printStackTrace(System.err);
    }
}

From source file:gov.va.ds4p.ds4pmobileportal.ui.eHealthExchange.java

private Document getW3CDocument(String docString) {
    Document doc = null;/*from  w w w .j  a  v  a2  s .c  o  m*/
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource source = new InputSource(new StringReader(docString));

        doc = db.parse(source);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return doc;
}

From source file:it.cnr.icar.eric.server.profile.ws.wsdl.cataloger.WSDLCatalogerEngine.java

private Document parseXML(InputSource source) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    builderFactory.setValidating(false);
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    builder.setErrorHandler(new ErrorHandler() {
        public void error(SAXParseException e) throws SAXParseException {
            throw e;
        }//ww  w .j  av a 2s .  c  o  m

        public void fatalError(SAXParseException e) throws SAXParseException {
            throw e;
        }

        public void warning(SAXParseException err) throws SAXParseException {
            // do nothing
        }
    });

    return builder.parse(source);
}

From source file:com.zacwolf.commons.wbxcon.WBXCONorg.java

/**
 * Class <code>Contructor</code> initializes WBXCONorg instance for the given managed org (domain) instance.
 * As part of initialization the Constructor makes a call to establish orgID and namespaceID for the domain.
 * //from   w  w  w . j a  v  a 2s.c om
 * The REST API calls are made via https GET and POST.  As such, the <code>HTTPSCLIENT</code> needs to be
 * initialized via a certificate stored in a default keystore.  Since the keystore contains a "static"
 * certificate provided by WebEx Connect, the keystore is generated "in source".  If WebEx Connect modifies
 * their default https certificate, you will need to download the latest version of this package from:<br />
 * <br />
 * <a href="https://github.com/ZacWolf/com.zacwolf.commons">https://github.com/ZacWolf/com.zacwolf.commons</a>
 * 
 * 
 * Whatever user is specified for wapiUSER, the following special privileges need to be granted to the account:
 * 
 * WBX:ManageDomain
 * WBX:ManageUsers
 * WBX:ManageRoles
 * 
 * @param domain_name   Name of the WebEx Connect Managed Org
 * @param wapiAUTHURL   (optional) URL used to override the default URL used to generate the initial login token
 * @param wapiUSER      WebEx UserName to use in making the REST calls
 * @param wapiPASS      WebEx user password to use in making the REST calls
 * @throws WBXCONexception
 */
WBXCONorg(final String domain_name, final String wapiAUTHURL, final String wapiUSER, final String wapiPASS)
        throws WBXCONexception {
    if (HTTPSCLIENT == null)
        try {
            //Quiet the various apache http client loggers
            Logger.getLogger("org.apache.http").setLevel(Level.SEVERE);
            Logger.getLogger("org.apache.http.wire").setLevel(Level.SEVERE);
            Logger.getLogger("org.apache.http.headers").setLevel(Level.SEVERE);
            System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
            System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
            System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "ERROR");
            System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "ERROR");
            System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.headers", "ERROR");

            final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(MAX_HTTP_REQUESTS);
            final KeyStore trustStore = KeyStore.getInstance("JCEKS");
            // Use the default keystore that is in the same package directory
            final InputStream instream = WBXCONorg.class.getClassLoader().getResourceAsStream(
                    WBXCONorg.class.getPackage().getName().replaceAll("\\.", "/") + "/" + TRUSTSTOREFILENAME);
            try {
                trustStore.load(instream, TRUSTSTOREPASS.toCharArray());
            } finally {
                instream.close();
            }
            final SSLContext sslcontext = SSLContexts.custom()// Trust own CA and all self-signed certs
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
            final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
                    new String[] { "TLSv1" }, // Allow TLSv1 protocol only
                    null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            final RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_TIMEOUT * 60000)
                    .setConnectionRequestTimeout(HTTP_TIMEOUT * 60000).setSocketTimeout(HTTP_TIMEOUT * 60000)
                    .build();
            HTTPSCLIENT = HttpClients.custom().setConnectionManager(cm).setSSLSocketFactory(sslsf)
                    .setDefaultRequestConfig(config).build();
        } catch (final Exception e) {
            System.err.println(WBXCONorg.class.getCanonicalName()
                    + " UNABLE TO ESTABLISH HTTPSCLIENT FOR WAPI CALLS. All WAPI CALLS WILL FAIL!!!");
            e.printStackTrace();
            //System.exit(2);
        }
    Runtime.getRuntime().addShutdownHook(new Thread("WBXCONorg shutdownhook") {
        @Override
        public void run() {
            try {
                finalize();
            } catch (final Throwable e) {
                e.printStackTrace();
            }
        }
    });
    this.orgName = domain_name;
    this.wapiAUTHURL = wapiAUTHURL != null ? wapiAUTHURL : this.wapiAUTHURL;
    this.wapiUSER = wapiUSER + (!wapiUSER.endsWith("@" + domain_name) ? "@" + domain_name : "");
    this.wapiPASS = wapiPASS;

    final Document dom;
    try {
        System.out.println("===============  1");
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        System.out.println("===============  2");
        factory.setValidating(false);
        System.out.println("===============  3");
        factory.setCoalescing(true);
        System.out.println("===============  4");
        final DocumentBuilder db = factory.newDocumentBuilder();
        System.out.println("===============  5");
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        System.out.println("===============  6");
        params.add(new BasicNameValuePair("cmd", "get"));
        System.out.println("===============  7");
        params.add(new BasicNameValuePair("type", "org"));
        System.out.println("===============  8");
        params.add(new BasicNameValuePair("select", "org/orgID:/org/namespaceID:ext/WBX/PWSRule"));
        System.out.println("===============  9");
        params.add(new BasicNameValuePair("id", "current"));
        System.out.println("===============  10");
        System.out.println("===============  getDomainCredToken() :" + getDomainCredToken());
        params.add(new BasicNameValuePair("cred", getDomainCredToken()));
        System.out.println("===============  11");
        System.out.println("===============  params" + params.toString());
        System.out.println("===============Before wapiURL :" + this.wapiURL);
        final HttpPost httpPost = new HttpPost(this.wapiURL);
        System.out.println("=============== after wapiURL :" + this.wapiURL);

        httpPost.setEntity(new UrlEncodedFormEntity(params, org.apache.http.Consts.UTF_8));
        System.out.println("===============  12");
        final CloseableHttpResponse httpRes = HTTPSCLIENT.execute(httpPost, new BasicHttpContext());
        System.out.println("===============  13");

        if (httpRes == null) {
            System.out.println("===============  httpRes is NULL");
        }

        try {
            dom = db.parse(httpRes.getEntity().getContent());
            System.out.println("===============  14");
        } finally {
            httpRes.close();
        }
    } catch (final Exception e) {
        throw new WBXCONexception(e);
    }
    final NodeList result = dom.getElementsByTagName("result");
    if (result == null || result.item(0) == null
            || !result.item(0).getTextContent().equalsIgnoreCase("success"))
        throw new WBXCONexception(
                "ERROR::WBXCONorg:constructor(\"" + domain_name + "\")::" + documentGetErrorString(dom));

    this.orgID = dom.getElementsByTagName("orgID").item(0).getTextContent();
    this.namespaceID = dom.getElementsByTagName("namespaceID").item(0).getTextContent();
    this.passwordrule = new PWSRule(Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumLength_9")),
            Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumAlpha_9")),
            Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumNumeric_9")),
            Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumSpecial_9")),
            documentGetTextContentByTagName(dom, "PWRequireMixedCase_B").equalsIgnoreCase("true"));
    this.wapiUser = restapiAccountGet(this.wapiUSER);
}

From source file:jef.tools.XMLUtils.java

private static DocumentBuilderFactory initFactory(boolean ignorComments, boolean namespaceAware) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setValidating(false); // DTD
    dbf.setIgnoringComments(ignorComments);
    dbf.setNamespaceAware(namespaceAware);
    // dbf.setCoalescing(true);//CDATA
    // ?Text???//  w ww .j  a  va 2  s .c o m
    try {
        // dbf.setFeature("http://xml.org/sax/features/namespaces", false);
        // dbf.setFeature("http://xml.org/sax/features/validation", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (ParserConfigurationException e) {
        log.warn(
                "Your xerces implemention is too old to support 'load-dtd-grammar' and 'load-external-dtd' feature. Please upgrade xercesImpl.jar to 2.6.2 or above.");
    } catch (AbstractMethodError e) {
        log.warn(
                "Your xerces implemention is too old to support 'load-dtd-grammar' and 'load-external-dtd' feature. Please upgrade xercesImpl.jar to 2.6.2 or above.");
    }

    try {
        dbf.setAttribute("http://xml.org/sax/features/external-general-entities", false);
    } catch (IllegalArgumentException e) {
        log.warn("Your xerces implemention is too old to support 'external-general-entities' attribute.");
    }
    try {
        dbf.setAttribute("http://xml.org/sax/features/external-parameter-entities", false);
    } catch (IllegalArgumentException e) {
        log.warn("Your xerces implemention is too old to support 'external-parameter-entities' attribute.");
    }
    try {
        dbf.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (IllegalArgumentException e) {
        log.warn("Your xerces implemention is too old to support 'load-external-dtd' attribute.");
    }
    return dbf;
}

From source file:io.datalayer.conf.XmlConfigurationTest.java

/**
 * Creates a validating document builder.
 * /* w w w. j  a v a 2 s  . c  o  m*/
 * @return the document builder
 * @throws ParserConfigurationException
 *             if an error occurs
 */
private DocumentBuilder createValidatingDocBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new DefaultHandler() {
        @Override
        public void error(SAXParseException ex) throws SAXException {
            throw ex;
        }
    });
    return builder;
}

From source file:org.apache.manifoldcf.crawler.connectors.meridio.meridiowrapper.MeridioWrapper.java

/** Given the castor object representing the Meridio DMDataSet XSD, this method generates
* the XML that must be passed over the wire to invoke the Meridio DM Web Service
*///from   w w  w  . j av  a  2 s  . c  o m
protected MessageElement[] getSOAPMessage(DMDataSet dsDM) throws MeridioDataSetException {

    if (oLog != null)
        oLog.debug("Meridio: Entered getSOAPMessage method.");

    try {
        Writer writer = new StringWriter();
        dsDM.marshal(writer);
        writer.close();
        //oLog.debug("Meridio: Marshalled XML: " + writer.toString());

        StringReader stringReader = new StringReader(writer.toString());
        InputSource inputSource = new InputSource(stringReader);

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setValidating(false);
        Document document = documentBuilderFactory.newDocumentBuilder().parse(inputSource);
        Element element = document.getDocumentElement();
        MessageElement messageElement = new MessageElement(element);

        MessageElement[] messageElementArray = { messageElement };
        if (oLog != null)
            oLog.debug("Meridio: Exiting getSOAPMessage method.");
        return messageElementArray;

    } catch (MarshalException marshalException) {
        throw new MeridioDataSetException("Castor error in marshalling the XML from the Meridio Dataset",
                marshalException);
    } catch (ValidationException validationException) {
        throw new MeridioDataSetException("Castor error in validating the XML from the Meridio Dataset",
                validationException);
    } catch (IOException IoException) {
        throw new MeridioDataSetException("IO Error in marshalling the Meridio Dataset", IoException);
    } catch (SAXException SaxException) {
        throw new MeridioDataSetException("XML Error in marshalling the Meridio Dataset", SaxException);
    } catch (ParserConfigurationException parserConfigurationException) {
        throw new MeridioDataSetException("XML Error in parsing the Meridio Dataset",
                parserConfigurationException);
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.meridio.meridiowrapper.MeridioWrapper.java

/** Given the castor object representing the Meridio DMDataSet XSD, this method generates
* the XML that must be passed over the wire to invoke the Meridio DM Web Service
*//*  w  w  w.ja  va 2s. c  o  m*/

protected MessageElement[] getSOAPMessage(RMDataSet dsRM) throws MeridioDataSetException {

    if (oLog != null)
        oLog.debug("Meridio: Entered getSOAPMessage method.");

    try {
        Writer writer = new StringWriter();
        dsRM.marshal(writer);
        writer.close();
        //oLog.debug("Meridio: Marshalled XML: " + writer.toString());

        StringReader stringReader = new StringReader(writer.toString());
        InputSource inputSource = new InputSource(stringReader);

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setValidating(false);
        Document document = documentBuilderFactory.newDocumentBuilder().parse(inputSource);
        Element element = document.getDocumentElement();
        MessageElement messageElement = new MessageElement(element);

        MessageElement[] messageElementArray = { messageElement };
        if (oLog != null)
            oLog.debug("Meridio: Exiting getSOAPMessage method.");
        return messageElementArray;

    } catch (MarshalException marshalException) {
        throw new MeridioDataSetException("Castor error in marshalling the XML from the Meridio Dataset",
                marshalException);
    } catch (ValidationException validationException) {
        throw new MeridioDataSetException("Castor error in validating the XML from the Meridio Dataset",
                validationException);
    } catch (IOException IoException) {
        throw new MeridioDataSetException("IO Error in marshalling the Meridio Dataset", IoException);
    } catch (SAXException SaxException) {
        throw new MeridioDataSetException("XML Error in marshalling the Meridio Dataset", SaxException);
    } catch (ParserConfigurationException parserConfigurationException) {
        throw new MeridioDataSetException("XML Error in parsing the Meridio Dataset",
                parserConfigurationException);
    }
}