Example usage for org.w3c.dom Element getTextContent

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

Introduction

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

Prototype

public String getTextContent() throws DOMException;

Source Link

Document

This attribute returns the text content of this node and its descendants.

Usage

From source file:module.signature.util.XAdESValidator.java

/**
 * @author joao.antunes@tagus.ist.utl.pt adapted it from {@link #validateXMLSignature(String)}
 * @param streamWithSignature//w  w  w  . ja  va  2 s  . c om
 *            the {@link InputStream} that has the signature content
 * @return true if it's valid, false otherwise
 */
public boolean validateXMLSignature(InputStream streamWithSignature) {
    try {

        // get the  xsd schema

        Validator validator = schemaXSD.newValidator();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder parser = dbf.newDocumentBuilder();

        ErrorHandler eh = new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }
        };

        // parse the document
        parser.setErrorHandler(eh);
        Document document = parser.parse(streamWithSignature);

        // XAdES extension
        NodeList nlObject = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Object");
        // XMLDSIG
        NodeList nlSignature = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#",
                "Signature");

        if (checkSchema) {
            if (nlObject.getLength() < 1) {
                return false;
            }
            if (nlSignature.getLength() < 1) {
                return false;
            }

            // parse the XML DOM tree againts the XSD schema
            validator.validate(new DOMSource(nlSignature.item(0)));
        }

        if (checkSignature) {
            // Validate Every Signature Element (including CounterSignatures)
            for (int i = 0; i < nlSignature.getLength(); i++) {

                Element signature = (Element) nlSignature.item(i);
                //          String baseURI = fileToValidate.toURL().toString();
                XMLSignature xmlSig = new XMLSignature(signature, null);

                KeyInfo ki = xmlSig.getKeyInfo();

                // If signature contains X509Data
                if (ki.containsX509Data()) {

                    NodeList nlSigningTime = signature.getElementsByTagNameNS(xadesNS, "SigningTime");
                    Date signingDate = null;

                    if (nlSigningTime.item(0) != null) {
                        StringBuilder xmlDate = new StringBuilder(nlSigningTime.item(0).getTextContent())
                                .deleteCharAt(22);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                        signingDate = simpleDateFormat.parse(xmlDate.toString());
                    }

                    //verificao OCSP
                    //TODO FENIX-189 joantune: na realidade acho que isto no verifica mesmo a revocao.. a no ser que a keystore indicada seja actualizada regularmente.
                    if (checkRevocation) {
                        //keystore certs cc, raiz estado

                        Security.setProperty("ocsp.enable", "true");
                        //System.setProperty("com.sun.security.enableCRLDP", "true");

                        CertificateFactory cf = CertificateFactory.getInstance("X.509");

                        CertPath certPath = cf
                                .generateCertPath(Collections.singletonList(ki.getX509Certificate()));
                        //             TrustAnchor trustA = new TrustAnchor(ki.getX509Certificate(), null);
                        //             Set trustAnchors = Collections.singleton(trustA);

                        PKIXParameters params = new PKIXParameters(cartaoCidadaoKeyStore);
                        params.setRevocationEnabled(true);

                        // validar o estado na data da assinatura
                        if (nlSigningTime.item(0) != null) {
                            params.setDate(signingDate);
                        }

                        try {
                            CertPathValidator cpValidator = CertPathValidator.getInstance("PKIX");
                            CertPathValidatorResult result = cpValidator.validate(certPath, params);
                            //TODO FENIX-196 probably one would want to send a notification here
                        } catch (CertPathValidatorException ex) {
                            return false;
                        } catch (InvalidAlgorithmParameterException ex) {
                            return false;
                        }
                    }

                    // verifica a validade do certificado no momento da assinatura
                    if (checkValidity) {

                        if (nlSigningTime.item(0) != null) { // continue if there is no SigningTime, if CounterSignature isn't XAdES
                            try {
                                ki.getX509Certificate().checkValidity(signingDate);
                            } catch (CertificateExpiredException ex) {
                                return false;
                            } catch (CertificateNotYetValidException ex) {
                                return false;
                            }
                        }
                    }

                    // validate against Certificate Public Key
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getX509Certificate().getPublicKey());

                    if (!validSignature) {
                        return false;
                    }
                }

                // if signature includes KeyInfo KeyValue, also check against it
                if (ki.containsKeyValue()) {
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getPublicKey());
                    if (!validSignature) {
                        return false;
                    }
                }

                //let's check the SignatureTimeStamp(s) joantune

                NodeList signatureTimeStamps = signature.getElementsByTagNameNS("*", "SignatureTimeStamp");
                Element signatureValue = null;
                if (signatureTimeStamps.getLength() > 0) {
                    signatureValue = (Element) signature.getElementsByTagNameNS("*", "SignatureValue").item(0);
                }
                for (int j = 0; j < signatureTimeStamps.getLength(); j++) {
                    logger.debug("Found a SignatureTimeStamp");
                    Element signatureTimeStamp = (Element) signatureTimeStamps.item(j);
                    //for now we are ignoring the XMLTimeStamp element, let's iterate through all of the EncapsulatedTimeStamp that we find
                    NodeList encapsulatedTimeStamps = signatureTimeStamp.getElementsByTagNameNS("*",
                            "EncapsulatedTimeStamp");
                    for (int k = 0; k < encapsulatedTimeStamps.getLength(); k++) {
                        logger.debug("Found an EncapsulatedTimeStamp");
                        Element encapsulatedTimeStamp = (Element) encapsulatedTimeStamps.item(k);
                        //let's check it
                        // note, we have the timestamptoken, not the whole response, that is, we don't have the status field

                        ASN1Sequence signedTimeStampToken = ASN1Sequence
                                .getInstance(Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        CMSSignedData cmsSignedData = new CMSSignedData(
                                Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        TimeStampToken timeStampToken = new TimeStampToken(cmsSignedData);

                        //let's construct the Request to make sure this is a valid response

                        //let's generate the digest
                        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
                        byte[] digest = sha1.digest(signatureValue.getTextContent().getBytes("UTF-8"));

                        //let's make sure the digests are the same
                        if (!Arrays.equals(digest,
                                timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
                            //TODO probably want to send an e-mail if this happens, as it's clearly a sign of tampering
                            //FENIX-196
                            logger.debug("Found a different digest in the timestamp!");
                            return false;
                        }

                        try {
                            //TODO for now we won't use the provided certificates that came with the TST
                            //            X509Store certificateStore = (X509Store) timeStampToken.getCertificates();
                            //            JcaDigestCalculatorProviderBuilder builder = new JcaDigestCalculatorProviderBuilder();
                            //            timeStampToken.validate(tsaCert, "BC");
                            //            timeStampToken.validate(new SignerInformationVerifier(new JcaContentVerifierProviderBuilder()
                            //               .build(tsaCert), builder.build()));
                            timeStampToken.validate(new SignerInformationVerifier(
                                    new JcaContentVerifierProviderBuilder().build(tsaCert),
                                    new BcDigestCalculatorProvider()));
                            //let's just verify that the timestamp was done in the past :) - let's give a tolerance of 5 mins :)
                            Date currentDatePlus5Minutes = new Date();
                            //let's make it go 5 minutes ahead
                            currentDatePlus5Minutes.setMinutes(currentDatePlus5Minutes.getMinutes() + 5);
                            if (!timeStampToken.getTimeStampInfo().getGenTime()
                                    .before(currentDatePlus5Minutes)) {
                                //FENIX-196 probably we want to log this!
                                //what the heck, timestamp is done in the future!! (clocks might be out of sync)
                                logger.warn("Found a timestamp in the future!");
                                return false;
                            }
                            logger.debug("Found a valid TimeStamp!");
                            //as we have no other timestamp elements in this signature, this means all is ok! :) 
                            //(point 5) of g.2.2.16.1.3 on the specs

                        } catch (TSPException exception) {
                            logger.debug("TimeStamp response did not validate", exception);
                            return false;
                        }

                    }
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (SAXException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (Exception ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}

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 ww w .j a va  2  s. com
        value = client.getPrimitiveValueBuilder().setType(edmType == null ? null : edmType.getSimpleType())
                .setText(prop.getTextContent()).build();
    }
    return value;
}

From source file:com.microsoft.windowsazure.management.scheduler.SchedulerManagementClientImpl.java

/**
* The Get Operation Status operation returns the status of thespecified
* operation. After calling an asynchronous operation, you can call Get
* Operation Status to determine whether the operation has succeeded,
* failed, or is still in progress.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for
* more information)// w  ww. j  a  va  2 s .co  m
*
* @param requestId Required. The request ID for the request you wish to
* track. The request ID is returned in the x-ms-request-id response header
* for every request.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request.  If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public SchedulerOperationStatusResponse getOperationStatus(String requestId)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (requestId == null) {
        throw new NullPointerException("requestId");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("requestId", requestId);
        CloudTracing.enter(invocationId, this, "getOperationStatusAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    if (this.getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/operations/";
    url = url + URLEncoder.encode(requestId, "UTF-8");
    String baseUrl = this.getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpGet httpRequest = new HttpGet(url);

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2013-03-01");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        SchedulerOperationStatusResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new SchedulerOperationStatusResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element operationElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "Operation");
            if (operationElement != null) {
                Element idElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "ID");
                if (idElement != null) {
                    String idInstance;
                    idInstance = idElement.getTextContent();
                    result.setId(idInstance);
                }

                Element statusElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "Status");
                if (statusElement != null && statusElement.getTextContent() != null
                        && !statusElement.getTextContent().isEmpty()) {
                    SchedulerOperationStatus statusInstance;
                    statusInstance = SchedulerOperationStatus.valueOf(statusElement.getTextContent());
                    result.setStatus(statusInstance);
                }

                Element httpStatusCodeElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "HttpStatusCode");
                if (httpStatusCodeElement != null && httpStatusCodeElement.getTextContent() != null
                        && !httpStatusCodeElement.getTextContent().isEmpty()) {
                    Integer httpStatusCodeInstance;
                    httpStatusCodeInstance = Integer.valueOf(httpStatusCodeElement.getTextContent());
                    result.setHttpStatusCode(httpStatusCodeInstance);
                }

                Element errorElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "Error");
                if (errorElement != null) {
                    SchedulerOperationStatusResponse.ErrorDetails errorInstance = new SchedulerOperationStatusResponse.ErrorDetails();
                    result.setError(errorInstance);

                    Element codeElement = XmlUtility.getElementByTagNameNS(errorElement,
                            "http://schemas.microsoft.com/windowsazure", "Code");
                    if (codeElement != null) {
                        String codeInstance;
                        codeInstance = codeElement.getTextContent();
                        errorInstance.setCode(codeInstance);
                    }

                    Element messageElement = XmlUtility.getElementByTagNameNS(errorElement,
                            "http://schemas.microsoft.com/windowsazure", "Message");
                    if (messageElement != null) {
                        String messageInstance;
                        messageInstance = messageElement.getTextContent();
                        errorInstance.setMessage(messageInstance);
                    }
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:eu.elf.license.LicenseQueryHandler.java

/**
 * Gets the price of the License Model//from  w  w w.  j av a 2 s  . c  om
 *
 * @param lm     - LicenseModel object
 * @param userId - UserId
 * @throws Exception
 * @return         - ProductPriceSum as String
 */
public String getLicenseModelPrice(LicenseModel lm, String userId) throws Exception {
    StringBuffer buf = null;
    String productPriceSum = "";
    List<LicenseParam> lpList = lm.getParams();

    String productPriceQuery = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
            + "<wpos:WPOSRequest xmlns:wpos=\"http://www.conterra.de/wpos/1.1\" version=\"1.1.0\">"
            + "<wpos:GetPrice collapse=\"true\">" + "<wpos:Product id=\""
            + StringEscapeUtils.escapeXml10(lm.getId()) + "\">" + "<wpos:ConfigParams>";

    for (int i = 0; i < lpList.size(); i++) {
        if (lpList.get(i).getParameterClass().equals("configurationParameter")) {

            LicenseParam lp = (LicenseParam) lpList.get(i);

            String priceQuery = "<wpos:Parameter name=\"" + StringEscapeUtils.escapeXml10(lp.getName()) + "\">";

            if (lp instanceof LicenseParamInt) {
                LicenseParamInt lpi = (LicenseParamInt) lp;

                priceQuery += "<wpos:Value selected=\"true\">" + lpi.getValue() + "</wpos:Value>"
                        + "</wpos:Parameter>";
            } else if (lp instanceof LicenseParamBln) {
                LicenseParamBln lpBln = (LicenseParamBln) lp;

                priceQuery += "<wpos:Value selected=\"true\">" + lpBln.getValue() + "</wpos:Value>"
                        + "</wpos:Parameter>";
            } else if (lp instanceof LicenseParamDisplay) {
                LicenseParamDisplay lpd = (LicenseParamDisplay) lp;
                List<String> values = lpd.getValues();

                if (lp.getName().equals("LICENSE_USER_GROUP")) {
                    priceQuery += "<wpos:Value>Users</wpos:Value>";

                } else if (lp.getName().equals("LICENSE_USER_ID")) {
                    priceQuery += "<wpos:Value>" + userId + "</wpos:Value>";

                } else {
                    for (int l = 0; l < values.size(); l++) {
                        priceQuery += "<wpos:Value selected=\"true\">"
                                + StringEscapeUtils.escapeXml10(values.get(l)) + "</wpos:Value>";
                    }
                }

                priceQuery += "</wpos:Parameter>";
            } else if (lp instanceof LicenseParamEnum) {
                LicenseParamEnum lpEnum = (LicenseParamEnum) lp;

                List<String> tempOptions = lpEnum.getOptions();
                List<String> tempSelections = lpEnum.getSelections();

                if (tempSelections.size() == 0) {
                    priceQuery = "";
                } else {
                    String selectionsString = "";

                    for (int j = 0; j < tempSelections.size(); j++) {
                        if (j == 0) {
                            selectionsString = tempSelections.get(j);
                        } else {
                            selectionsString += ", " + tempSelections.get(j);
                        }
                    }

                    priceQuery += "<wpos:Value selected=\"true\">"
                            + StringEscapeUtils.escapeXml10(selectionsString) + "</wpos:Value>"
                            + "</wpos:Parameter>";
                }
            } else if (lp instanceof LicenseParamText) {
                LicenseParamText lpText = (LicenseParamText) lp;
                List<String> values = lpText.getValues();

                for (int k = 0; k < values.size(); k++) {
                    priceQuery += "<wpos:Value selected=\"true\">" + lpText.getValues() + "</wpos:Value>";
                }
                priceQuery += "</wpos:Parameter>";
            }

            productPriceQuery += priceQuery;
        }

    }

    productPriceQuery += "</wpos:ConfigParams>" + "</wpos:Product>" + "</wpos:GetPrice>"
            + "</wpos:WPOSRequest>";

    //System.out.println("query: "+productPriceQuery.toString());

    try {
        buf = doHTTPQuery(this.wposURL, "post", productPriceQuery, false);
        //System.out.println("response: "+buf.toString());

        // Get productPriceInfo from the response
        Document xmlDoc = LicenseParser.createXMLDocumentFromString(buf.toString());
        Element catalogElement = (Element) xmlDoc
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "catalog").item(0);
        NodeList productGroupElementList = catalogElement
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "productGroup");

        for (int m = 0; m < productGroupElementList.getLength(); m++) {
            Element productGroupElement = (Element) productGroupElementList.item(m);
            Element calculationElement = (Element) productGroupElement
                    .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "calculation").item(0);
            Element declarationListElement = (Element) calculationElement
                    .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "declarationList").item(0);
            Element referencedParametersElement = (Element) declarationListElement
                    .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "referencedParameters").item(0);
            NodeList referencedParametersParameterList = referencedParametersElement
                    .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "parameter");

            for (int n = 0; n < referencedParametersParameterList.getLength(); n++) {
                Element referencedParametersParameterElement = (Element) referencedParametersParameterList
                        .item(n);

                NamedNodeMap referencedParametersParameterAttributeMap = referencedParametersParameterElement
                        .getAttributes();

                for (int o = 0; o < referencedParametersParameterAttributeMap.getLength(); o++) {
                    Attr attrs = (Attr) referencedParametersParameterAttributeMap.item(o);

                    if (attrs.getNodeName().equals("name")) {
                        if (attrs.getNodeValue().equals("productPriceSum")) {
                            Element valueElement = (Element) referencedParametersParameterElement
                                    .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "value").item(0);

                            productPriceSum = valueElement.getTextContent();
                        }
                    }
                }

            }

        }

    } catch (Exception e) {
        throw e;
    }

    return productPriceSum;
}

