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:com.microsoft.windowsazure.management.compute.ServiceCertificateOperationsImpl.java

/**
* The Get Service Certificate operation returns the public data for the
* specified X.509 certificate associated with a hosted service.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460792.aspx for
* more information)//from   w  ww. j a v  a  2 s  .com
*
* @param parameters Required. Parameters supplied to the Get Service
* Certificate operation.
* @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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Get Service Certificate operation response.
*/
@Override
public ServiceCertificateGetResponse get(ServiceCertificateGetParameters parameters)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getServiceName() == null) {
        throw new NullPointerException("parameters.ServiceName");
    }
    // TODO: Validate parameters.ServiceName is a valid DNS name.
    if (parameters.getThumbprint() == null) {
        throw new NullPointerException("parameters.Thumbprint");
    }
    if (parameters.getThumbprintAlgorithm() == null) {
        throw new NullPointerException("parameters.ThumbprintAlgorithm");
    }

    // 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("parameters", parameters);
        CloudTracing.enter(invocationId, this, "getAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/hostedservices/";
    url = url + URLEncoder.encode(parameters.getServiceName(), "UTF-8");
    url = url + "/certificates/";
    url = url + URLEncoder.encode(parameters.getThumbprintAlgorithm(), "UTF-8");
    url = url + "-";
    url = url + URLEncoder.encode(parameters.getThumbprint(), "UTF-8");
    String baseUrl = this.getClient().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", "2015-04-01");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().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
        ServiceCertificateGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ServiceCertificateGetResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element certificateElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "Certificate");
            if (certificateElement != null) {
                Element dataElement = XmlUtility.getElementByTagNameNS(certificateElement,
                        "http://schemas.microsoft.com/windowsazure", "Data");
                if (dataElement != null) {
                    byte[] dataInstance;
                    dataInstance = dataElement.getTextContent() != null
                            ? Base64.decode(dataElement.getTextContent())
                            : null;
                    result.setData(dataInstance);
                }
            }

        }
        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:com.evolveum.midpoint.prism.schema.DomToSchemaPostProcessor.java

private PrismReferenceDefinitionImpl processObjectReferenceDefinition(XSType xsType, QName elementName,
        XSAnnotation annotation, ComplexTypeDefinition containingCtd, XSParticle elementParticle,
        boolean inherited) throws SchemaException {
    QName typeName = new QName(xsType.getTargetNamespace(), xsType.getName());
    QName primaryElementName = elementName;
    Element objRefAnnotationElement = SchemaProcessorUtil.getAnnotationElement(annotation, A_OBJECT_REFERENCE);
    boolean hasExplicitPrimaryElementName = (objRefAnnotationElement != null
            && !StringUtils.isEmpty(objRefAnnotationElement.getTextContent()));
    if (hasExplicitPrimaryElementName) {
        primaryElementName = DOMUtil.getQNameValue(objRefAnnotationElement);
    }/*  www  .  jav a  2  s.c om*/
    PrismReferenceDefinitionImpl definition = null;
    if (containingCtd != null) {
        definition = (PrismReferenceDefinitionImpl) containingCtd.findItemDefinition(primaryElementName,
                PrismReferenceDefinition.class);
    }
    if (definition == null) {
        SchemaDefinitionFactory definitionFactory = getDefinitionFactory();
        definition = (PrismReferenceDefinitionImpl) definitionFactory.createReferenceDefinition(
                primaryElementName, typeName, containingCtd, prismContext, annotation, elementParticle);
        definition.setInherited(inherited);
        if (containingCtd != null) {
            ((ComplexTypeDefinitionImpl) containingCtd).add(definition);
        }
    }
    if (hasExplicitPrimaryElementName) {
        // The elements that have explicit type name determine the target
        // type name (if not yet set)
        if (definition.getTargetTypeName() == null) {
            definition.setTargetTypeName(typeName);
        }
        if (definition.getCompositeObjectElementName() == null) {
            definition.setCompositeObjectElementName(elementName);
        }
    } else {
        // The elements that use default element names override type
        // definition
        // as there can be only one such definition, therefore the behavior
        // is deterministic
        definition.setTypeName(typeName);
    }
    Element targetTypeAnnotationElement = SchemaProcessorUtil.getAnnotationElement(annotation,
            A_OBJECT_REFERENCE_TARGET_TYPE);
    if (targetTypeAnnotationElement != null
            && !StringUtils.isEmpty(targetTypeAnnotationElement.getTextContent())) {
        // Explicit definition of target type overrides previous logic
        QName targetType = DOMUtil.getQNameValue(targetTypeAnnotationElement);
        definition.setTargetTypeName(targetType);
    }
    setMultiplicity(definition, elementParticle, annotation, false);
    Boolean composite = SchemaProcessorUtil.getAnnotationBooleanMarker(annotation, A_COMPOSITE);
    if (composite != null) {
        definition.setComposite(composite);
    }

    parseItemDefinitionAnnotations(definition, annotation);
    // extractDocumentation(definition, annotation);
    return definition;
}

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

