Example usage for org.w3c.dom Element getPrefix

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

Introduction

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

Prototype

public String getPrefix();

Source Link

Document

The namespace prefix of this node, or null if it is unspecified.

Usage

From source file:dk.dbc.rawrepo.oai.OAIWorker.java

private void fixXmlNamespacePrefix(Element element, String metadataPrefix, String namespaceURI)
        throws DOMException {
    String prefix = null;/*  w w w.  j a  v  a2 s.c  om*/
    if (namespaceURI.equals(element.getNamespaceURI())) {
        prefix = element.getPrefix();
        if (prefix == null) {
            prefix = "";
        }
        element.setPrefix(metadataPrefix);
    }
    for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            fixXmlNamespacePrefix((Element) child, metadataPrefix, namespaceURI);
        }
    }
    if (prefix != null) {
        element.removeAttribute(prefix.isEmpty() ? "xmlns" : ("xmlns:" + prefix));
    }
}

From source file:com.msopentech.odatajclient.engine.data.AbstractODataBinder.java

protected ODataPrimitiveValue fromPrimitiveValueElement(final Element prop, final EdmType edmType) {
    final ODataPrimitiveValue value;
    if (edmType != null && edmType.getSimpleType().isGeospatial()) {
        final Element geoProp = ODataConstants.PREFIX_GML.equals(prop.getPrefix()) ? prop
                : (Element) XMLUtils.getChildNodes(prop, Node.ELEMENT_NODE).get(0);
        value = client.getGeospatialValueBuilder().setType(edmType.getSimpleType()).setTree(geoProp).build();
    } else {/*from   w w w  .  j a v  a 2 s  . c om*/
        value = client.getPrimitiveValueBuilder().setType(edmType == null ? null : edmType.getSimpleType())
                .setText(prop.getTextContent()).build();
    }
    return value;
}

From source file:de.betterform.xml.xforms.CustomElementFactory.java

/**
 * Returns true if the given DOM Element matches a configured custom
 * element.//from  www. java2s.  c  o  m
 * 
 * @param element
 *            The DOM Element to investigate.
 * @return Whether the element matches a custom element or not.
 * 
 * @throws XFormsException
 *             In case of MustUnderstand Module failure.
 */
public boolean isCustomElement(Element element) throws XFormsException {

    if (this.noCustomElements) {
        //no custom elements configured
        return false;
    }

    //key to search the Map for a custom element
    String key = getKeyForElement(element);

    if (ELEMENTS.containsKey(key)) {
        //a match was found
        return true;
    }

    //if the element is not recognized but it has a
    //mustUnderstand attribute, throw an exception to
    //signal error according to the spec
    if (element.hasAttributeNS(NamespaceConstants.XFORMS_NS, MUST_UNDERSTAND_ATTRIBUTE)) {

        String elementId = element.getPrefix() + ":" + element.getLocalName();

        throw new XFormsException("MustUnderstand Module failure at element " + elementId);
    }

    //no matching configuration was found
    return false;
}

From source file:be.fedict.eid.applet.service.signer.facets.XAdESXLSignatureFacet.java