From source file:com.evolveum.midpoint.prism.schema.DomToSchemaPostProcessor.java

private boolean containsAccessFlag(String flag, List<Element> accessList) {
    for (Element element : accessList) {
        if (flag.equals(element.getTextContent())) {
            return true;
        }/*  www .  j a va 2s.  c o  m*/
    }

    return false;
}

From source file:com.bluexml.side.clazz.alfresco.reverse.reverser.ReverseModel.java

protected void createDataType(Model model,
        com.bluexml.side.alfresco.binding.Model.DataTypes.DataType dataType) {
    CustomDataType createCustomDataType = CommonFactory.eINSTANCE.createCustomDataType();
    // extract data from dataType 
    Element analyserClass = (Element) dataType.getAnalyserClass();
    if (analyserClass == null) {
        // model from alfresco 4.0+
        analyserClass = (Element) dataType.getDefaultAnalyserClass();
    }/*from w  ww  .j a v  a2s.  c o m*/

    System.out.println("ReverseModel.addDataTypes() " + analyserClass.getClass().getName());
    String description = dataType.getDescription();
    Element javaClass = (Element) dataType.getJavaClass();
    System.out.println("ReverseModel.addDataTypes() " + javaClass.getClass().getName());
    String qname = dataType.getName();
    String title = dataType.getTitle();

    // set customDataType
    setNameAndNS(createCustomDataType, qname);
    createCustomDataType.setDescription(description);
    createCustomDataType.setDataTypeImp(javaClass.getTextContent());

    MetaInfo createMetaInfo = ReverseHelper.createMetaInfo("analyser", null, analyserClass.getTextContent());
    createCustomDataType.getMetainfo().add(createMetaInfo);
    model.getCustomDataTypeSet().add(createCustomDataType);
    register.recordNewEObject(createCustomDataType, qname);
    System.out.println("ReverseModel.addDataTypes() reccord :" + qname);
    ReverseHelper.addSimpleNameTag(createCustomDataType);
}