@Override
public List<CertificateRef> getCertificateRefs() {

    try {//from  w w w. j av a2s . c  o  m

        Element signingCertEl = XMLUtils.getElement(signatureElement,
                "./ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties"
                        + "/xades:CompleteCertificateRefs/xades:CertRefs");
        if (signingCertEl == null) {
            return null;
        }

        List<CertificateRef> certIds = new ArrayList<CertificateRef>();
        NodeList certIdnodes = XMLUtils.getNodeList(signingCertEl, "./xades:Cert");
        for (int i = 0; i < certIdnodes.getLength(); i++) {
            Element certId = (Element) certIdnodes.item(i);
            Element issuerNameEl = XMLUtils.getElement(certId, "./xades:IssuerSerial/ds:X509IssuerName");
            Element issuerSerialEl = XMLUtils.getElement(certId, "./xades:IssuerSerial/ds:X509SerialNumber");
            Element digestAlgorithmEl = XMLUtils.getElement(certId, "./xades:CertDigest/ds:DigestMethod");
            Element digestValueEl = XMLUtils.getElement(certId, "./xades:CertDigest/ds:DigestValue");

            CertificateRef genericCertId = new CertificateRef();
            if (issuerNameEl != null && issuerSerialEl != null) {
                genericCertId.setIssuerName(issuerNameEl.getTextContent());
                genericCertId.setIssuerSerial(issuerSerialEl.getTextContent());
            }

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

            genericCertId.setDigestValue(Base64.decodeBase64(digestValueEl.getTextContent()));
            certIds.add(genericCertId);
        }

        return certIds;

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

From source file:it.iit.genomics.cru.structures.bridges.uniprot.UniprotkbUtils.java

private Collection<MoleculeEntry> getUniprotEntriesXML(String location, boolean waitAndRetryOnFailure)
        throws BridgesRemoteAccessException {

    String url = location + "&format=xml";

    ArrayList<MoleculeEntry> uniprotEntries = new ArrayList<>();
    try {//from w ww.  j a v  a2s.  c  o m
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
        HttpGet request = new HttpGet(url);

        // add request header
        request.addHeader("User-Agent", USER_AGENT);

        HttpResponse response = client.execute(request);

        if (response.getEntity().getContentLength() == 0) {
            // No result
            return uniprotEntries;
        }

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new InputSource(response.getEntity().getContent()));

        // optional, but recommended
        // read this -
        // http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        doc.getDocumentElement().normalize();

        // interaction structure
        NodeList entryList = doc.getElementsByTagName("entry");

        for (int i = 0; i < entryList.getLength(); i++) {

            Element entryElement = (Element) entryList.item(i);

            String dataset = entryElement.getAttribute("dataset");

            String ac = entryElement.getElementsByTagName("accession").item(0).getFirstChild().getNodeValue();

            MoleculeEntry uniprotEntry = new MoleculeEntry(ac);

            uniprotEntry.setDataset(dataset);

            // Taxid
            Element organism = (Element) entryElement.getElementsByTagName("organism").item(0);

            String organismCommonName = null;
            String organismScientificName = null;
            String organismOtherName = null;

            NodeList organismNames = organism.getElementsByTagName("name");

            for (int j = 0; j < organismNames.getLength(); j++) {

                Element reference = (Element) organismNames.item(j);
                switch (reference.getAttribute("type")) {
                case "scientific":
                    organismScientificName = reference.getTextContent();
                    break;
                case "common":
                    organismCommonName = reference.getTextContent();
                    break;
                default:
                    organismOtherName = reference.getTextContent();
                    break;
                }
            }

            if (null != organismCommonName) {
                uniprotEntry.setOrganism(organismCommonName);
            } else if (null != organismScientificName) {
                uniprotEntry.setOrganism(organismScientificName);
            } else if (null != organismOtherName) {
                uniprotEntry.setOrganism(organismOtherName);
            }

            NodeList organismReferences = organism.getElementsByTagName("dbReference");

            for (int j = 0; j < organismReferences.getLength(); j++) {
                Element reference = (Element) organismReferences.item(j);
                if (reference.hasAttribute("type") && "NCBI Taxonomy".equals(reference.getAttribute("type"))) {
                    String proteinTaxid = reference.getAttribute("id");
                    uniprotEntry.setTaxid(proteinTaxid);
                }
            }

            // GENE
            NodeList geneNames = entryElement.getElementsByTagName("gene");

            for (int j = 0; j < geneNames.getLength(); j++) {
                Element gene = (Element) geneNames.item(j);

                NodeList nameList = gene.getElementsByTagName("name");

                for (int k = 0; k < nameList.getLength(); k++) {
                    Element name = (Element) nameList.item(k);
                    uniprotEntry.addGeneName(name.getFirstChild().getNodeValue());
                }
            }

            // modified residues
            HashMap<String, ModifiedResidue> modifiedResidues = new HashMap<>();

            NodeList features = entryElement.getElementsByTagName("feature");
            for (int j = 0; j < features.getLength(); j++) {
                Element feature = (Element) features.item(j);

                if (false == entryElement.equals(feature.getParentNode())) {
                    continue;
                }

                // ensembl
                if (feature.hasAttribute("type") && "modified residue".equals(feature.getAttribute("type"))) {

                    String description = feature.getAttribute("description").split(";")[0];

                    if (false == modifiedResidues.containsKey(description)) {
                        modifiedResidues.put(description, new ModifiedResidue(description));
                    }

                    NodeList locations = feature.getElementsByTagName("location");
                    for (int k = 0; k < locations.getLength(); k++) {
                        Element loc = (Element) locations.item(k);
                        NodeList positions = loc.getElementsByTagName("position");
                        for (int l = 0; l < positions.getLength(); l++) {
                            Element position = (Element) positions.item(l);
                            modifiedResidues.get(description).addPosition(
                                    new UniprotPosition(Integer.parseInt(position.getAttribute("position"))));
                        }

                    }
                }
            }

            uniprotEntry.getModifications().addAll(modifiedResidues.values());

            // Xrefs:
            NodeList dbReferences = entryElement.getElementsByTagName("dbReference");
            for (int j = 0; j < dbReferences.getLength(); j++) {
                Element dbReference = (Element) dbReferences.item(j);

                if (false == entryElement.equals(dbReference.getParentNode())) {
                    continue;
                }

                NodeList molecules = dbReference.getElementsByTagName("molecule");

                // ensembl
                if (dbReference.hasAttribute("type") && "Ensembl".equals(dbReference.getAttribute("type"))) {

                    // transcript ID
                    String id = dbReference.getAttribute("id");

                    for (int iMolecule = 0; iMolecule < molecules.getLength(); iMolecule++) {
                        Element molecule = (Element) molecules.item(iMolecule);
                        uniprotEntry.addXrefToVarSplice(id, molecule.getAttribute("id"));
                    }

                    uniprotEntry.addEnsemblGene(id);

                    NodeList properties = dbReference.getElementsByTagName("property");

                    for (int k = 0; k < properties.getLength(); k++) {
                        Element property = (Element) properties.item(k);

                        if (property.hasAttribute("type") && "gene ID".equals(property.getAttribute("type"))) {
                            uniprotEntry.addEnsemblGene(property.getAttribute("value"));
                        }
                    }
                }

                // refseq
                if (dbReference.hasAttribute("type") && "RefSeq".equals(dbReference.getAttribute("type"))) {
                    NodeList properties = dbReference.getElementsByTagName("property");
                    for (int k = 0; k < properties.getLength(); k++) {
                        Element property = (Element) properties.item(k);
                        if (property.hasAttribute("type")
                                && "nucleotide sequence ID".equals(property.getAttribute("type"))) {

                            String id = property.getAttribute("value");
                            if (molecules.getLength() > 0) {
                                for (int iMolecule = 0; iMolecule < molecules.getLength(); iMolecule++) {
                                    Element molecule = (Element) molecules.item(iMolecule);

                                    // If refseq, add also without the version                                       
                                    uniprotEntry.addXrefToVarSplice(id, molecule.getAttribute("id"));
                                    uniprotEntry.addXrefToVarSplice(id.split("\\.")[0],
                                            molecule.getAttribute("id"));

                                }
                            } else {
                                // If refseq, add also without the version                                       
                                uniprotEntry.addXrefToVarSplice(id, ac);
                                uniprotEntry.addXrefToVarSplice(id.split("\\.")[0], ac);
                            }

                            uniprotEntry.addRefseq(id);

                        }
                    }
                }

                /* PDB chains will be imported from the webservice */
                // PDB
                if (dbReference.hasAttribute("type") && "PDB".equals(dbReference.getAttribute("type"))) {
                    NodeList properties = dbReference.getElementsByTagName("property");
                    String method = null;
                    String chains = null;

                    for (int k = 0; k < properties.getLength(); k++) {
                        Element property = (Element) properties.item(k);
                        if (property.hasAttribute("type") && "method".equals(property.getAttribute("type"))) {
                            method = property.getAttribute("value");
                        } else if (property.hasAttribute("type")
                                && "chains".equals(property.getAttribute("type"))) {
                            chains = property.getAttribute("value");
                        }
                    }

                    if (method != null && "Model".equals(method)) {
                        continue;
                    }

                    if (chains == null) {
                        continue;
                    }

                    String pdb = dbReference.getAttribute("id");

                    uniprotEntry.addPDB(pdb, method);

                    for (String chainElement : chains.split(",")) {
                        try {
                            String chainNames = chainElement.split("=")[0];
                            int start = Integer.parseInt(chainElement.split("=")[1].trim().split("-")[0]);
                            int end = Integer
                                    .parseInt(chainElement.split("=")[1].trim().split("-")[1].replace(".", ""));
                            for (String chainName : chainNames.split("/")) {
                                uniprotEntry.addChain(pdb, new ChainMapping(pdb, chainName.trim(), start, end),
                                        method);
                            }
                        } catch (ArrayIndexOutOfBoundsException aiobe) {
                            // IGBLogger.getInstance().warning(
                            // "Cannot parse chain: " + chainElement
                            // + ", skip");
                        }
                    }
                }

            }

            // Sequence
            NodeList sequenceElements = entryElement.getElementsByTagName("sequence");

            for (int j = 0; j < sequenceElements.getLength(); j++) {
                Element sequenceElement = (Element) sequenceElements.item(j);

                if (false == sequenceElement.getParentNode().equals(entryElement)) {
                    continue;
                }
                String sequence = sequenceElement.getFirstChild().getNodeValue().replaceAll("\n", "");
                uniprotEntry.setSequence(sequence);
            }

            // Diseases
            NodeList diseases = entryElement.getElementsByTagName("disease");

            for (int j = 0; j < diseases.getLength(); j++) {
                Element disease = (Element) diseases.item(j);

                NodeList nameList = disease.getElementsByTagName("name");

                for (int k = 0; k < nameList.getLength(); k++) {
                    Element name = (Element) nameList.item(k);
                    uniprotEntry.addDisease(name.getFirstChild().getNodeValue());
                }
            }

            // Get fasta for all varsplice
            String fastaQuery = "http://www.uniprot.org/uniprot/" + uniprotEntry.getUniprotAc()
                    + ".fasta?include=yes";

            try {
                //HttpClient fastaClient = new DefaultHttpClient();

                client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
                HttpGet fastaRequest = new HttpGet(fastaQuery);

                // add request header
                request.addHeader("User-Agent", USER_AGENT);

                HttpResponse fastaResponse = client.execute(fastaRequest);

                if (fastaResponse.getEntity().getContentLength() == 0) {
                    continue;
                }

                InputStream is = fastaResponse.getEntity().getContent();

                try {
                    LinkedHashMap<String, ProteinSequence> fasta = FastaReaderHelper
                            .readFastaProteinSequence(is);

                    boolean mainSequence = true;

                    for (ProteinSequence seq : fasta.values()) {
                        //                            logger.info("Add sequence: " + seq.getAccession().getID() + " : " + seq.getSequenceAsString());
                        uniprotEntry.addSequence(seq.getAccession().getID(), seq.getSequenceAsString());
                        if (mainSequence) {
                            uniprotEntry.setMainIsoform(seq.getAccession().getID());
                            mainSequence = false;
                        }
                    }
                } catch (Exception e) {
                    logger.error("Cannot retrieve fasta for : " + uniprotEntry.getUniprotAc());
                }
            } catch (IOException | IllegalStateException ex) {
                logger.error(null, ex);
            }

            uniprotEntries.add(uniprotEntry);

        }

    } catch (SAXParseException se) {
        // Nothing was return
        // IGBLogger.getInstance()
        // .error("Uniprot returns empty result: " + url);
    } catch (IOException | ParserConfigurationException | IllegalStateException | SAXException | DOMException
            | NumberFormatException e) {
        if (waitAndRetryOnFailure && allowedUniprotFailures > 0) {
            try {
                allowedUniprotFailures--;
                Thread.sleep(5000);
                return getUniprotEntriesXML(location, false);
            } catch (InterruptedException e1) {
                logger.error("Fail to retrieve data from " + location);
                throw new BridgesRemoteAccessException("Fail to retrieve data from Uniprot " + location);
            }
        } else {
            logger.error("Problem with Uniprot: " + url);
            throw new BridgesRemoteAccessException("Fail to retrieve data from Uniprot " + location);
        }
    }

    for (MoleculeEntry entry : uniprotEntries) {
        addToCache(entry);
    }

    return uniprotEntries;
}

From source file:org.gvnix.web.exception.handler.roo.addon.addon.WebExceptionHandlerOperationsImpl.java

/**
 * Update the webmvc-config.xml with the new Exception.
 * /*from   w ww.ja va  2  s.  com*/
 * @param exceptionName Exception Name to Handle.
 * @return {@link String} The exceptionViewName to create the .jspx view.
 */
protected String updateWebMvcConfig(String exceptionName) {

    String webXmlPath = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
            WEB_MVC_CONFIG);
    Validate.isTrue(fileManager.exists(webXmlPath), WEB_MVC_CONFIG_NOT_FOUND);

    MutableFile webXmlMutableFile = null;
    Document webXml;

    try {
        webXmlMutableFile = fileManager.updateFile(webXmlPath);
        webXml = XmlUtils.getDocumentBuilder().parse(webXmlMutableFile.getInputStream());
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    Element root = webXml.getDocumentElement();

    Element simpleMappingException = XmlUtils
            .findFirstElement(RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props", root);

    Element exceptionResolver = XmlUtils.findFirstElement(RESOLVER_BEAN_MESSAGE
            + "/property[@name='exceptionMappings']/props/prop[@key='" + exceptionName + "']", root);

    boolean updateMappings = false;
    boolean updateController = false;

    // View name for this Exception.
    String exceptionViewName;

    if (exceptionResolver != null) {
        exceptionViewName = exceptionResolver.getTextContent();
    } else {
        updateMappings = true;
        exceptionViewName = getExceptionViewName(exceptionName);
    }

    Element newExceptionMapping;

    // Exception Mapping
    newExceptionMapping = webXml.createElement("prop");
    newExceptionMapping.setAttribute("key", exceptionName);

    Validate.isTrue(exceptionViewName != null,
            "Can't create the view for the:\t" + exceptionName + " Exception.");

    newExceptionMapping.setTextContent(exceptionViewName);

    if (updateMappings) {
        simpleMappingException.appendChild(newExceptionMapping);
    }

    // Exception Controller
    Element newExceptionView = XmlUtils
            .findFirstElement("/beans/view-controller[@path='/" + exceptionViewName + "']", root);

    if (newExceptionView == null) {
        updateController = true;
    }

    newExceptionView = webXml.createElementNS("http://www.springframework.org/schema/mvc", "view-controller");
    newExceptionView.setPrefix("mvc");

    newExceptionView.setAttribute("path", "/" + exceptionViewName);

    if (updateController) {
        root.appendChild(newExceptionView);
    }

    if (updateMappings || updateController) {
        XmlUtils.writeXml(webXmlMutableFile.getOutputStream(), webXml);
    }

    return exceptionViewName;
}

From source file:com.microsoft.windowsazure.management.network.IPForwardingOperationsImpl.java

/**
* Gets the IP Forwarding applied to a role.
*
* @param serviceName Required./*www . j av  a  2  s. co m*/
* @param deploymentName Required.
* @param roleName Required.
* @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 IP Forwarding state associated with a role or network
* interface.
*/
@Override
public IPForwardingGetResponse getForRole(String serviceName, String deploymentName, String roleName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (roleName == null) {
        throw new NullPointerException("roleName");
    }

    // 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("serviceName", serviceName);
        tracingParameters.put("deploymentName", deploymentName);
        tracingParameters.put("roleName", roleName);
        CloudTracing.enter(invocationId, this, "getForRoleAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/roles/";
    url = url + URLEncoder.encode(roleName, "UTF-8");
    url = url + "/ipforwarding";
    String baseUrl = this.getClient().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", "2015-04-01");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().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
        IPForwardingGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new IPForwardingGetResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element iPForwardingElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "IPForwarding");
            if (iPForwardingElement != null) {
                Element stateElement = XmlUtility.getElementByTagNameNS(iPForwardingElement,
                        "http://schemas.microsoft.com/windowsazure", "State");
                if (stateElement != null) {
                    String stateInstance;
                    stateInstance = stateElement.getTextContent();
                    result.setState(stateInstance);
                }
            }

        }
        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:org.gvnix.web.exception.handler.roo.addon.addon.WebExceptionHandlerOperationsImpl.java

/**
 * Removes the definition of the selected Exception in the webmvc-config.xml
 * file./*  w  w  w .  j  a va2s. com*/
 * 
 * @param exceptionName Exception Name to remove.
 */
private String removeWebMvcConfig(String exceptionName) {

    String webXmlPath = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
            WEB_MVC_CONFIG);
    Validate.isTrue(fileManager.exists(webXmlPath), WEB_MVC_CONFIG_NOT_FOUND);

    MutableFile webXmlMutableFile = null;
    Document webXml;

    try {
        webXmlMutableFile = fileManager.updateFile(webXmlPath);
        webXml = XmlUtils.getDocumentBuilder().parse(webXmlMutableFile.getInputStream());
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    Element root = webXml.getDocumentElement();

    Element exceptionResolver = XmlUtils.findFirstElement(RESOLVER_BEAN_MESSAGE
            + "/property[@name='exceptionMappings']/props/prop[@key='" + exceptionName + "']", root);

    Validate.isTrue(exceptionResolver != null,
            "There isn't a Handled Exception with the name:\t" + exceptionName);

    // Remove Mapping
    exceptionResolver.getParentNode().removeChild(exceptionResolver);

    String exceptionViewName = exceptionResolver.getTextContent();

    Validate.isTrue(exceptionViewName != null,
            "Can't remove the view for the:\t" + exceptionName + " Exception.");

    // Remove NameSpace bean.
    Element lastExceptionControlled = XmlUtils
            .findFirstElement("/beans/view-controller[@path='/" + exceptionViewName + "']", root);

    lastExceptionControlled.getParentNode().removeChild(lastExceptionControlled);

    XmlUtils.writeXml(webXmlMutableFile.getOutputStream(), webXml);

    return exceptionViewName;
}

From source file:com.microsoft.windowsazure.management.network.IPForwardingOperationsImpl.java

/**
* Gets the IP Forwarding applied to a network interface.
*
* @param serviceName Required./*  www  .java 2s.  com*/
* @param deploymentName Required.
* @param roleName Required.
* @param networkInterfaceName Required.
* @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 IP Forwarding state associated with a role or network
* interface.
*/
@Override
public IPForwardingGetResponse getForNetworkInterface(String serviceName, String deploymentName,
        String roleName, String networkInterfaceName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (roleName == null) {
        throw new NullPointerException("roleName");
    }
    if (networkInterfaceName == null) {
        throw new NullPointerException("networkInterfaceName");
    }

    // 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("serviceName", serviceName);
        tracingParameters.put("deploymentName", deploymentName);
        tracingParameters.put("roleName", roleName);
        tracingParameters.put("networkInterfaceName", networkInterfaceName);
        CloudTracing.enter(invocationId, this, "getForNetworkInterfaceAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/roles/";
    url = url + URLEncoder.encode(roleName, "UTF-8");
    url = url + "/networkinterfaces/";
    url = url + URLEncoder.encode(networkInterfaceName, "UTF-8");
    url = url + "/ipforwarding";
    String baseUrl = this.getClient().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", "2015-04-01");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().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
        IPForwardingGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new IPForwardingGetResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element iPForwardingElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "IPForwarding");
            if (iPForwardingElement != null) {
                Element stateElement = XmlUtility.getElementByTagNameNS(iPForwardingElement,
                        "http://schemas.microsoft.com/windowsazure", "State");
                if (stateElement != null) {
                    String stateInstance;
                    stateInstance = stateElement.getTextContent();
                    result.setState(stateInstance);
                }
            }

        }
        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.europa.ec.markt.dss.validation.xades.XAdESSignature.java

@Override
public List<OCSPRef> getOCSPRefs() {

    try {//from  w w w  . j  a v  a2  s .  c om
        List<OCSPRef> certIds = new ArrayList<OCSPRef>();
        Element signingCertEl = XMLUtils.getElement(signatureElement,
                "./ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties"
                        + "/xades:CompleteRevocationRefs/xades:OCSPRefs");
        if (signingCertEl != null) {

            NodeList certIdnodes = XMLUtils.getNodeList(signingCertEl, "./xades:OCSPRef");
            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");

                if (digestAlgorithmEl == null || digestValueEl == null) {
                    throw new NotETSICompliantException(
                            eu.europa.ec.markt.dss.NotETSICompliantException.MSG.XADES_DIGEST_ALG_AND_VALUE_ENCODING);
                }

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

                certIds.add(
                        new OCSPRef(digestAlgo, Base64.decodeBase64(digestValueEl.getTextContent()), false));
            }
        }
        return certIds;
    } catch (XPathExpressionException e) {
        throw new EncodingException(MSG.OCSP_REF_ENCODING);
    }

}