Example usage for javax.xml.parsers DocumentBuilder newDocument

List of usage examples for javax.xml.parsers DocumentBuilder newDocument

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder newDocument.

Prototype


public abstract Document newDocument();

Source Link

Document

Obtain a new instance of a DOM Document object to build a DOM tree with.

Usage

From source file:com.liferay.portal.editor.fckeditor.receiver.impl.BaseCommandReceiver.java

private Document _createDocument() {
    try {//from   www.ja  v  a 2 s  . c om
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        return documentBuilder.newDocument();
    } catch (ParserConfigurationException pce) {
        throw new FCKException(pce);
    }
}

From source file:de.mpg.mpdl.inge.transformation.Util.java

public static Node getSize(String url) {
    DocumentBuilder documentBuilder;

    HttpClient httpClient = new HttpClient();
    HeadMethod headMethod = new HeadMethod(url);

    try {/*from   ww w.  java2  s.  c  o m*/
        logger.info("Getting size of " + url);
        ProxyHelper.executeMethod(httpClient, headMethod);

        if (headMethod.getStatusCode() != 200) {
            logger.warn("Wrong status code " + headMethod.getStatusCode() + " at " + url);
        }

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element element = document.createElement("size");
        document.appendChild(element);
        Header header = headMethod.getResponseHeader("Content-Length");
        logger.info("HEAD Request to " + url + " returned Content-Length: "
                + (header != null ? header.getValue() : null));
        if (header != null) {
            element.setTextContent(header.getValue());
            return document;
        } else {
            // did not get length via HEAD request, try to do a GET request
            // workaround for biomed central, where HEAD requests sometimes return Content-Length,
            // sometimes not

            logger.info("GET request to " + url + " did not return any Content-Length. Trying GET request.");
            httpClient = new HttpClient();
            GetMethod getMethod = new GetMethod(url);
            ProxyHelper.executeMethod(httpClient, getMethod);

            if (getMethod.getStatusCode() != 200) {
                logger.warn("Wrong status code " + getMethod.getStatusCode() + " at " + url);
            }

            InputStream is = getMethod.getResponseBodyAsStream();
            long size = 0;

            while (is.read() != -1) {
                size++;
            }
            is.close();

            logger.info("GET request to " + url + " returned a file with length: " + size);
            element.setTextContent(String.valueOf(size));
            return document;
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.mmax2.MMAXWriter.java

public Document createXML() throws MMAXWriterException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {//from  ww  w .  j  a  v  a  2s .com
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new MMAXWriterException(e);
    }
    return builder.newDocument();
}

From source file:at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient.java

/**
 * Gets a identity link.//from w  w w .ja v  a 2  s.  c o  m
 * 
 * @param reqElem the request.
 * @return a SZR-gateway response containing the result
 * @throws SZRGWException when an error occurs creating the mandate.
 */
public CreateIdentityLinkResponse createIdentityLinkResponse(Element reqElem) throws SZRGWClientException {

    try {
        if (address == null) {
            throw new NullPointerException("Address (SZR-gateway ServiceURL) must not be null.");
        }
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(address);
        method.setRequestHeader("SOAPAction", "");

        // ssl settings
        if (sSLSocketFactory != null) {
            SZRGWSecureSocketFactory fac = new SZRGWSecureSocketFactory(sSLSocketFactory);
            Protocol.registerProtocol("https", new Protocol("https", fac, 443));
        }

        // create soap body
        Element soapBody = getSOAPBody();
        Document doc = soapBody.getOwnerDocument();
        soapBody.appendChild(doc.importNode(reqElem, true));
        Element requestElement = soapBody.getOwnerDocument().getDocumentElement();

        //ParepUtils.saveElementToFile(requestElement, new File("c:/temp/szrRequest.xml"));
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ParepUtils.serializeElementAsDocument(requestElement, bos);

        method.setRequestBody(new ByteArrayInputStream(bos.toByteArray()));
        client.executeMethod(method);
        CreateIdentityLinkResponse response = new CreateIdentityLinkResponse();

        bos = new ByteArrayOutputStream();
        doc = ParepUtils.readDocFromIs(method.getResponseBodyAsStream());
        //ParepUtils.saveElementToFile(doc.getDocumentElement(), new File("c:/temp/szrResponse.xml"));

        NodeList list = doc.getElementsByTagNameNS(SZRGWConstants.SZRGW_REQUEST_NS, "ErrorResponse");
        if (list.getLength() > 0) {
            // set error response
            list = doc.getElementsByTagNameNS(SZRGWConstants.SZRGW_REQUEST_NS, "Info");
            String error = DOMUtils.getText(list.item(0));

            response.setError(error);
        } else {
            // set assertion
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document newdoc = builder.newDocument();

            Element nameSpaceNode = newdoc.createElement("NameSpaceNode");
            nameSpaceNode.setAttribute("xmlns:" + Constants.DSIG_PREFIX, Constants.DSIG_NS_URI);
            nameSpaceNode.setAttribute("xmlns:" + Constants.SAML_PREFIX, Constants.SAML_NS_URI);

            Element samlAssertion = (Element) XPathAPI.selectSingleNode(doc, "//saml:Assertion[1]",
                    nameSpaceNode);

            if (samlAssertion == null)
                throw new SZRGWClientException("Could not found a saml:Assertion element in response.");
            else
                response.setAssertion(samlAssertion);
        }

        return response;

    } catch (Exception e) {
        throw new SZRGWClientException(e);
    }
}

From source file:io.cos.cas.authentication.handler.support.OpenScienceFrameworkPrincipalFromRequestRemoteUserNonInteractiveCredentialsAction.java

/**
 * Normalize the Remote Principal credential.
 *
 * @param credential the credential object bearing the username, password, etc...
 * @return the json object to serialize for authorization with the OSF API
 * @throws ParserConfigurationException a parser configuration exception
 * @throws TransformerException a transformer exception
 *//*ww  w  .  j  a v a 2s  .co  m*/
private JSONObject normalizeRemotePrincipal(final OpenScienceFrameworkCredential credential)
        throws ParserConfigurationException, TransformerException {
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder builder = factory.newDocumentBuilder();

    final Document document = builder.newDocument();
    final Element rootElement = document.createElement("auth");
    document.appendChild(rootElement);

    for (final String key : credential.getAuthenticationHeaders().keySet()) {
        final Element attribute = document.createElement("attribute");
        attribute.setAttribute("name", key);
        attribute.setAttribute("value", credential.getAuthenticationHeaders().get(key));
        rootElement.appendChild(attribute);
    }

    // run the auth document through the transformer
    final DOMSource source = new DOMSource(document);
    final StringWriter writer = new StringWriter();
    final StreamResult result = new StreamResult(writer);

    this.institutionsAuthTransformer.transform(source, result);

    // convert transformed xml to json
    return XML.toJSONObject(writer.getBuffer().toString());
}

From source file:at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient.java

public Document buildGetIdentityLinkRequest(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname,
        String PEPSDateOfBirth, String signature, String representative, String represented,
        String mandateContent) throws SZRGWClientException {

    String SZRGW_NS = "http://reference.e-government.gv.at/namespace/szrgw/20070807#";
    try {/*ww w .  j a  va 2 s.  c om*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();

        Element getIdentityLink = doc.createElementNS(SZRGW_NS, "szrgw:GetIdentityLinkRequest");
        getIdentityLink.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:szrgw", SZRGW_NS);
        doc.appendChild(getIdentityLink);

        if ((PEPSIdentifier != null) || (PEPSFirstname != null) || (PEPSFamilyname != null)
                || (PEPSDateOfBirth != null)) {

            Element pepsDataElem = doc.createElementNS(SZRGW_NS, "szrgw:PEPSData");
            getIdentityLink.appendChild(pepsDataElem);

            if (PEPSIdentifier != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Identifier");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(PEPSIdentifier);
                elem.appendChild(text);
            }
            if (PEPSFirstname != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Firstname");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(PEPSFirstname);
                elem.appendChild(text);
            }

            if (PEPSFamilyname != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Familyname");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(PEPSFamilyname);
                elem.appendChild(text);
            }

            if (PEPSDateOfBirth != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:DateOfBirth");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(PEPSDateOfBirth);
                elem.appendChild(text);
            }

            if (representative != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Representative");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(representative);
                elem.appendChild(text);
            }

            if (represented != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Represented");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(represented);
                elem.appendChild(text);
            }

            if (mandateContent != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:MandateContent");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(mandateContent);
                elem.appendChild(text);
            }
        }

        if (signature == null)
            throw new SZRGWClientException("Signature element must not be null!");
        else {
            Element sig = doc.createElementNS(SZRGW_NS, "szrgw:Signature");
            Element base64content = doc.createElementNS(SZRGW_NS, "szrgw:Base64Content");
            sig.appendChild(base64content);
            getIdentityLink.appendChild(sig);
            Text text = doc.createTextNode(signature);
            base64content.appendChild(text);
        }

        if (representative != null && represented != null && mandateContent != null) {
            Element mis = doc.createElementNS(SZRGW_NS, "szrgw:MIS");
            Element filters = doc.createElementNS(SZRGW_NS, "szrgw:Filters");
            mis.appendChild(filters);
            Element target = doc.createElementNS(SZRGW_NS, "szrgw:Target");
            mis.appendChild(target);
            Element friendlyName = doc.createElementNS(SZRGW_NS, "szrgw:OAFriendlyName");
            mis.appendChild(friendlyName);
            getIdentityLink.appendChild(mis);

            //            TODO fetch data from oa params
            //             String moasessionid = req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID);
            //             moasessionid = StringEscapeUtils.escapeHtml(moasessionid);
            //              AuthenticationSession moasession = AuthenticationSessionStoreage.getSession(moasessionid);
            //             OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moasession.getPublicOAURLPrefix());
            //             if (oaParam == null)
            //                   throw new AuthenticationException("auth.00", new Object[] { moasession.getPublicOAURLPrefix() });
            //              Text text = doc.createTextNode(oaParam.getFriendlyName());
        }

        return doc;
    } catch (ParserConfigurationException e) {
        throw new SZRGWClientException(e);
    } /*catch (CertificateEncodingException e) {
       throw new SZRGWClientException(e);
      }*/

}

From source file:de.mpg.escidoc.services.transformation.Util.java

/**
 * queries the framework with the given request
 * @param request// w  ww . j  a v a2 s  . com
 * @return XML document returned by the framework
 * @throws Exception
 */
public static Document queryFramework(String request) throws Exception {
    final String FRAMEWORK_PROPERTY = "escidoc.framework_access.framework.url";
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactoryImpl.newInstance();
    DocumentBuilder documentBuilder;
    String url = null;
    String frameworkUrl = null;
    Document document = null;
    try {
        frameworkUrl = PropertyReader.getProperty(FRAMEWORK_PROPERTY);
        url = frameworkUrl + request;

        if (logger.isDebugEnabled())
            logger.debug("queryFramework: (" + url.toString() + ")");

        documentBuilderFactory.setNamespaceAware(true);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.newDocument();

        HttpClient client = new HttpClient();
        GetMethod getMethod = new GetMethod(url);
        int statusCode = client.executeMethod(getMethod);
        if (statusCode == 200) {
            InputStream input = getMethod.getResponseBodyAsStream();
            document = documentBuilder.parse(input);
        } else {
            throw new RuntimeException("Error requesting <" + url + ">");
        }
    } catch (IOException e) {
        logger.error("IOException when getting Property <" + FRAMEWORK_PROPERTY + ">\n"
                + "Or reading document from URL <" + url, e);
        throw e;
    } catch (URISyntaxException e) {
        logger.error("Invalid URL when getting Property: <" + FRAMEWORK_PROPERTY + ">", e);
        throw e;
    } catch (ParserConfigurationException e) {
        logger.error("Parser configuration error", e);
        throw e;
    } catch (SAXException e) {
        logger.error("Could not parse returned XML", e);
        throw e;
    }

    return document;
}

From source file:be.fedict.eid.idp.sp.protocol.ws_federation.AuthenticationResponseProcessor.java

/**
 * Process the incoming WS-Federation response.
 * //from w  w w. j  av  a2s .  com
 * @param recipient
 *            recipient, should match SAML v2.0 assertions's
 *            AudienceRestriction
 * @param context
 *            optional expected context
 * @param requiresResponseSignature
 *            do we expect a signature on the response or not, or
 *            <code>null</code> if to be retrieved from the
 *            {@link AuthenticationResponseService}.
 * @param request
 *            the HTTP servlet request that holds the SAML2 response.
 * @return the {@link be.fedict.eid.idp.common.saml2.AuthenticationResponse}
 * @throws AuthenticationResponseProcessorException
 *             case something went wrong
 */
public AuthenticationResponse process(String recipient, String context, Boolean requiresResponseSignature,
        HttpServletRequest request) throws AuthenticationResponseProcessorException {

    DateTime now = new DateTime();
    SecretKey secretKey = null;
    PrivateKey privateKey = null;
    int maxOffset = 5;
    boolean expectAssertionSigned = null != requiresResponseSignature ? requiresResponseSignature : false;
    ValidationService validationService = null;

    if (null != this.service) {
        secretKey = this.service.getAttributeSecretKey();
        privateKey = this.service.getAttributePrivateKey();
        maxOffset = this.service.getMaximumTimeOffset();
        expectAssertionSigned = this.service.requiresResponseSignature();
        validationService = this.service.getValidationService();
    }

    // force UTF8 encoding!
    try {
        request.setCharacterEncoding("UTF8");
    } catch (UnsupportedEncodingException e) {
        throw new AuthenticationResponseProcessorException(e);
    }

    // check wa
    String wa = request.getParameter("wa");
    if (null == wa) {
        throw new AuthenticationResponseProcessorException("Missing \"wa\" param.");
    }
    if (!wa.equals("wsignin1.0")) {
        throw new AuthenticationResponseProcessorException("Unexpected value for \"wa\" param.");
    }

    // validate optional ctx
    validateContext(context, request.getParameter("wctx"));

    // get wresult
    String wresult = request.getParameter("wresult");
    LOG.debug("wresult=\"" + wresult + "\"");

    if (null == wresult) {
        throw new AuthenticationResponseProcessorException("Missing \"wresult\" param.");
    }
    Document responseDocument = Saml2Util.parseDocument(wresult);
    RequestSecurityTokenResponseCollection rstCollections = Saml2Util
            .unmarshall(responseDocument.getDocumentElement());

    if (rstCollections.getRequestSecurityTokenResponses().size() != 1) {
        throw new AuthenticationResponseProcessorException("Expected exactly 1 RequestSecurityTokenResponse");
    }

    RequestSecurityTokenResponse rstResponse = rstCollections.getRequestSecurityTokenResponses().get(0);

    // context
    validateContext(context, rstResponse.getContext());

    // tokentype
    validateTokenType(rstResponse);

    // requesttype
    validateRequestType(rstResponse);

    // keytype
    validateKeyType(rstResponse);

    // validate security token
    Assertion assertion = validateSecurityToken(rstResponse);

    // validate assertion
    AuthenticationResponse authenticationResponse;
    try {
        authenticationResponse = Saml2Util.validateAssertion(assertion, now, maxOffset, recipient, recipient,
                null, secretKey, privateKey);
    } catch (AssertionValidationException e) {
        throw new AuthenticationResponseProcessorException(e);
    }

    // check if SP expects a signature and if there is one
    if (null == assertion.getSignature() && expectAssertionSigned) {
        throw new AuthenticationResponseProcessorException("Expected a signed assertion but was not so! ");
    }

    // validate assertion's signature if any
    if (null != assertion.getSignature()) {
        try {
            // fix for recent versions of Apache xmlsec
            assertion.getDOM().setIdAttribute("ID", true);

            List<X509Certificate> certificateChain = Saml2Util.validateSignature(assertion.getSignature());

            if (null != validationService) {
                // have to reparse the document here
                NodeList assertionNodeList = Saml2Util.parseDocument(wresult)
                        .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Assertion");
                LOG.debug("number of SAML2 assertions: " + assertionNodeList.getLength());
                if (1 != assertionNodeList.getLength()) {
                    throw new AuthenticationResponseProcessorException("missing SAML2 Assertion");
                }
                Element assertionElement = (Element) assertionNodeList.item(0);

                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document tokenDocument = documentBuilder.newDocument();
                Node assertionTokenNode = tokenDocument.importNode(assertionElement, true);
                tokenDocument.appendChild(assertionTokenNode);

                String validationServiceLocation = validationService.getLocation();
                String expectedAudience = validationService.getExpectedAudience();
                SecurityTokenServiceClient securityTokenServiceClient = new SecurityTokenServiceClient(
                        validationServiceLocation);
                securityTokenServiceClient.validateToken(tokenDocument.getDocumentElement(), expectedAudience);
            }
            if (null != this.service) {
                this.service.validateServiceCertificate(authenticationResponse.getAuthenticationPolicy(),
                        certificateChain);
            }

        } catch (CertificateException e) {
            throw new AuthenticationResponseProcessorException(e);
        } catch (ValidationException e) {
            throw new AuthenticationResponseProcessorException(e);
        } catch (Exception e) {

            if ("javax.ejb.EJBException".equals(e.getClass().getName())) {
                Exception exception;
                try {
                    Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException",
                            new Class[] {});
                    exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {});
                } catch (Exception e2) {
                    LOG.debug("error: " + e.getMessage(), e);
                    throw new AuthenticationResponseProcessorException(
                            "error retrieving the root cause: " + e2.getMessage());
                }

                throw new AuthenticationResponseProcessorException("Validation exception: "
                        + (null != exception ? exception.getMessage() : e.getMessage()));
            }

            throw new AuthenticationResponseProcessorException(e);
        }
    }

    return authenticationResponse;
}

From source file:com.bluexml.xforms.actions.GetAction.java

/**
 * Gets the instance for forms that do not require calling the controller because of how simple
 * their instance is. The controller acts as a bridge to the mapping; when there's no
 * information to extract from the mapping, a better option is to serve the instance here.
 * //from   w  ww  . ja v a2 s  .  com
 * @param dataType
 * @param formType
 * @return the instance
 */
private Document getInstanceListOrSelector(String dataType, FormTypeEnum formType) {
    DocumentBuilder docBuilder = null;
    try {
        docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        if (logger.isErrorEnabled()) {
            logger.error("Failed to obtain a document builder", e);
        }
        return null;
    }
    Document instance = docBuilder.newDocument();
    Element rootElement = instance.createElement(dataType);
    instance.appendChild(rootElement);
    if (formType == FormTypeEnum.SELECTOR) {
        // the data type in the combo box
        Element sideData = instance.createElement(MsgId.INT_INSTANCE_SIDE_DATATYPE.getText());
        sideData.setTextContent(dataType);
        rootElement.appendChild(sideData);
        return instance;
    } else if (formType == FormTypeEnum.LIST) {
        // the id of the object whose Edit button was clicked
        Element editedid = instance.createElement(MsgId.INT_INSTANCE_SIDEEDIT.getText());
        rootElement.appendChild(editedid);
        return instance;
    }

    return null; // we never reach here
}

From source file:com.photon.phresco.plugins.JavaPackage.java

private void updatemainClassName() throws MojoExecutionException {
    try {//from ww  w  .ja  v a 2 s  .  c om
        if (StringUtils.isEmpty(mainClassName)) {
            return;
        }
        File pom = project.getFile();
        List<Element> configList = new ArrayList<Element>();
        PomProcessor pomprocessor = new PomProcessor(pom);
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element archive = doc.createElement(JAVA_POM_ARCHIVE);
        Element manifest = doc.createElement(JAVA_POM_MANIFEST);
        Element addClasspath = doc.createElement(JAVA_POM_ADD_PATH);
        addClasspath.setTextContent("true");
        manifest.appendChild(addClasspath);
        Element mainClass = doc.createElement(JAVA_POM_MAINCLASS);
        mainClass.setTextContent(mainClassName);
        manifest.appendChild(addClasspath);
        manifest.appendChild(mainClass);
        archive.appendChild(manifest);
        configList.add(archive);

        pomprocessor.addConfiguration(JAR_PLUGIN_GROUPID, JAR_PLUGIN_ARTIFACT_ID, configList, false);
        pomprocessor.save();
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}