From source file:com.evolveum.midpoint.prism.schema.DomToSchemaPostProcessor.java

@NotNull
private List<String> getIgnoredNamespaces(XSType xsType) {
    List<String> rv = new ArrayList<>();
    List<Element> annoElements = SchemaProcessorUtil.getAnnotationElements(xsType.getAnnotation(),
            A_IGNORED_NAMESPACE);//ww  w.j av a2  s  . c  om
    for (Element annoElement : annoElements) {
        rv.add(annoElement.getTextContent());
    }
    if (xsType.getBaseType() != null && !xsType.getBaseType().equals(xsType)) {
        rv.addAll(getIgnoredNamespaces(xsType.getBaseType()));
    }
    return rv;
}

From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java

@Override
public List<CRLRef> getCRLRefs() {

    try {//from   www  .  ja  v a2 s  .  c  om
        List<CRLRef> certIds = new ArrayList<CRLRef>();

        Element signingCertEl = XMLUtils.getElement(signatureElement,
                "./ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties"
                        + "/xades:CompleteRevocationRefs/xades:CRLRefs");
        if (signingCertEl != null) {

            NodeList certIdnodes = XMLUtils.getNodeList(signingCertEl, "./xades:CRLRef");
            for (int i = 0; i < certIdnodes.getLength(); i++) {
                Element certId = (Element) certIdnodes.item(i);
                Element digestAlgorithmEl = XMLUtils.getElement(certId,
                        "./xades:DigestAlgAndValue/ds:DigestMethod");
                Element digestValueEl = XMLUtils.getElement(certId, "./xades:DigestAlgAndValue/ds:DigestValue");

                String algorithm = digestAlgorithmEl.getAttribute("Algorithm");
                String digestAlgo = getShortAlgoName(algorithm);

                CRLRef ref = new CRLRef();
                ref.setAlgorithm(digestAlgo);
                ref.setDigestValue(Base64.decodeBase64(digestValueEl.getTextContent()));
                certIds.add(ref);
            }

        }
        return certIds;

    } catch (XPathExpressionException e) {
        throw new EncodingException(MSG.CRL_REF_ENCODING);
    }
}

