Example usage for org.w3c.dom Element getOwnerDocument

List of usage examples for org.w3c.dom Element getOwnerDocument

Introduction

In this page you can find the example usage for org.w3c.dom Element getOwnerDocument.

Prototype

public Document getOwnerDocument();

Source Link

Document

The Document object associated with this node.

Usage

From source file:org.codehaus.grepo.core.config.GenericRepositoryBeanDefinitionParser.java

/**
 * {@inheritDoc}/*from   ww w  . ja  v a  2 s . c  o  m*/
 */
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
    Object source = parserContext.extractSource(element);
    GenericRepositoryConfigContext configContext = new GenericRepositoryConfigContext(element);

    // init bean defintion parse delegate...
    BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(parserContext.getReaderContext());
    delegate.initDefaults(element.getOwnerDocument().getDocumentElement());

    BeanDefinitionBuilder builder = BeanDefinitionParserHelper.createBuilderFromConfigContext(configContext,
            source, defaultGenericRepositoryFactoryType);

    delegate.parsePropertyElements(configContext.getElement(), builder.getRawBeanDefinition());

    builder.addPropertyValue(GenericRepositoryConfigContext.PROXY_CLASS_PROPERTY,
            configContext.getProxyClass());

    return builder.getBeanDefinition();
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static void setQNameAttribute(Element element, String attributeName, QName attributeValue,
        Element definitionElement) {
    Document doc = element.getOwnerDocument();
    Attr attr = doc.createAttribute(attributeName);
    setQNameAttribute(element, attr, attributeValue, definitionElement);
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static void setQNameAttribute(Element element, QName attributeName, QName attributeValue,
        Element definitionElement) {
    Document doc = element.getOwnerDocument();
    Attr attr = doc.createAttributeNS(attributeName.getNamespaceURI(), attributeName.getLocalPart());
    String namePrefix = lookupOrCreateNamespaceDeclaration(element, attributeName.getNamespaceURI(),
            attributeName.getPrefix(), element, true);
    attr.setPrefix(namePrefix);/*from w  ww . j a v  a  2  s .com*/
    setQNameAttribute(element, attr, attributeValue, definitionElement);
}

From source file:org.codehaus.grepo.core.config.GenericRepositoryFactoryBeanDefinitionParser.java

/**
 * {@inheritDoc}/* w w  w  .  j a v  a  2 s.  c o m*/
 */
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
    Object source = parserContext.extractSource(element);
    GenericRepositoryConfigContext configContext = new GenericRepositoryConfigContext(element);

    // init bean defintion parse delegate...
    BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(parserContext.getReaderContext());
    delegate.initDefaults(element.getOwnerDocument().getDocumentElement());

    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition().setAbstract(true);
    builder.getRawBeanDefinition().setSource(source);

    if (configContext.hasClazz()) {
        builder.getRawBeanDefinition().setBeanClassName(configContext.getClazz());
    } else {
        // no 'class' attribute is set, so use default bean class...
        builder.getRawBeanDefinition().setBeanClass(defaultGenericRepositoryFactoryType);
    }

    delegate.parsePropertyElements(element, builder.getRawBeanDefinition());

    return builder.getBeanDefinition();
}

From source file:cz.incad.kramerius.rest.api.k5.client.search.SearchResource.java

public static void replacePidsInDOM(Element docE) {
    String[] apiReplace = KConfiguration.getInstance().getAPIPIDReplace();
    for (String k : apiReplace) {
        if (k.equals("PID"))
            continue; // already replaced
        Element foundElm = findSolrElement(docE, k);
        if (foundElm != null) {

            if (foundElm.getNodeName().equals("str")) {
                String value = SOLRUtils.value(foundElm.getTextContent(), String.class);
                if (value != null && (value.indexOf("/@") > 0)) {
                    value = value.replace("/@", "@");
                    foundElm.setTextContent(value);
                }//  w  w w.  ja v  a  2 s.c o m
            } else if (foundElm.getNodeName().equals("arr")) {
                List<String> array = SOLRUtils.array(docE, k, String.class);
                List<String> newArray = new ArrayList<String>();
                for (String value : array) {
                    value = value.replace("/@", "@");
                    newArray.add(value);
                }

                docE.removeChild(foundElm);
                Element newArrElm = SOLRUtils.arr(foundElm.getOwnerDocument(), k, newArray);
                docE.appendChild(newArrElm);
            } else {
                LOGGER.warning("skipping object type '" + foundElm.getNodeName() + "'");
            }

        }
    }

}

From source file:au.com.identityconcepts.shibboleth.test.TestCaseBase.java

/**
 * Asserts a given XMLObject is equal to an expected DOM. The XMLObject is marshalled and the resulting DOM object
 * is compared against the expected DOM object for equality.
 * //from w w  w  .ja  v  a2  s .  c o m
 * @param failMessage the message to display if the DOMs are not equal
 * @param expectedDOM the expected DOM
 * @param xmlObject the XMLObject to be marshalled and compared against the expected DOM
 */
public void assertEquals(String failMessage, Document expectedDOM, XMLObject xmlObject) {
    Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
    if (marshaller == null) {
        fail("Unable to locate marshaller for " + xmlObject.getElementQName()
                + " can not perform equality check assertion");
    }

    try {
        Element generatedDOM = marshaller.marshall(xmlObject, parser.newDocument());
        if (log.isDebugEnabled()) {
            log.debug("Marshalled DOM was " + XMLHelper.nodeToString(generatedDOM));
        }
        assertXMLEqual(failMessage, expectedDOM, generatedDOM.getOwnerDocument());
    } catch (Exception e) {
        log.error("Marshalling failed with the following error:", e);
        fail("Marshalling failed with the following error: " + e);
    }
}

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