public void postSign(Element signatureElement, List<X509Certificate> signingCertificateChain) {
    LOG.debug("XAdES-X-L post sign phase");
    for (X509Certificate xCert : signingCertificateChain) {
        LOG.debug("Cert chain: " + xCert.getSubjectX500Principal());
    }/*from w w w. j a v  a  2 s .  co  m*/

    // check for XAdES-BES
    Element qualifyingPropertiesElement = (Element) findSingleNode(signatureElement,
            "ds:Object/xades:QualifyingProperties");
    if (null == qualifyingPropertiesElement) {
        throw new IllegalArgumentException("no XAdES-BES extension present");
    }

    // create basic XML container structure
    Document document = signatureElement.getOwnerDocument();
    String xadesNamespacePrefix;
    if (null != qualifyingPropertiesElement.getPrefix()) {
        xadesNamespacePrefix = qualifyingPropertiesElement.getPrefix() + ":";
    } else {
        xadesNamespacePrefix = "";
    }
    Element unsignedPropertiesElement = (Element) findSingleNode(qualifyingPropertiesElement,
            "xades:UnsignedProperties");
    if (null == unsignedPropertiesElement) {
        unsignedPropertiesElement = document.createElementNS(XADES_NAMESPACE,
                xadesNamespacePrefix + "UnsignedProperties");
        qualifyingPropertiesElement.appendChild(unsignedPropertiesElement);
    }
    Element unsignedSignaturePropertiesElement = (Element) findSingleNode(unsignedPropertiesElement,
            "xades:UnsignedSignatureProperties");
    if (null == unsignedSignaturePropertiesElement) {
        unsignedSignaturePropertiesElement = document.createElementNS(XADES_NAMESPACE,
                xadesNamespacePrefix + "UnsignedSignatureProperties");
        unsignedPropertiesElement.appendChild(unsignedSignaturePropertiesElement);
    }

    // create the XAdES-T time-stamp
    Node signatureValueNode = findSingleNode(signatureElement, "ds:SignatureValue");
    RevocationData tsaRevocationDataXadesT = new RevocationData();
    LOG.debug("creating XAdES-T time-stamp");
    XAdESTimeStampType signatureTimeStamp = createXAdESTimeStamp(Collections.singletonList(signatureValueNode),
            tsaRevocationDataXadesT, this.c14nAlgoId, this.timeStampService, this.objectFactory,
            this.xmldsigObjectFactory);

    // marshal the XAdES-T extension
    try {
        this.marshaller.marshal(this.objectFactory.createSignatureTimeStamp(signatureTimeStamp),
                unsignedSignaturePropertiesElement);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // xadesv141::TimeStampValidationData
    if (tsaRevocationDataXadesT.hasRevocationDataEntries()) {
        ValidationDataType validationData = createValidationData(tsaRevocationDataXadesT);
        try {
            this.marshaller.marshal(this.xades141ObjectFactory.createTimeStampValidationData(validationData),
                    unsignedSignaturePropertiesElement);
        } catch (JAXBException e) {
            throw new RuntimeException("JAXB error: " + e.getMessage(), e);
        }
    }

    if (null == this.revocationDataService) {
        /*
         * Without revocation data service we cannot construct the XAdES-C
         * extension.
         */
        return;
    }

    // XAdES-C: complete certificate refs
    CompleteCertificateRefsType completeCertificateRefs = this.objectFactory
            .createCompleteCertificateRefsType();
    CertIDListType certIdList = this.objectFactory.createCertIDListType();
    completeCertificateRefs.setCertRefs(certIdList);
    List<CertIDType> certIds = certIdList.getCert();
    for (int certIdx = 1; certIdx < signingCertificateChain.size(); certIdx++) {
        /*
         * We skip the signing certificate itself according to section
         * 4.4.3.2 of the XAdES 1.4.1 specification.
         */
        X509Certificate certificate = signingCertificateChain.get(certIdx);
        CertIDType certId = XAdESSignatureFacet.getCertID(certificate, this.objectFactory,
                this.xmldsigObjectFactory, this.digestAlgorithm, false);
        certIds.add(certId);
    }

    // XAdES-C: complete revocation refs
    CompleteRevocationRefsType completeRevocationRefs = this.objectFactory.createCompleteRevocationRefsType();
    RevocationData revocationData = this.revocationDataService.getRevocationData(signingCertificateChain);
    if (revocationData.hasCRLs()) {
        CRLRefsType crlRefs = this.objectFactory.createCRLRefsType();
        completeRevocationRefs.setCRLRefs(crlRefs);
        List<CRLRefType> crlRefList = crlRefs.getCRLRef();

        List<byte[]> crls = revocationData.getCRLs();
        for (byte[] encodedCrl : crls) {
            CRLRefType crlRef = this.objectFactory.createCRLRefType();
            crlRefList.add(crlRef);
            X509CRL crl;
            try {
                crl = (X509CRL) this.certificateFactory.generateCRL(new ByteArrayInputStream(encodedCrl));
            } catch (CRLException e) {
                throw new RuntimeException("CRL parse error: " + e.getMessage(), e);
            }

            CRLIdentifierType crlIdentifier = this.objectFactory.createCRLIdentifierType();
            crlRef.setCRLIdentifier(crlIdentifier);
            String issuerName;
            try {
                issuerName = PrincipalUtil.getIssuerX509Principal(crl).getName().replace(",", ", ");
            } catch (CRLException e) {
                throw new RuntimeException("CRL encoding error: " + e.getMessage(), e);
            }
            crlIdentifier.setIssuer(issuerName);
            crlIdentifier.setIssueTime(this.datatypeFactory
                    .newXMLGregorianCalendar(new DateTime(crl.getThisUpdate()).toGregorianCalendar()));
            crlIdentifier.setNumber(getCrlNumber(crl));

            DigestAlgAndValueType digestAlgAndValue = XAdESSignatureFacet.getDigestAlgAndValue(encodedCrl,
                    this.objectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
            crlRef.setDigestAlgAndValue(digestAlgAndValue);
        }
    }
    if (revocationData.hasOCSPs()) {
        OCSPRefsType ocspRefs = this.objectFactory.createOCSPRefsType();
        completeRevocationRefs.setOCSPRefs(ocspRefs);
        List<OCSPRefType> ocspRefList = ocspRefs.getOCSPRef();
        List<byte[]> ocsps = revocationData.getOCSPs();
        for (byte[] ocsp : ocsps) {
            OCSPRefType ocspRef = this.objectFactory.createOCSPRefType();
            ocspRefList.add(ocspRef);

            DigestAlgAndValueType digestAlgAndValue = XAdESSignatureFacet.getDigestAlgAndValue(ocsp,
                    this.objectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
            ocspRef.setDigestAlgAndValue(digestAlgAndValue);

            OCSPIdentifierType ocspIdentifier = this.objectFactory.createOCSPIdentifierType();
            ocspRef.setOCSPIdentifier(ocspIdentifier);
            OCSPResp ocspResp;
            try {
                ocspResp = new OCSPResp(ocsp);
            } catch (IOException e) {
                throw new RuntimeException("OCSP decoding error: " + e.getMessage(), e);
            }
            Object ocspResponseObject;
            try {
                ocspResponseObject = ocspResp.getResponseObject();
            } catch (OCSPException e) {
                throw new RuntimeException("OCSP error: " + e.getMessage(), e);
            }
            BasicOCSPResp basicOcspResp = (BasicOCSPResp) ocspResponseObject;
            Date producedAt = basicOcspResp.getProducedAt();
            ocspIdentifier.setProducedAt(this.datatypeFactory
                    .newXMLGregorianCalendar(new DateTime(producedAt).toGregorianCalendar()));

            ResponderIDType responderId = this.objectFactory.createResponderIDType();
            ocspIdentifier.setResponderID(responderId);
            RespID respId = basicOcspResp.getResponderId();
            ResponderID ocspResponderId = respId.toASN1Object();
            DERTaggedObject derTaggedObject = (DERTaggedObject) ocspResponderId.toASN1Object();
            if (2 == derTaggedObject.getTagNo()) {
                ASN1OctetString keyHashOctetString = (ASN1OctetString) derTaggedObject.getObject();
                responderId.setByKey(keyHashOctetString.getOctets());
            } else {
                X509Name name = X509Name.getInstance(derTaggedObject.getObject());
                responderId.setByName(name.toString());
            }
        }
    }

    // marshal XAdES-C
    NodeList unsignedSignaturePropertiesNodeList = ((Element) qualifyingPropertiesElement)
            .getElementsByTagNameNS(XADES_NAMESPACE, "UnsignedSignatureProperties");
    Node unsignedSignaturePropertiesNode = unsignedSignaturePropertiesNodeList.item(0);
    try {
        this.marshaller.marshal(this.objectFactory.createCompleteCertificateRefs(completeCertificateRefs),
                unsignedSignaturePropertiesNode);
        this.marshaller.marshal(this.objectFactory.createCompleteRevocationRefs(completeRevocationRefs),
                unsignedSignaturePropertiesNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // XAdES-X Type 1 timestamp
    List<Node> timeStampNodesXadesX1 = new LinkedList<Node>();
    timeStampNodesXadesX1.add(signatureValueNode);
    Node signatureTimeStampNode = findSingleNode(unsignedSignaturePropertiesNode, "xades:SignatureTimeStamp");
    timeStampNodesXadesX1.add(signatureTimeStampNode);
    Node completeCertificateRefsNode = findSingleNode(unsignedSignaturePropertiesNode,
            "xades:CompleteCertificateRefs");
    timeStampNodesXadesX1.add(completeCertificateRefsNode);
    Node completeRevocationRefsNode = findSingleNode(unsignedSignaturePropertiesNode,
            "xades:CompleteRevocationRefs");
    timeStampNodesXadesX1.add(completeRevocationRefsNode);

    RevocationData tsaRevocationDataXadesX1 = new RevocationData();
    LOG.debug("creating XAdES-X time-stamp");
    XAdESTimeStampType timeStampXadesX1 = createXAdESTimeStamp(timeStampNodesXadesX1, tsaRevocationDataXadesX1,
            this.c14nAlgoId, this.timeStampService, this.objectFactory, this.xmldsigObjectFactory);
    ValidationDataType timeStampXadesX1ValidationData;
    if (tsaRevocationDataXadesX1.hasRevocationDataEntries()) {
        timeStampXadesX1ValidationData = createValidationData(tsaRevocationDataXadesX1);
    } else {
        timeStampXadesX1ValidationData = null;
    }

    // marshal XAdES-X
    try {
        this.marshaller.marshal(this.objectFactory.createSigAndRefsTimeStamp(timeStampXadesX1),
                unsignedSignaturePropertiesNode);
        if (null != timeStampXadesX1ValidationData) {
            this.marshaller.marshal(
                    this.xades141ObjectFactory.createTimeStampValidationData(timeStampXadesX1ValidationData),
                    unsignedSignaturePropertiesNode);
        }
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // XAdES-X-L
    CertificateValuesType certificateValues = this.objectFactory.createCertificateValuesType();
    List<Object> certificateValuesList = certificateValues.getEncapsulatedX509CertificateOrOtherCertificate();
    for (X509Certificate certificate : signingCertificateChain) {
        EncapsulatedPKIDataType encapsulatedPKIDataType = this.objectFactory.createEncapsulatedPKIDataType();
        try {
            encapsulatedPKIDataType.setValue(certificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
        }
        certificateValuesList.add(encapsulatedPKIDataType);
    }
    RevocationValuesType revocationValues = createRevocationValues(revocationData);

    // marshal XAdES-X-L
    try {
        this.marshaller.marshal(this.objectFactory.createCertificateValues(certificateValues),
                unsignedSignaturePropertiesNode);
        this.marshaller.marshal(this.objectFactory.createRevocationValues(revocationValues),
                unsignedSignaturePropertiesNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }
}

From source file:iristk.flow.FlowCompiler.java

private String newState(Element elem) {
    if (elem.getPrefix().equals("this")) {
        return "new " + elem.getLocalName() + "()";
    }//  w w  w  .j a v a  2 s .  co m
    for (Var var : flowXml.getVariables()) {
        if (var.getName().equals(elem.getPrefix()))
            return elem.getPrefix() + ".new " + elem.getLocalName() + "()";
    }
    for (Param param : flowXml.getParameters()) {
        if (param.getName().equals(elem.getPrefix()))
            return elem.getPrefix() + ".new " + elem.getLocalName() + "()";
    }
    return "new " + elem.getNamespaceURI() + "." + elem.getLocalName() + "()";
}

From source file:iristk.flow.FlowCompiler.java

protected void printAction(Object action, Object parent, String exprContext) throws FlowCompilerException {
    if (action instanceof JAXBElement<?>)
        action = ((JAXBElement<?>) action).getValue();
    printLocation(action);/*from   w  w  w .j  a va2  s . co m*/
    if (action instanceof iristk.xml.flow.Goto) {
        iristk.xml.flow.Goto gotoAction = (iristk.xml.flow.Goto) action;
        if (exprContext != null)
            throw new FlowCompilerException("<goto> not allowed in expression",
                    gotoAction.sourceLocation().getLineNumber());
        String stateVar = "";
        if (gotoAction.getState() != null) {
            if (!stateExists(gotoAction.getState()))
                throw new FlowCompilerException("State " + gotoAction.getState() + " does not exist",
                        gotoAction.sourceLocation().getLineNumber());
            stateVar = varname("state");
            code.println(stateClass(gotoAction.getState()) + " " + stateVar + " = "
                    + newState(gotoAction.getState()) + ";");
            printSetStateParameters(stateVar,
                    getParameters(gotoAction.getOtherAttributes(), gotoAction.getContent(), gotoAction));
        } else if (gotoAction.getExpr() != null) {
            stateVar = gotoAction.getExpr();
        } else {
            throw new FlowCompilerException("Goto must either have a 'state' or 'expr' attribute",
                    gotoAction.sourceLocation().getLineNumber());
        }
        code.println(
                "flowThread.gotoState(" + stateVar + ", currentState, new FlowEventInfo(currentState, event, "
                        + location(flowXml.getLocation(action)) + "));");
        code.println("eventResult = EVENT_ABORTED;");
        code.println("break EXECUTION;");
    } else if (action instanceof iristk.xml.flow.Run) {
        iristk.xml.flow.Run runAction = (iristk.xml.flow.Run) action;
        if (exprContext != null)
            throw new FlowCompilerException("<run> not allowed in expression",
                    runAction.sourceLocation().getLineNumber());
        String stateVar = varname("state");
        code.println(stateClass(runAction.getState()) + " " + stateVar + " = " + newState(runAction.getState())
                + ";");
        printSetStateParameters(stateVar,
                getParameters(runAction.getOtherAttributes(), runAction.getContent(), runAction));
        code.println("FlowRunner.FlowThread " + stateVar + "Thread = flowThread.runState(" + stateVar
                + ", new FlowEventInfo(currentState, event, " + location(flowXml.getLocation(action)) + "));");
    } else if (action instanceof iristk.xml.flow.Call) {
        iristk.xml.flow.Call callAction = (iristk.xml.flow.Call) action;
        if (exprContext != null)
            throw new FlowCompilerException("<call> not allowed in expression",
                    callAction.sourceLocation().getLineNumber());
        String stateVar = varname("state");
        code.println(stateClass(callAction.getState()) + " " + stateVar + " = "
                + newState(callAction.getState()) + ";");
        printSetStateParameters(stateVar,
                getParameters(callAction.getOtherAttributes(), callAction.getContent(), callAction));
        code.println("if (!flowThread.callState(" + stateVar + ", new FlowEventInfo(currentState, event, "
                + location(flowXml.getLocation(action)) + "))) {");
        code.println("eventResult = EVENT_ABORTED;");
        code.println("break EXECUTION;");
        code.println("}");
    } else if (action instanceof iristk.xml.flow.Return) {
        iristk.xml.flow.Return returnAction = (iristk.xml.flow.Return) action;
        if (exprContext != null)
            throw new FlowCompilerException("<return> not allowed in expression",
                    returnAction.sourceLocation().getLineNumber());
        if (returnAction.getEvent() != null || returnAction.getCopy() != null) {
            String returnEvent = varname("returnEvent");
            printInitEvent(returnEvent, returnAction.getCopy(), returnAction.getEvent(),
                    getParameters(returnAction.getOtherAttributes(), returnAction.getContent(), returnAction));
            //code.println("flowThread.raiseEvent(" + returnEvent + ", new FlowEventInfo(currentState, event, " + locationConstructor(flowReader.getLocation(action)) + ");");
            code.println("flowThread.returnFromCall(this, " + returnEvent
                    + ", new FlowEventInfo(currentState, event, " + location(flowXml.getLocation(action))
                    + "));");
        } else {
            code.println("flowThread.returnFromCall(this, null, new FlowEventInfo(currentState, event, "
                    + location(flowXml.getLocation(action)) + "));");
        }
        code.println("eventResult = EVENT_ABORTED;");
        code.println("break EXECUTION;");
    } else if (action instanceof Reentry) {
        //code.println("flowThread.raiseEvent(new EntryEvent(), new FlowEventInfo(currentState, event, " + locationConstructor(flowReader.getLocation(action)) + ");");
        Reentry reentryAction = (Reentry) action;
        if (exprContext != null)
            throw new FlowCompilerException("<reentry> not allowed in expression",
                    reentryAction.sourceLocation().getLineNumber());
        code.println("flowThread.reentryState(this, new FlowEventInfo(currentState, event, "
                + location(flowXml.getLocation(action)) + "));");
        code.println("eventResult = EVENT_ABORTED;");
        code.println("break EXECUTION;");
    } else if (action instanceof iristk.xml.flow.Block) {
        //System.out.println("BLOCK " + currentLineNumber);
        iristk.xml.flow.Block blockAction = (iristk.xml.flow.Block) action;
        String cond = "";
        if (blockAction.getCond() != null) {
            cond = "if (" + formatCondExpr(blockAction.getCond()) + ") ";
        }
        code.println(cond + "{");
        printActions(blockAction.getContent(), action, exprContext);
        code.println("}");
    } else if (action instanceof iristk.xml.flow.Wait) {
        iristk.xml.flow.Wait waitAction = (iristk.xml.flow.Wait) action;
        if (exprContext != null)
            throw new FlowCompilerException("<wait> not allowed in expression",
                    waitAction.sourceLocation().getLineNumber());

        String waitvar = varname("waitState");
        code.println(DialogFlow.class.getName() + ".wait " + waitvar + " = new " + DialogFlow.class.getName()
                + ".wait();");
        code.println(waitvar + ".setMsec(" + waitAction.getMsec() + ");");
        code.println("if (!flowThread.callState(" + waitvar + ", new FlowEventInfo(currentState, event, "
                + location(flowXml.getLocation(action)) + "))) {");
        code.println("eventResult = EVENT_ABORTED;");
        code.println("break EXECUTION;");
        code.println("}");
    } else if (action instanceof Random) {
        Random randomAction = (Random) action;
        if (randomAction.getList() != null) {
            if (exprContext == null) {
                throw new FlowCompilerException("<random list=\"...\"/> only allowed in expressions",
                        randomAction.sourceLocation().getLineNumber());
            }
            code.println(exprContext + ".append(randstr(" + randomAction.getList() + "));");
        } else {
            int tot = 0;
            for (Object child : randomAction.getAny()) {
                int inc = 1;
                if (child instanceof JAXBElement)
                    child = ((JAXBElement) child).getValue();
                if (child instanceof Block && ((Block) child).getWeight() != null)
                    inc = ((Block) child).getWeight();
                tot += inc;
            }
            int n = 0;
            int lastn = 0;
            String chosenVar = varname("chosen");
            String matchingVar = varname("matching");
            code.println("boolean " + chosenVar + " = false;");
            code.println("boolean " + matchingVar + " = true;");
            code.println("while (!" + chosenVar + " && " + matchingVar + ") {");
            String randVar = varname("rand");
            String model = "iristk.util.RandomList.RandomModel." + randomAction.getModel().toUpperCase();
            code.println("int " + randVar + " = random(" + randomAction.hashCode() + ", " + tot + ", " + model
                    + ");");
            code.println(matchingVar + " = false;");
            for (Object child : randomAction.getAny()) {
                if (n > 0)
                    code.println("}");
                int inc = 1;
                String cond = "true";
                List<Object> actions = new ArrayList<>();
                if (child instanceof JAXBElement)
                    child = ((JAXBElement) child).getValue();
                if (child instanceof Block) {
                    Block block = (Block) child;
                    if (block.getWeight() != null)
                        inc = block.getWeight();
                    if (block.getCond() != null)
                        cond = formatCondExpr(block.getCond());
                    actions.addAll(block.getContent());
                } else {
                    actions.add(child);
                }
                n += inc;
                code.println("if (" + cond + ") {");
                code.println(matchingVar + " = true;");
                code.println("if (" + randVar + " >= " + lastn + " && " + randVar + " < " + n + ") {");
                code.println(chosenVar + " = true;");
                printActions(actions, randomAction, exprContext);
                code.println("}");
                lastn = n;
            }
            code.println("}");
            code.println("}");
        }
    } else if (action instanceof Select) {
        Select select = (Select) action;
        String label = varname("SELECTION");
        code.println(label + ":");
        code.println("{");
        for (Object child : select.getAny()) {
            String cond = "";
            List<Object> actions = new ArrayList<>();
            if (child instanceof JAXBElement)
                child = ((JAXBElement) child).getValue();
            if (child instanceof Block) {
                Block block = (Block) child;
                if (block.getCond() != null)
                    cond = "if (" + formatCondExpr(block.getCond()) + ") ";
                actions.addAll(block.getContent());
            } else {
                actions.add(child);
            }
            code.println(cond + "{");
            printActions(actions, select, exprContext);
            code.println("break " + label + ";");
            code.println("}");
            if (cond.equals(""))
                break;
        }
        code.println("}");
    } else if (action instanceof iristk.xml.flow.Raise) {
        iristk.xml.flow.Raise raiseAction = (iristk.xml.flow.Raise) action;
        if (exprContext != null)
            throw new FlowCompilerException("<raise> not allowed in expression",
                    raiseAction.sourceLocation().getLineNumber());

        String raiseEvent = varname("raiseEvent");
        printInitEvent(raiseEvent, raiseAction.getCopy(), raiseAction.getEvent(),
                getParameters(raiseAction.getOtherAttributes(), raiseAction.getContent(), raiseAction));
        if (raiseAction.getDelay() != null) {
            String delayedEvent = "flowThread.raiseEvent(" + raiseEvent + ", "
                    + formatAttrExpr(raiseAction.getDelay()) + ", new FlowEventInfo(currentState, event, "
                    + location(flowXml.getLocation(action)) + "))";
            if (raiseAction.isForgetOnExit()) {
                code.println("forgetOnExit(" + delayedEvent + ");");
            } else {
                code.println(delayedEvent + ";");
            }
        } else {
            code.println("if (flowThread.raiseEvent(" + raiseEvent + ", new FlowEventInfo(currentState, event, "
                    + location(flowXml.getLocation(action)) + ")) == State.EVENT_ABORTED) {");
            code.println("eventResult = EVENT_ABORTED;");
            code.println("break EXECUTION;");
            code.println("}");
        }
    } else if (action instanceof iristk.xml.flow.Send) {
        iristk.xml.flow.Send sendAction = (iristk.xml.flow.Send) action;
        if (exprContext != null)
            throw new FlowCompilerException("<send> not allowed in expression",
                    sendAction.sourceLocation().getLineNumber());
        String sendEvent = varname("sendEvent");
        printInitEvent(sendEvent, sendAction.getCopy(), sendAction.getEvent(),
                getParameters(sendAction.getOtherAttributes(), sendAction.getContent(), sendAction));
        if (sendAction.getDelay() != null)
            code.println("flowRunner.sendEvent(" + sendEvent + ", " + formatAttrExpr(sendAction.getDelay())
                    + ", new FlowEventInfo(currentState, event, " + location(flowXml.getLocation(action))
                    + "));");
        else
            code.println("flowRunner.sendEvent(" + sendEvent + ", new FlowEventInfo(currentState, event, "
                    + location(flowXml.getLocation(action)) + "));");
        if (sendAction.getBindId() != null) {
            code.println(sendAction.getBindId() + " = " + sendEvent + ".getId();");
        }
    } else if (action instanceof iristk.xml.flow.If) {
        iristk.xml.flow.If ifAction = (iristk.xml.flow.If) action;
        code.println("if (" + formatCondExpr(ifAction.getCond()) + ") {");
        printActions(ifAction.getContent(), ifAction, exprContext);
        code.println("}");
    } else if (action instanceof iristk.xml.flow.Else) {
        code.println("} else {");
    } else if (action instanceof iristk.xml.flow.Elseif) {
        iristk.xml.flow.Elseif eifAction = (iristk.xml.flow.Elseif) action;
        code.println("} else if (" + formatCondExpr(eifAction.getCond()) + ") {");
    } else if (action instanceof iristk.xml.flow.Propagate) {
        iristk.xml.flow.Propagate propagateAction = (iristk.xml.flow.Propagate) action;
        if (exprContext != null)
            throw new FlowCompilerException("<propagate> not allowed in expression",
                    propagateAction.sourceLocation().getLineNumber());

        code.println("eventResult = EVENT_IGNORED;");
        code.println("break EXECUTION;");
    } else if (action instanceof Repeat) {
        Repeat repeat = (Repeat) action;
        String handler = repeat.getHandler();
        if (handler == null) {
            handler = varname("handler");
        }
        code.println("{");
        if (repeat.getTimes() != null) {
            code.println("RepeatHandler " + handler + " = new RepeatHandler("
                    + formatAttrExpr(repeat.getTimes()) + ");");
            code.println("while (" + handler + ".getPosition() < " + handler + ".getLength()) {");
        } else if (repeat.getWhile() != null) {
            code.println("RepeatHandler " + handler + " = new RepeatHandler();");
            code.println("while (" + formatAttrExpr(repeat.getWhile()) + ") {");
        } else if (repeat.getList() != null) {
            code.println("RepeatHandler " + handler + " = new RepeatHandler(" + formatAttrExpr(repeat.getList())
                    + ");");
            code.println("while (" + handler + ".getPosition() < " + handler + ".getLength()) {");
        }
        printActions(repeat.getContent(), repeat, exprContext);
        code.println(handler + ".next();");
        code.println("}");
        code.println("}");
    } else if (action instanceof Var) {
        Var varAction = (Var) action;
        if (exprContext != null)
            throw new FlowCompilerException("<var> not allowed in expression",
                    varAction.sourceLocation().getLineNumber());
        code.println(variable((Var) action));
    } else if (action instanceof iristk.xml.flow.Exec) {
        code.println(formatExec(((iristk.xml.flow.Exec) action).getValue().trim()));
    } else if (action instanceof iristk.xml.flow.Log) {
        code.println("log(" + createExpression(((iristk.xml.flow.Log) action).getContent(), action) + ");");
    } else if (action instanceof iristk.xml.flow.Expr) {
        if (exprContext == null) {
            throw new FlowCompilerException("<expr> not allowed", currentLineNumber);
        } else {
            code.println(exprContext + ".append(" + formatExpr(((Expr) action).getValue()) + ");");
        }
    } else if (action instanceof Element) {//perhaps implement variable name here
        Element elem = (Element) action;
        if (exprContext == null) {
            if (elem.getNamespaceURI().equals("iristk.flow") || elem.getPrefix() == null) {
                throw new FlowCompilerException("Bad element: <" + elem.getLocalName() + ">",
                        currentLineNumber);
            }
            String stateVar = varname("state");
            code.println(stateClass(elem) + " " + stateVar + " = " + newState(elem) + ";");
            printSetStateParameters(stateVar, getParameters(elem));

            code.println("if (!flowThread.callState(" + stateVar + ", new FlowEventInfo(currentState, event, "
                    + location(flowXml.getLocation(parent)) + "))) {");
            code.println("eventResult = EVENT_ABORTED;");
            code.println("break EXECUTION;");
            code.println("}");
        } else {
            try {
                Object o = flowXml.unmarshal(elem);
                printAction(o, parent, exprContext);
            } catch (FlowCompilerException e) {
                code.println(exprContext + ".append(" + createExpression(elem) + ");");
            }
        }
    } else if (action instanceof Text) {
        printAction(((Text) action).getTextContent(), parent, exprContext);
    } else if (action instanceof String) {
        String str = action.toString().trim();
        if (str.length() > 0) {
            if (exprContext == null) {
                throw new FlowCompilerException("Text node not allowed: " + str, currentLineNumber);
            } else {
                code.println(exprContext + ".append(\"" + str.replaceAll("\\n", " ") + "\");");
            }
        }
    } else {
        throw new FlowCompilerException("Could not parse " + action, currentLineNumber);
    }
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * This method takes the SOAP request that come from the WSP and removes
 * the elements that need to be removed per the SAML Profiles spec.
 * /*from  w  w  w.  j a v  a  2 s.  co  m*/
 * @param samlSession
 * @param authnState 
 * @return true, if successful
 */
private boolean processSOAPRequest(SAMLSession samlSession, DelegatedSAMLAuthenticationState authnState) {
    this.logger.debug("Step 3 of 5: Process SOAP Request");
    try {
        String expression = "/S:Envelope/S:Header/paos:Request";
        Document dom = authnState.getSoapRequestDom();
        Node node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);

        if (node != null) {
            // Save the response consumer URL to samlSession
            String responseConsumerURL = node.getAttributes().getNamedItem("responseConsumerURL")
                    .getTextContent();
            logger.debug("Loaded response consumer URL {}", responseConsumerURL);
            authnState.setResponseConsumerURL(responseConsumerURL);
            // Save the PAOS MessageID, if present
            Node paosMessageID = node.getAttributes().getNamedItem("messageID");

            if (paosMessageID != null)
                authnState.setPaosMessageID(paosMessageID.getTextContent());
            else
                authnState.setPaosMessageID(null);

            // This removes the paos:Request node
            node.getParentNode().removeChild(node);

            // Retrieve the RelayState cookie for sending it back to the WSP with the SOAP Response
            expression = "/S:Envelope/S:Header/ecp:RelayState";
            node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);
            if (node != null) {
                Element relayStateElement = (Element) node;
                authnState.setRelayStateElement(relayStateElement);
                node.getParentNode().removeChild(node);
            }

            // On to the ecp:Request for removal
            expression = "/S:Envelope/S:Header/ecp:Request";
            node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);
            node.getParentNode().removeChild(node);

            // Now add some namespace bindings to the SOAP Header
            expression = "/S:Envelope/S:Header";
            Element soapHeader = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);

            // Add new elements to S:Header
            Element newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("sbf"), "sbf:Framework");
            newElement.setAttribute("version", "2.0");
            soapHeader.appendChild(newElement);
            newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("sb"), "sb:Sender");
            newElement.setAttribute("providerID", samlSession.getPortalEntityID());
            soapHeader.appendChild(newElement);
            newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("wsa"), "wsa:MessageID");
            String messageID = generateMessageID();
            newElement.setTextContent(messageID);
            soapHeader.appendChild(newElement);
            newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("wsa"), "wsa:Action");
            newElement.setTextContent("urn:liberty:ssos:2006-08:AuthnRequest");
            soapHeader.appendChild(newElement);

            // This is the wsse:Security element 
            Element securityElement = dom.createElementNS(
                    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                    "wsse:Security");
            securityElement.setAttribute(soapHeader.getPrefix() + ":mustUnderstand", "1");
            Element createdElement = dom.createElement("wsu:Created");
            // The examples use Zulu time zone, not local
            TimeZone zuluTimeZone = TimeZone.getTimeZone("Zulu");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
            sdf.setTimeZone(zuluTimeZone);
            createdElement.setTextContent(sdf.format(new Date()));
            newElement = dom.createElementNS(
                    "http://www.docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd",
                    "wsu:Timestamp");
            newElement.appendChild(createdElement);
            securityElement.appendChild(newElement);
            // Finally, insert the original SAML assertion
            Node samlAssertionNode = dom.importNode(samlSession.getSamlAssertionDom().getDocumentElement(),
                    true);
            securityElement.appendChild(samlAssertionNode);
            soapHeader.appendChild(securityElement);

            // Store the modified SOAP Request in the SAML Session
            String modifiedSOAPRequest = writeDomToString(dom);
            authnState.setModifiedSOAPRequest(modifiedSOAPRequest);
            logger.debug("Completed processing of SOAP request");
            return true;
        }
        logger.debug("Failed to process SOAP request using expression {}", expression);
    } catch (XPathExpressionException ex) {
        logger.error("Programming error.  Invalid XPath expression.", ex);
        throw new DelegatedAuthenticationRuntimeException("Programming error.  Invalid XPath expression.", ex);
    }
    return false;
}

From source file:org.alfresco.repo.template.XSLTProcessor.java

/**
 * Adds the specified parameters to the xsl template as variables within the alfresco namespace.
 * //from  w  w  w.  j  av a 2  s .  co m
 * @param xsltModel
 *            the variables to place within the xsl template
 * @param xslTemplate
 *            the xsl template
 */
protected void addParameters(final XSLTemplateModel xsltModel, final Document xslTemplate) {
    final Element docEl = xslTemplate.getDocumentElement();
    final String XSL_NS = docEl.getNamespaceURI();
    final String XSL_NS_PREFIX = docEl.getPrefix();

    for (Map.Entry<QName, Object> e : xsltModel.entrySet()) {
        if (ROOT_NAMESPACE.equals(e.getKey())) {
            continue;
        }
        final Element el = xslTemplate.createElementNS(XSL_NS, XSL_NS_PREFIX + ":variable");
        el.setAttribute("name", e.getKey().toPrefixString());
        final Object o = e.getValue();
        if (o instanceof String || o instanceof Number || o instanceof Boolean) {
            el.appendChild(xslTemplate.createTextNode(o.toString()));
            // ALF-15413. Add the variables at the end of the list of children
            docEl.insertBefore(el, null);
        }
    }
}

From source file:org.alfresco.web.forms.XSLTRenderingEngine.java

/**
 * Adds the specified parameters to the xsl template as variables within the 
 * alfresco namespace./*  ww w.  java 2s. c  o  m*/
 *
 * @param model the variables to place within the xsl template
 * @param xslTemplate the xsl template
 */
protected void addParameters(final Map<QName, Object> model, final Document xslTemplate) {
    final Element docEl = xslTemplate.getDocumentElement();
    final String XSL_NS = docEl.getNamespaceURI();
    final String XSL_NS_PREFIX = docEl.getPrefix();

    for (Map.Entry<QName, Object> e : model.entrySet()) {
        if (RenderingEngine.ROOT_NAMESPACE.equals(e.getKey())) {
            continue;
        }
        final Element el = xslTemplate.createElementNS(XSL_NS, XSL_NS_PREFIX + ":variable");
        el.setAttribute("name", e.getKey().toPrefixString());
        final Object o = e.getValue();
        if (o instanceof String || o instanceof Number || o instanceof Boolean) {
            el.appendChild(xslTemplate.createTextNode(o.toString()));
            docEl.insertBefore(el, docEl.getFirstChild());
        }
    }
}

From source file:org.apache.axis2.saaj.SOAPFactoryTest.java

@Validated
@Test/*from  www . ja v  a2s  .co  m*/
public void testCreateElement2() {
    try {
        SOAPFactory sf = SOAPFactory.newInstance();
        //SOAPFactory sf = SOAPFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
        if (sf == null) {
            fail("could not create SOAPFactory object");
        }
        log.info("Create a DOMElement");
        DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = dbfactory.newDocumentBuilder();
        Document document = builder.newDocument();
        Element de = document.createElementNS("http://MyNamespace.org/", "MyTag");
        //Calling SOAPFactory.createElement(org.w3c.dom.Element)
        SOAPElement se = sf.createElement(de);
        if (!de.getNodeName().equals(se.getNodeName()) || !de.getNamespaceURI().equals(se.getNamespaceURI())) {
            //Node names are not equal
            fail("Got: <URI=" + se.getNamespaceURI() + ", PREFIX=" + se.getPrefix() + ", NAME="
                    + se.getNodeName() + ">" + "Expected: <URI=" + de.getNamespaceURI() + ", PREFIX="
                    + de.getPrefix() + ", NAME=" + de.getNodeName() + ">");
        }
    } catch (Exception e) {
        fail("Exception: " + e);
    }
}