From source file:com.cloud.test.regression.ApiCommand.java

public boolean verifyParam() {
    boolean result = true;
    if (this.getCommandType() == CommandType.HTTP) {
        if (this.list == false) {
            Set<?> set = verifyParam.entrySet();
            Iterator<?> it = set.iterator();

            while (it.hasNext()) {
                Map.Entry<?, ?> me = (Map.Entry<?, ?>) it.next();
                String key = (String) me.getKey();
                String value = (String) me.getValue();
                if (value == null) {
                    s_logger.error("Parameter " + key + " is missing in the list of global parameters");
                    return false;
                }// www.j a  v  a  2  s  .  c  om

                NodeList itemName = this.responseBody.getElementsByTagName(key);
                if ((itemName.getLength() != 0) && (itemName != null)) {
                    Element itemNameElement = (Element) itemName.item(0);
                    if (itemNameElement.hasChildNodes()) {
                        continue;
                    }
                    if (!(verifyParam.get(key).equals("no value"))
                            && !(itemNameElement.getTextContent().equals(verifyParam.get(key)))) {
                        s_logger.error("Incorrect value for the following tag: " + key + ". Expected value is "
                                + verifyParam.get(key) + " while actual value is "
                                + itemNameElement.getTextContent());
                        result = false;
                    }
                } else {
                    s_logger.error("Following xml element is missing in the response: " + key);
                    result = false;
                }
            }
        }
        // for multiple elements
        else {
            Set<?> set = verifyParam.entrySet();
            Iterator<?> it = set.iterator();
            // get list element specified by id
            NodeList returnLst = this.responseBody.getElementsByTagName(this.listName.getTextContent());
            Node requiredNode = returnLst.item(Integer.parseInt(this.listId.getTextContent()));

            if (requiredNode.getNodeType() == Node.ELEMENT_NODE) {
                Element fstElmnt = (Element) requiredNode;

                while (it.hasNext()) {
                    Map.Entry<?, ?> me = (Map.Entry<?, ?>) it.next();
                    String key = (String) me.getKey();
                    String value = (String) me.getValue();
                    if (value == null) {
                        s_logger.error("Parameter " + key + " is missing in the list of global parameters");
                        return false;
                    }
                    NodeList itemName = fstElmnt.getElementsByTagName(key);
                    if ((itemName.getLength() != 0) && (itemName != null)) {
                        Element itemNameElement = (Element) itemName.item(0);
                        if (!(verifyParam.get(key).equals("no value"))
                                && !(itemNameElement.getTextContent().equals(verifyParam.get(key)))) {
                            s_logger.error("Incorrect value for the following tag: " + key
                                    + ". Expected value is " + verifyParam.get(key) + " while actual value is "
                                    + itemNameElement.getTextContent());
                            result = false;
                        }
                    } else {
                        s_logger.error("Following xml element is missing in the response: " + key);
                        result = false;
                    }
                }
            }
        }
    } else if (this.getCommandType() == CommandType.MYSQL) {
        Set<?> set = verifyParam.entrySet();
        Iterator<?> it = set.iterator();

        while (it.hasNext()) {
            Map.Entry<?, ?> me = (Map.Entry<?, ?>) it.next();
            String key = (String) me.getKey();
            String value = (String) me.getValue();
            if (value == null) {
                s_logger.error("Parameter " + key + " is missing in the list of global parameters");
                return false;
            }

            String itemName = null;
            try {
                while (this.result.next()) {
                    itemName = this.result.getString(key);
                }
            } catch (Exception ex) {
                s_logger.error("Unable to get element from result set " + key);
            }

            if (!(value.equals("no value")) && !(itemName.equals(verifyParam.get(key)))) {
                s_logger.error("Incorrect value for the following tag: " + key + ". Expected value is "
                        + verifyParam.get(key) + " while actual value is " + itemName);
                result = false;
            }
        }
    }
    return result;
}