/**
 * Gets a identity link.//from  w w  w.  j a 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:com.evolveum.midpoint.prism.lex.dom.DomLexicalWriter.java

public Element serializeUnderElement(RootXNode rootxnode, Element parentElement) throws SchemaException {
    initializeWithExistingDocument(parentElement.getOwnerDocument());
    return serializeInternal(rootxnode, parentElement);
}

From source file:org.apache.metron.dataloads.taxii.TaxiiHandler.java

/**
 * The action to be performed by this timer task.
 *//*from  w w  w . j  av a 2  s  .  c o  m*/
@Override
public void run() {
    if (inProgress) {
        return;
    }
    Date ts = new Date();
    LOG.info("Polling..." + new SimpleDateFormat().format(ts));
    try {
        inProgress = true;
        // Prepare the message to send.
        String sessionID = MessageHelper.generateMessageId();
        PollRequest request = messageFactory.get().createPollRequest().withMessageId(sessionID)
                .withCollectionName(collection);
        if (subscriptionId != null) {
            request = request.withSubscriptionID(subscriptionId);
        } else {
            request = request.withPollParameters(messageFactory.get().createPollParametersType());
        }
        if (beginTime != null) {
            Calendar gc = GregorianCalendar.getInstance();
            gc.setTime(beginTime);
            XMLGregorianCalendar gTime = null;
            try {
                gTime = DatatypeFactory.newInstance().newXMLGregorianCalendar((GregorianCalendar) gc)
                        .normalize();
            } catch (DatatypeConfigurationException e) {
                LOG.error("Unable to set the begin time", e);
            }
            gTime.setFractionalSecond(null);
            LOG.info("Begin Time: " + gTime);
            request.setExclusiveBeginTimestamp(gTime);
        }

        try {
            PollResponse response = call(request, PollResponse.class);
            LOG.info("Got Poll Response with " + response.getContentBlocks().size() + " blocks");
            int numProcessed = 0;
            long avgTimeMS = 0;
            long timeStartedBlock = System.currentTimeMillis();
            for (ContentBlock block : response.getContentBlocks()) {
                AnyMixedContentType content = block.getContent();
                for (Object o : content.getContent()) {
                    numProcessed++;
                    long timeS = System.currentTimeMillis();
                    String xml = null;
                    if (o instanceof Element) {
                        Element element = (Element) o;
                        xml = getStringFromDocument(element.getOwnerDocument());
                        if (LOG.isDebugEnabled() && Math.random() < 0.01) {
                            LOG.debug("Random Stix doc: " + xml);
                        }
                        for (LookupKV<ThreatIntelKey, ThreatIntelValue> kv : extractor.extract(xml)) {
                            String indicatorType = kv.getValue().getMetadata().get("indicator-type");
                            TableInfo tableInfo = tableMap.get(indicatorType);
                            boolean persisted = false;
                            if (tableInfo != null) {
                                kv.getValue().getMetadata().put("source_type", "taxii");
                                kv.getValue().getMetadata().put("taxii_url", endpoint.toString());
                                kv.getValue().getMetadata().put("taxii_collection", collection);
                                Put p = converter.toPut(tableInfo.getColumnFamily(), kv.getKey(),
                                        kv.getValue());
                                HTableInterface table = getTable(tableInfo);
                                table.put(p);
                                persisted = true;
                            }
                            LOG.info("Found Threat Intel: " + persisted + ", " + kv.getKey() + " => "
                                    + kv.getValue());
                        }
                    }
                    avgTimeMS += System.currentTimeMillis() - timeS;
                }
                if ((numProcessed + 1) % 100 == 0) {
                    LOG.info("Processed " + numProcessed + " in "
                            + (System.currentTimeMillis() - timeStartedBlock) + " ms, avg time: "
                            + avgTimeMS / content.getContent().size());
                    timeStartedBlock = System.currentTimeMillis();
                    avgTimeMS = 0;
                    numProcessed = 0;
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            throw new RuntimeException("Unable to make request", e);
        }
    } finally {
        inProgress = false;
        beginTime = ts;
    }
}

From source file:be.fedict.eid.idp.protocol.saml2.AbstractSAML2MetadataHttpServlet.java

private void writeMetadata(HttpServletRequest request, IdentityProviderConfiguration configuration,
        OutputStream outputStream)

        throws ServletException, TransformerException, IOException {

    IdPIdentity identity = configuration.findIdentity();

    // Add a descriptor for our node (the SAMLv2 Entity).
    EntityDescriptor entityDescriptor = getEntityDescriptor(request, configuration);

    // Marshall & sign the entity descriptor.
    Element element;
    if (null != identity) {

        LOG.debug("sign SAML2 Metadata");
        element = Saml2Util.signAsElement(entityDescriptor, entityDescriptor, identity.getPrivateKeyEntry());
    } else {/*from w  ww  .jav a  2s  . c  om*/

        LOG.warn("SAML2 Metadata NOT signed!");
        element = Saml2Util.marshall(entityDescriptor);
    }

    Saml2Util.writeDocument(element.getOwnerDocument(), outputStream);
}