From source file:net.pms.util.CoverArtArchiveUtil.java

private ArrayList<ReleaseRecord> parseRecording(final Document document, final CoverArtArchiveTagInfo tagInfo) {
    NodeList nodeList = document.getDocumentElement().getElementsByTagName("recording-list");
    if (nodeList.getLength() < 1) {
        return null;
    }//  www  .  j  a v  a2 s .  c om
    Element listElement = (Element) nodeList.item(0); // recording-list
    nodeList = listElement.getElementsByTagName("recording");
    if (nodeList.getLength() < 1) {
        return null;
    }

    Pattern pattern = Pattern.compile("\\d{4}");
    ArrayList<ReleaseRecord> releaseList = new ArrayList<>(nodeList.getLength());
    for (int i = 0; i < nodeList.getLength(); i++) {
        if (nodeList.item(i) instanceof Element) {
            Element recordingElement = (Element) nodeList.item(i);
            ReleaseRecord releaseTemplate = new ReleaseRecord();

            try {
                releaseTemplate.score = Integer.parseInt(recordingElement.getAttribute("ext:score"));
            } catch (NumberFormatException e) {
                releaseTemplate.score = 0;
            }

            // A slight misuse of release.title here, we store the track name
            // here. It is accounted for in the matching logic.
            try {
                releaseTemplate.title = getChildElement(recordingElement, "title").getTextContent();
            } catch (NullPointerException e) {
                releaseTemplate.title = null;
            }

            Element artists = getChildElement(recordingElement, "artist-credit");
            if (artists != null && artists.getChildNodes().getLength() > 0) {
                NodeList artistList = artists.getChildNodes();
                for (int j = 0; j < artistList.getLength(); j++) {
                    Node node = artistList.item(j);
                    if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals("name-credit")
                            && node instanceof Element) {
                        Element artistElement = getChildElement((Element) node, "artist");
                        if (artistElement != null) {
                            Element artistNameElement = getChildElement(artistElement, "name");
                            if (artistNameElement != null) {
                                releaseTemplate.artists.add(artistNameElement.getTextContent());
                            }
                        }

                    }
                }
            }

            Element releaseListElement = getChildElement(recordingElement, "release-list");
            if (releaseListElement != null) {
                NodeList releaseNodeList = releaseListElement.getElementsByTagName("release");
                for (int j = 0; j < releaseNodeList.getLength(); j++) {
                    ReleaseRecord release = new ReleaseRecord(releaseTemplate);
                    Element releaseElement = (Element) releaseNodeList.item(j);
                    release.id = releaseElement.getAttribute("id");
                    Element releaseGroup = getChildElement(releaseElement, "release-group");
                    if (releaseGroup != null) {
                        try {
                            release.type = ReleaseType
                                    .valueOf(getChildElement(releaseGroup, "primary-type").getTextContent());
                        } catch (IllegalArgumentException | NullPointerException e) {
                            release.type = null;
                        }
                    }
                    Element releaseYear = getChildElement(releaseElement, "date");
                    if (releaseYear != null) {
                        release.year = releaseYear.getTextContent();
                        Matcher matcher = pattern.matcher(release.year);
                        if (matcher.find()) {
                            release.year = matcher.group();
                        } else {
                            release.year = null;
                        }
                    } else {
                        release.year = null;
                    }

                    if (StringUtil.hasValue(release.id)) {
                        releaseList.add(release);
                    }
                }
            }
        }
    }
    return releaseList;
}