Example usage for org.w3c.dom Node setTextContent

List of usage examples for org.w3c.dom Node setTextContent

Introduction

In this page you can find the example usage for org.w3c.dom Node setTextContent.

Prototype

public void setTextContent(String textContent) throws DOMException;

Source Link

Document

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

Usage

From source file:org.wso2.appserver.test.integration.TestListener.java

/**
 * Updates thrift ports in wso2as.xml.//from ww  w.ja  v  a2s  .  c om
 *
 * @param thriftPort
 * @param thriftSSLPort
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 * @throws TransformerException
 */
private static void updateThriftPorts(int thriftSSLPort, int thriftPort)
        throws ParserConfigurationException, IOException, SAXException, TransformerException {
    Path serverXML = Paths.get(System.getProperty(TestConstants.APPSERVER_HOME), "conf", "wso2", "wso2as.xml");

    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new InputSource(serverXML.toString()));

    Node authenticationURL = document.getElementsByTagName("AuthenticationURL").item(0);
    authenticationURL.setTextContent("ssl://" + Constants.HOST + ":" + thriftSSLPort);

    Node publisherURL = document.getElementsByTagName("PublisherURL").item(0);
    publisherURL.setTextContent("tcp://" + Constants.HOST + ":" + thriftPort);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(new DOMSource(document), new StreamResult(serverXML.toFile().getPath()));

}

From source file:org.wso2.carbon.apimgt.hybrid.gateway.api.synchronizer.APISynchronizer.java

/**
 * Method to write a custom sequence of an API to file
 *
 * @param sequenceInfo MediationDTO object
 * @param api          APIDTO object/*from  w w  w.  j  a  v  a 2  s . com*/
 */
private void writeSequenceToFile(MediationDTO sequenceInfo, APIDTO api)
        throws APIManagementException, APISynchronizationException {
    String seqFileName = APISynchronizationConstants.EMPTY_STRING;
    String tenantDomain = APISynchronizationConstants.EMPTY_STRING;
    try {
        String type = sequenceInfo.getType().name();
        String xmlStr = sequenceInfo.getConfig();
        String name = api.getName();

        // Sequences should be named according to the naming convention provider--apiName_version--sequenceType.xml
        // Provider should be set as Admin
        APIManagerConfiguration config = ServiceDataHolder.getInstance().getAPIManagerConfigurationService()
                .getAPIManagerConfiguration();
        String provider = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME);

        provider = provider.replaceAll("@", "-AT-");
        String version = api.getVersion();

        if ("in".equals(type)) {
            type = "In";
        } else if ("out".equals(type)) {
            type = "Out";
        }
        String seqElementName = provider + "--" + name + ":" + "v" + version + "--" + type;
        String seqName = provider + "--" + name + "_v" + version + "--" + type;
        seqFileName = seqName + ".xml";
        if (log.isDebugEnabled()) {
            log.debug("Starting to deploy sequence: " + seqName);
        }

        Document doc = convertStringToDocument(xmlStr);
        Node seqNode = doc.getElementsByTagName(APISynchronizationConstants.API_SEQUENCE).item(0);
        NamedNodeMap attr = seqNode.getAttributes();
        Node nodeAttr = attr.getNamedItem(APISynchronizationConstants.API_NAME);
        nodeAttr.setTextContent(seqElementName);
        String str = convertDocumentToString(doc);

        // ToDo Generalise the fix for automatic xmlns="" namespace (un)declaration
        str = str.replaceAll("xmlns=\"\"", APISynchronizationConstants.EMPTY_STRING);
        APIManagerConfiguration apimConfig = ServiceDataHolder.getInstance().getAPIManagerConfigurationService()
                .getAPIManagerConfiguration();
        String username = apimConfig.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME);
        tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = ServiceDataHolder.getInstance().getRealmService().getTenantManager()
                .getTenantId(tenantDomain);
        String path = CarbonUtils.getCarbonTenantsDirPath() + File.separator + tenantId + File.separator
                + "synapse-configs" + File.separator + "default" + File.separator + "sequences"
                + File.separator;

        File dir = new File(path);
        File file = new File(dir, seqFileName);
        FileUtils.writeStringToFile(file, str);
        if (log.isDebugEnabled()) {
            log.debug("Successfully deployed sequence: " + seqName);
        }
    } catch (UserStoreException e) {
        throw new APISynchronizationException(
                "An error occurred while obtaining tenant identifier of " + "tenant domain " + tenantDomain, e);
    } catch (FileNotFoundException e) {
        throw new APISynchronizationException("The file " + seqFileName + " could not be located.", e);
    } catch (IOException e) {
        throw new APISynchronizationException("An error occurred while reading the file " + seqFileName);
    }
}

From source file:org.wso2.carbon.apimgt.hybrid.gateway.configurator.XmlConfigurator.java

/**
 * Replace values in given Document/*from ww  w . j  av  a2 s.c  o m*/
 *
 * @param doc Document
 * @param xpathMap Map<String, String>
 * @param configProperties Properties
 * @throws XPathExpressionException
 */
private void replaceValues(Document doc, Map<String, String> xpathMap, Properties configProperties)
        throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    for (Map.Entry entry : xpathMap.entrySet()) {
        String xpathKey = (String) entry.getKey();
        String replaceKey = (String) entry.getValue();
        if (configProperties.containsKey(replaceKey) && configProperties.getProperty(replaceKey) != null
                && !configProperties.getProperty(replaceKey).isEmpty()) {
            Node node = (Node) xpath.evaluate("//" + xpathKey.replace(".", "/"), doc, XPathConstants.NODE);
            node.setTextContent(configProperties.getProperty(replaceKey));
        }
    }
}

From source file:org.wso2.carbon.dashboard.migratetool.DSCarFileMigrationTool.java

/**
 * Process unzipped car file in order to migrate to carbon-dashboards version 1.0.15+
 *
 * @param tempDirectory tempDirectory of unzipped car file directory
 */// w ww . j  a  va2 s.  com
private void migrateUnZippedCarFile(File tempDirectory) {
    for (int i = 0; i < tempDirectory.listFiles().length; i++) {
        File[] listOfFiles = tempDirectory.listFiles();
        File artifactPath = listOfFiles[i];
        File artifactXML = new File(artifactPath.getPath() + File.separator + ARTIFACT_XML);
        if (listOfFiles[i].isDirectory() && artifactXML.exists()) {
            try {
                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                Document doc = docBuilder.parse(artifactXML);
                doc.getDocumentElement().normalize();

                if (doc.getFirstChild().getAttributes().getNamedItem("type").getTextContent()
                        .equals(GADGET_ARTIFACT)) {
                    Node file = doc.getElementsByTagName("file").item(0);
                    file.setTextContent(file.getTextContent().toLowerCase());
                    saveArtifactXML(doc, artifactXML);
                    gadgetJSONUpdater(artifactPath);
                } else if (doc.getFirstChild().getAttributes().getNamedItem("type").getTextContent()
                        .equals(DASHBOARD_ARTIFACT)) {
                    Node file = doc.getElementsByTagName("file").item(0);
                    if (isDashboardArtifact(artifactPath, file.getTextContent())) {
                        dashboardUpdater(new File(artifactPath.getPath() + "/resources"));
                    }
                } else if (doc.getFirstChild().getAttributes().getNamedItem("type").getTextContent()
                        .equals("dashboards/dashboard")) {
                    dashboardUpdater(new File(artifactPath.getPath()));
                }

            } catch (ParserConfigurationException e) {
                log.error("Error in parsing artifact.xml of " + listOfFiles[i].getName(), e);
            } catch (IOException e) {
                log.error("Error in opening artifact.xml of " + listOfFiles[i].getName(), e);
            } catch (SAXException e) {
                log.error("Error in parsing artifact.xml of " + listOfFiles[i].getName(), e);
            }
        }
    }

}

From source file:org.wso2.carbon.device.mgt.mobile.windows.api.services.enrollment.impl.EnrollmentServiceImpl.java

/**
 * This method prepares the wap-provisioning file by including relevant certificates etc.
 *
 * @param binarySecurityToken     - CSR from device
 * @param wapProvisioningFilePath - File path of wap-provisioning file
 * @return - base64 encoded final wap-provisioning file as a String
 * @throws CertificateGenerationException
 * @throws org.wso2.carbon.device.mgt.mobile.windows.api.common.exceptions.WAPProvisioningException
 *///from  ww  w.j  ava 2  s  . c o m
private String prepareWapProvisioningXML(String binarySecurityToken, String wapProvisioningFilePath,
        String headerBst)
        throws CertificateGenerationException, WAPProvisioningException, WindowsDeviceEnrolmentException {
    String rootCertEncodedString;
    String signedCertEncodedString;
    X509Certificate signedCertificate;
    String provisioningXmlString;
    CertificateManagementServiceImpl certMgtServiceImpl = CertificateManagementServiceImpl.getInstance();
    Base64 base64Encoder = new Base64();
    try {
        X509Certificate rootCACertificate = (X509Certificate) certMgtServiceImpl.getCACertificate();
        rootCertEncodedString = base64Encoder.encodeAsString(rootCACertificate.getEncoded());

        signedCertificate = certMgtServiceImpl.getSignedCertificateFromCSR(binarySecurityToken);
        signedCertEncodedString = base64Encoder.encodeAsString(signedCertificate.getEncoded());

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        domFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        DocumentBuilder builder;

        builder = domFactory.newDocumentBuilder();
        Document document = builder.parse(wapProvisioningFilePath);
        NodeList wapParm = document.getElementsByTagName(PluginConstants.CertificateEnrolment.PARM);
        Node caCertificatePosition = wapParm.item(PluginConstants.CertificateEnrolment.CA_CERTIFICATE_POSITION);

        //Adding SHA1 CA certificate finger print to wap-provisioning xml.
        caCertificatePosition.getParentNode().getAttributes()
                .getNamedItem(PluginConstants.CertificateEnrolment.TYPE).setTextContent(
                        String.valueOf(DigestUtils.sha1Hex(rootCACertificate.getEncoded())).toUpperCase());
        //Adding encoded CA certificate to wap-provisioning file after removing new line
        // characters.
        NamedNodeMap rootCertAttributes = caCertificatePosition.getAttributes();
        Node rootCertNode = rootCertAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        rootCertEncodedString = rootCertEncodedString.replaceAll("\n", "");
        rootCertNode.setTextContent(rootCertEncodedString);

        if (log.isDebugEnabled()) {
            log.debug("Root certificate: " + rootCertEncodedString);
        }

        Node signedCertificatePosition = wapParm
                .item(PluginConstants.CertificateEnrolment.SIGNED_CERTIFICATE_POSITION);

        //Adding SHA1 signed certificate finger print to wap-provisioning xml.
        signedCertificatePosition.getParentNode().getAttributes()
                .getNamedItem(PluginConstants.CertificateEnrolment.TYPE).setTextContent(
                        String.valueOf(DigestUtils.sha1Hex(signedCertificate.getEncoded())).toUpperCase());

        //Adding encoded signed certificate to wap-provisioning file after removing new line
        // characters.
        NamedNodeMap clientCertAttributes = signedCertificatePosition.getAttributes();
        Node clientEncodedNode = clientCertAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        signedCertEncodedString = signedCertEncodedString.replaceAll("\n", "");

        clientEncodedNode.setTextContent(signedCertEncodedString);
        if (log.isDebugEnabled()) {
            log.debug("Signed certificate: " + signedCertEncodedString);
        }

        //Adding domainName to wap-provisioning xml.
        Node domainPosition = wapParm.item(PluginConstants.CertificateEnrolment.DOMAIN_POSITION);
        NamedNodeMap domainAttribute = domainPosition.getAttributes();
        Node domainNode = domainAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        domainNode.setTextContent(domain);

        //Adding Next provisioning service URL to wap-provisioning xml.
        Node syncmlServicePosition = wapParm
                .item(PluginConstants.CertificateEnrolment.SYNCML_PROVISIONING_ADDR_POSITION);
        NamedNodeMap syncmlServiceAttribute = syncmlServicePosition.getAttributes();
        Node syncmlServiceNode = syncmlServiceAttribute
                .getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        syncmlServiceNode.setTextContent(provisioningURL);

        // Adding user name auth token to wap-provisioning xml.
        Node userNameAuthPosition = wapParm
                .item(PluginConstants.CertificateEnrolment.APPAUTH_USERNAME_POSITION);
        NamedNodeMap appServerAttribute = userNameAuthPosition.getAttributes();
        Node authNameNode = appServerAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        String userName = getRequestedUser(headerBst);
        //CacheEntry cacheEntry = (CacheEntry) DeviceUtil.getCacheEntry(headerBst);
        // String userName = cacheEntry.getUsername();
        authNameNode.setTextContent(userName);
        DeviceUtil.removeTokenEntry(headerBst);
        String password = DeviceUtil.generateRandomToken();
        Node passwordAuthPosition = wapParm
                .item(PluginConstants.CertificateEnrolment.APPAUTH_PASSWORD_POSITION);
        NamedNodeMap appSrvPasswordAttribute = passwordAuthPosition.getAttributes();
        Node authPasswordNode = appSrvPasswordAttribute
                .getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        authPasswordNode.setTextContent(password);
        String requestSecurityTokenResponse = SyncmlCredentialUtil.generateRST(userName, password);
        DeviceUtil.persistChallengeToken(requestSecurityTokenResponse, null, userName);

        // Get device polling frequency from the tenant Configurations.
        Node numberOfFirstRetries = wapParm
                .item(PluginConstants.CertificateEnrolment.POLLING_FREQUENCY_POSITION);
        NamedNodeMap pollingAttributes = numberOfFirstRetries.getAttributes();
        Node pollValue = pollingAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        pollValue.setTextContent(pollingFrequency);
        provisioningXmlString = convertDocumentToString(document);
    } catch (ParserConfigurationException e) {
        throw new WAPProvisioningException("Problem occurred while creating configuration request", e);
    } catch (CertificateEncodingException e) {
        throw new WindowsDeviceEnrolmentException("Error occurred while encoding certificates.", e);
    } catch (SAXException e) {
        throw new WAPProvisioningException("Error occurred while parsing wap-provisioning.xml file.", e);
    } catch (TransformerException e) {
        throw new WAPProvisioningException("Error occurred while transforming wap-provisioning.xml file.", e);
    } catch (IOException e) {
        throw new WAPProvisioningException("Error occurred while getting wap-provisioning.xml file.", e);
    } catch (SyncmlMessageFormatException e) {
        throw new WindowsDeviceEnrolmentException("Error occurred while generating password hash value.", e);
    } catch (KeystoreException e) {
        throw new CertificateGenerationException("CA certificate cannot be generated.", e);
    }
    return base64Encoder.encodeAsString(provisioningXmlString.getBytes());
}

From source file:org.wso2.carbon.device.mgt.mobile.windows.api.services.wstep.impl.CertificateEnrollmentServiceImpl.java

/**
 * This method prepares the wap-provisioning file by including relevant certificates etc.
 *
 * @param binarySecurityToken     - CSR from device
 * @param wapProvisioningFilePath - File path of wap-provisioning file
 * @return - base64 encoded final wap-provisioning file as a String
 * @throws CertificateGenerationException
 * @throws org.wso2.carbon.device.mgt.mobile.windows.api.common.exceptions.WAPProvisioningException
 *//*from ww  w .  j a  va2s. c  o m*/
private String prepareWapProvisioningXML(String binarySecurityToken, String wapProvisioningFilePath,
        String headerBst)
        throws CertificateGenerationException, WAPProvisioningException, WindowsDeviceEnrolmentException {
    String rootCertEncodedString;
    String signedCertEncodedString;
    X509Certificate signedCertificate;
    String provisioningXmlString;

    CertificateManagementServiceImpl certMgtServiceImpl = CertificateManagementServiceImpl.getInstance();
    Base64 base64Encoder = new Base64();
    try {
        rootCACertificate = (X509Certificate) certMgtServiceImpl.getCACertificate();
        rootCertEncodedString = base64Encoder.encodeAsString(rootCACertificate.getEncoded());

        signedCertificate = certMgtServiceImpl.getSignedCertificateFromCSR(binarySecurityToken);
        signedCertEncodedString = base64Encoder.encodeAsString(signedCertificate.getEncoded());

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        domFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);

        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document document = builder.parse(wapProvisioningFilePath);
        NodeList wapParm = document.getElementsByTagName(PluginConstants.CertificateEnrolment.PARM);
        Node caCertificatePosition = wapParm.item(PluginConstants.CertificateEnrolment.CA_CERTIFICATE_POSITION);

        //Adding SHA1 CA certificate finger print to wap-provisioning xml.
        caCertificatePosition.getParentNode().getAttributes()
                .getNamedItem(PluginConstants.CertificateEnrolment.TYPE).setTextContent(
                        String.valueOf(DigestUtils.sha1Hex(rootCACertificate.getEncoded())).toUpperCase());
        //Adding encoded CA certificate to wap-provisioning file after removing new line
        // characters.
        NamedNodeMap rootCertAttributes = caCertificatePosition.getAttributes();
        Node rootCertNode = rootCertAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        rootCertEncodedString = rootCertEncodedString.replaceAll("\n", "");
        rootCertNode.setTextContent(rootCertEncodedString);

        if (log.isDebugEnabled()) {
            log.debug("Root certificate: " + rootCertEncodedString);
        }

        Node signedCertificatePosition = wapParm
                .item(PluginConstants.CertificateEnrolment.SIGNED_CERTIFICATE_POSITION);

        //Adding SHA1 signed certificate finger print to wap-provisioning xml.
        signedCertificatePosition.getParentNode().getAttributes()
                .getNamedItem(PluginConstants.CertificateEnrolment.TYPE).setTextContent(
                        String.valueOf(DigestUtils.sha1Hex(signedCertificate.getEncoded())).toUpperCase());

        //Adding encoded signed certificate to wap-provisioning file after removing new line
        // characters.
        NamedNodeMap clientCertAttributes = signedCertificatePosition.getAttributes();
        Node clientEncodedNode = clientCertAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        signedCertEncodedString = signedCertEncodedString.replaceAll("\n", "");

        clientEncodedNode.setTextContent(signedCertEncodedString);
        if (log.isDebugEnabled()) {
            log.debug("Signed certificate: " + signedCertEncodedString);
        }

        //Adding domainName to wap-provisioning xml.
        Node domainPosition = wapParm.item(PluginConstants.CertificateEnrolment.DOMAIN_POSITION);
        NamedNodeMap domainAttribute = domainPosition.getAttributes();
        Node domainNode = domainAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        domainNode.setTextContent(domain);

        //Adding Next provisioning service URL to wap-provisioning xml.
        Node syncmlServicePosition = wapParm
                .item(PluginConstants.CertificateEnrolment.SYNCML_PROVISIONING_ADDR_POSITION);
        NamedNodeMap syncmlServiceAttribute = syncmlServicePosition.getAttributes();
        Node syncmlServiceNode = syncmlServiceAttribute
                .getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        syncmlServiceNode.setTextContent(provisioningURL);

        // Adding user name auth token to wap-provisioning xml.
        Node userNameAuthPosition = wapParm
                .item(PluginConstants.CertificateEnrolment.APPAUTH_USERNAME_POSITION);
        NamedNodeMap appServerAttribute = userNameAuthPosition.getAttributes();
        Node authNameNode = appServerAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        MobileCacheEntry cacheEntry = DeviceUtil.getTokenEntry(headerBst);
        String userName = cacheEntry.getUsername();
        authNameNode.setTextContent(cacheEntry.getUsername());
        DeviceUtil.removeTokenEntry(headerBst);
        String password = DeviceUtil.generateRandomToken();
        Node passwordAuthPosition = wapParm
                .item(PluginConstants.CertificateEnrolment.APPAUTH_PASSWORD_POSITION);
        NamedNodeMap appSrvPasswordAttribute = passwordAuthPosition.getAttributes();
        Node authPasswordNode = appSrvPasswordAttribute
                .getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        authPasswordNode.setTextContent(password);
        String requestSecurityTokenResponse = SyncmlCredentialUtil.generateRST(userName, password);
        DeviceUtil.persistChallengeToken(requestSecurityTokenResponse, null, userName);

        // Get device polling frequency from the tenant Configurations.
        Node numberOfFirstRetries = wapParm
                .item(PluginConstants.CertificateEnrolment.POLLING_FREQUENCY_POSITION);
        NamedNodeMap pollingAttributes = numberOfFirstRetries.getAttributes();
        Node pollValue = pollingAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        pollValue.setTextContent(pollingFrequency);
        provisioningXmlString = convertDocumentToString(document);

    } catch (ParserConfigurationException e) {
        throw new WAPProvisioningException("Problem occurred while creating configuration request", e);
    } catch (CertificateEncodingException e) {
        throw new WindowsDeviceEnrolmentException("Error occurred while encoding certificates.", e);
    } catch (SAXException e) {
        throw new WAPProvisioningException("Error occurred while parsing wap-provisioning.xml file.", e);
    } catch (TransformerException e) {
        throw new WAPProvisioningException("Error occurred while transforming wap-provisioning.xml file.", e);
    } catch (IOException e) {
        throw new WAPProvisioningException("Error occurred while getting wap-provisioning.xml file.", e);
    } catch (SyncmlMessageFormatException e) {
        throw new WindowsDeviceEnrolmentException("Error occurred while generating password hash value.", e);
    } catch (KeystoreException e) {
        throw new CertificateGenerationException("CA certificate cannot be generated.", e);
    }
    return base64Encoder.encodeAsString(provisioningXmlString.getBytes());
}

From source file:org.wso2.carbon.humantask.core.api.rendering.HTRenderingApiImpl.java

/**
 * Function to update xml DOM element according to the xpath expression with given string value
 *
 * @param xmlElement DOM element representing the xml
 * @param xPathExpression xpath expression
 * @param value string that need to replace in the xml
 * @param referanceDoc reference Document which represents original ht rendering element, which used to resolve
 *                     namespaces mentioned in the xpath expression
 * @return/*from   www . j  a  va  2 s  .c om*/
 * @throws XPathExpressionException
 */
private Element updateXmlByXpath(Element xmlElement, String xPathExpression, String value,
        Document referanceDoc) throws XPathExpressionException {
    if (xPathExpression.length() > 0) {
        //Evaluate XPath
        XPath xPath = XPathFactory.newInstance().newXPath();
        NamespaceResolver nsResolver = new NamespaceResolver(referanceDoc);
        xPath.setNamespaceContext(nsResolver);

        Node result = (Node) xPath.evaluate(xPathExpression, xmlElement, XPathConstants.NODE);
        result.setTextContent(value);
    }

    return xmlElement;
}

From source file:org.wso2.carbon.mdm.mobileservices.windows.services.wstep.impl.CertificateEnrollmentServiceImpl.java

/**
 * This method prepares the wap-provisioning file by including relevant certificates etc
 *
 * @param binarySecurityToken     - CSR from device
 * @param wapProvisioningFilePath - File path of wap-provisioning file
 * @return - base64 encoded final wap-provisioning file as a String
 * @throws CertificateGenerationException
 * @throws org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.WAPProvisioningException
 *///from   ww  w  .  j a  v a2  s .c  om
public String prepareWapProvisioningXML(String binarySecurityToken, String wapProvisioningFilePath,
        String headerBst)
        throws CertificateGenerationException, WAPProvisioningException, WindowsDeviceEnrolmentException {

    String rootCertEncodedString;
    String signedCertEncodedString;
    X509Certificate signedCertificate;

    CertificateManagementServiceImpl impl = CertificateManagementServiceImpl.getInstance();
    Base64 base64Encoder = new Base64();
    try {
        rootCACertificate = (X509Certificate) impl.getCACertificate();
        rootCertEncodedString = base64Encoder.encodeToString(rootCACertificate.getEncoded());
    } catch (KeystoreException e) {
        String msg = "CA certificate cannot be generated";
        log.error(msg, e);
        throw new CertificateGenerationException(msg, e);
    } catch (CertificateEncodingException e) {
        String msg = "CA certificate cannot be encoded.";
        log.error(msg, e);
        throw new CertificateGenerationException(msg, e);
    }

    try {
        signedCertificate = impl.getSignedCertificateFromCSR(binarySecurityToken);
        signedCertEncodedString = base64Encoder.encodeToString(signedCertificate.getEncoded());
    } catch (CertificateEncodingException e) {
        String msg = "Singed certificate cannot be encoded.";
        log.error(msg, e);
        throw new CertificateGenerationException(msg, e);
    } catch (KeystoreException e) {
        String msg = "CA certificate cannot be generated";
        log.error(msg, e);
        throw new CertificateGenerationException(msg, e);
    }
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    String wapProvisioningString = null;
    try {
        builder = domFactory.newDocumentBuilder();

        Document document = builder.parse(wapProvisioningFilePath);
        NodeList wapParm = document.getElementsByTagName(PluginConstants.CertificateEnrolment.PARM);
        Node caCertificatePosition = wapParm.item(CA_CERTIFICATE_POSITION);

        //Adding SHA1 CA certificate finger print to wap-provisioning xml.
        caCertificatePosition.getParentNode().getAttributes()
                .getNamedItem(PluginConstants.CertificateEnrolment.TYPE).setTextContent(
                        String.valueOf(DigestUtils.sha512Hex(rootCACertificate.getEncoded())).toUpperCase());
        //Adding encoded CA certificate to wap-provisioning file after removing new line
        // characters.
        NamedNodeMap rootCertAttributes = caCertificatePosition.getAttributes();
        Node rootCertNode = rootCertAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        rootCertEncodedString = rootCertEncodedString.replaceAll("\n", "");
        rootCertNode.setTextContent(rootCertEncodedString);

        if (log.isDebugEnabled()) {
            log.debug("Root certificate: " + rootCertEncodedString);
        }

        Node signedCertificatePosition = wapParm.item(SIGNED_CERTIFICATE_POSITION);

        //Adding SHA1 signed certificate finger print to wap-provisioning xml.
        signedCertificatePosition.getParentNode().getAttributes()
                .getNamedItem(PluginConstants.CertificateEnrolment.TYPE).setTextContent(
                        String.valueOf(DigestUtils.sha512Hex(signedCertificate.getEncoded())).toUpperCase());

        //Adding encoded signed certificate to wap-provisioning file after removing new line
        // characters.
        NamedNodeMap clientCertAttributes = signedCertificatePosition.getAttributes();
        Node clientEncodedNode = clientCertAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        signedCertEncodedString = signedCertEncodedString.replaceAll("\n", "");

        clientEncodedNode.setTextContent(signedCertEncodedString);
        if (log.isDebugEnabled()) {
            log.debug("Signed certificate: " + signedCertEncodedString);
        }

        // Adding user name auth token to wap-provisioning xml
        Node userNameAuthPosition = wapParm.item(APPAUTH_USERNAME_POSITION);
        NamedNodeMap appServerAttribute = userNameAuthPosition.getAttributes();
        Node authNameNode = appServerAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        CacheEntry cacheEntry = (CacheEntry) DeviceUtil.getCacheEntry(headerBst);
        String userName = cacheEntry.getUsername();
        authNameNode.setTextContent(cacheEntry.getUsername());
        DeviceUtil.removeToken(headerBst);
        String password = DeviceUtil.generateRandomToken();
        Node passwordAuthPosition = wapParm.item(APPAUTH_PASSWORD_POSITION);
        NamedNodeMap appSrvPasswordAttribute = passwordAuthPosition.getAttributes();
        Node authPasswordNode = appSrvPasswordAttribute
                .getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        authPasswordNode.setTextContent(password);
        String requestSecurityTokenResponse = new SyncmlCredentials().generateRST(userName, password);
        DeviceUtil.persistChallengeToken(requestSecurityTokenResponse, null, userName);

        // Get device polling frequency from the tenant Configurations.
        Node numberOfFirstRetries = wapParm.item(POLLING_FREQUENCY_POSITION);
        NamedNodeMap pollingAttributes = numberOfFirstRetries.getAttributes();
        Node pollValue = pollingAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        pollValue.setTextContent(pollingFrequency);
        if (log.isDebugEnabled()) {
            log.debug("Username: " + userName + "Password: " + requestSecurityTokenResponse);
        }
        wapProvisioningString = convertDocumentToString(document);
    } catch (ParserConfigurationException e) {
        String msg = "Problem occurred in parsing wap-provisioning.xml file.";
        log.error(msg, e);
        throw new WAPProvisioningException(msg, e);
    } catch (DeviceManagementException e) {
        String msg = "Error occurred in while getting CA and Root certificates.";
        log.error(msg, e);
        throw new WindowsDeviceEnrolmentException(msg, e);
    } catch (CertificateEncodingException e) {
        String msg = "Error occurred in while encoding certificates.";
        log.error(msg, e);
        throw new WindowsDeviceEnrolmentException(msg, e);
    } catch (UnsupportedEncodingException e) {
        String msg = "Error occurred in while encoding wap-provisioning file.";
        log.error(msg, e);
        throw new WindowsDeviceEnrolmentException(msg, e);
    } catch (SAXException e) {
        String msg = "Error occurred in while parsing wap-provisioning.xml file.";
        log.error(msg, e);
        throw new WAPProvisioningException(msg, e);
    } catch (TransformerException e) {
        String msg = "Error occurred in while transforming wap-provisioning.xml file.";
        log.error(msg, e);
        throw new WAPProvisioningException(msg, e);
    } catch (IOException e) {
        String msg = "Error occurred in while getting wap-provisioning.xml file.";
        log.error(msg, e);
        throw new WAPProvisioningException(msg, e);
    } catch (SyncmlMessageFormatException e) {
        String msg = "Error occurred in while getting CA and Root certificates.";
        log.error(msg, e);
        throw new WindowsDeviceEnrolmentException(msg, e);
    }
    return base64Encoder.encodeToString(wapProvisioningString.getBytes());
}

From source file:org.wso2.carbon.mdm.mobileservices.windowspc.services.wstep.impl.CertificateEnrollmentServiceImpl.java

/**
 * This method prepares the wap-provisioning file by including relevant certificates etc
 *
 * @param binarySecurityToken     - CSR from device
 * @param certPropertyList        - property list for signed certificate
 * @param wapProvisioningFilePath - File path of wap-provisioning file
 * @return - base64 encoded final wap-provisioning file
 * @throws CertificateGenerationException
 * @throws XMLFileOperationException/*from  w ww .ja  va 2  s  . co m*/
 */
public String prepareWapProvisioningXML(String binarySecurityToken, List certPropertyList,
        String wapProvisioningFilePath) throws CertificateGenerationException, XMLFileOperationException {

    byte[] DERByteArray = javax.xml.bind.DatatypeConverter.parseBase64Binary(binarySecurityToken);
    PKCS10CertificationRequest certificationRequest;
    try {
        certificationRequest = new PKCS10CertificationRequest(DERByteArray);
    } catch (IOException e) {
        throw new CertificateGenerationException("CSR cannot be recovered.", e);
    }

    JcaPKCS10CertificationRequest CSRRequest = new JcaPKCS10CertificationRequest(certificationRequest);

    X509Certificate signedCertificate = CertificateSigningService.signCSR(CSRRequest, privateKey,
            rootCACertificate, certPropertyList);

    BASE64Encoder base64Encoder = new BASE64Encoder();
    String rootCertEncodedString;
    try {
        rootCertEncodedString = base64Encoder.encode(rootCACertificate.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new CertificateGenerationException("CA certificate cannot be encoded.", e);
    }
    String signedCertEncodedString;
    try {
        signedCertEncodedString = base64Encoder.encode(signedCertificate.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new CertificateGenerationException("Singed certificate cannot be encoded.", e);
    }

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    String wapProvisioningString;
    try {
        builder = domFactory.newDocumentBuilder();
        Document document = builder.parse(wapProvisioningFilePath);
        NodeList wapParm = document.getElementsByTagName(Constants.CertificateEnrollment.PARM);
        Node CACertificatePosition = wapParm.item(CA_CERTIFICATE_POSITION);

        //Adding SHA1 CA certificate finger print to wap-provisioning xml.
        CACertificatePosition.getParentNode().getAttributes().getNamedItem(Constants.CertificateEnrollment.TYPE)
                .setTextContent(
                        String.valueOf(DigestUtils.sha1Hex(rootCACertificate.getEncoded())).toUpperCase());

        //Adding encoded CA certificate to wap-provisioning file after removing new line
        // characters.
        NamedNodeMap rootCertAttributes = CACertificatePosition.getAttributes();
        Node rootCertNode = rootCertAttributes.getNamedItem(Constants.CertificateEnrollment.VALUE);
        rootCertEncodedString = rootCertEncodedString.replaceAll("\n", "");
        rootCertNode.setTextContent(rootCertEncodedString);

        if (logger.isDebugEnabled()) {
            logger.debug("Root certificate:" + rootCertEncodedString);
        }

        Node signedCertificatePosition = wapParm.item(SIGNED_CERTIFICATE_POSITION);

        //Adding SHA1 signed certificate finger print to wap-provisioning xml.
        signedCertificatePosition.getParentNode().getAttributes()
                .getNamedItem(Constants.CertificateEnrollment.TYPE).setTextContent(
                        String.valueOf(DigestUtils.sha1Hex(signedCertificate.getEncoded())).toUpperCase());

        //Adding encoded signed certificate to wap-provisioning file after removing new line
        // characters.
        NamedNodeMap clientCertAttributes = signedCertificatePosition.getAttributes();
        Node clientEncodedNode = clientCertAttributes.getNamedItem(Constants.CertificateEnrollment.VALUE);
        signedCertEncodedString = signedCertEncodedString.replaceAll("\n", "");
        clientEncodedNode.setTextContent(signedCertEncodedString);
        if (logger.isDebugEnabled()) {
            logger.debug("Signed certificate:" + signedCertEncodedString);
        }
        wapProvisioningString = convertDocumentToString(document);
        //Generic exception is caught here as there is no need of taking different actions for
        // different exceptions.
    } catch (Exception e) {
        throw new XMLFileOperationException("Problem occurred with wap-provisioning.xml file.", e);
    }
    String encodedWap = base64Encoder.encode(wapProvisioningString.getBytes());
    return encodedWap;
}

From source file:org.wso2.developerstudio.eclipse.artifact.axis2.project.refactor.Axis2ServicesXMLFileChange.java

/**
 * Update DOM Document with new Axis2 service class name
 *
 * @param document a DOM Document//from  w ww .  j  a v a  2 s  .  c o  m
 */
private void updateDocumentWithNewClassName(Document document) {
    //Getting all service nodes from document
    NodeList serviceList = document.getElementsByTagName(SERVICE_ELEMENT_NAME);

    //Looping through each service node to find which service to update with new class name
    for (int i = 0; i < serviceList.getLength(); i++) {
        Node service = serviceList.item(i);
        NodeList serviceChildNodes = service.getChildNodes();

        //Looping through each child node to find the node named as 'parameter'
        for (int j = 0; j < serviceChildNodes.getLength(); j++) {
            Node node = serviceChildNodes.item(j);
            if (PARAMETER_ELEMENT_NAME.equals(node.getNodeName())) {
                NamedNodeMap attr = node.getAttributes();
                Node nodeAttr = attr.getNamedItem(NAME_ATTRIBUTE);
                //If the 'name' attribute value is 'ServiceClass', then updating the node
                if (nodeAttr.getNodeValue().equals(SERVICE_CLASS_IDENTIFIER)) {
                    String oldFullyQualifiedClassName = node.getTextContent();
                    String packageName = Axis2Utils.extractPackageName(oldFullyQualifiedClassName);
                    String className = Axis2Utils.extractClassName(oldFullyQualifiedClassName);
                    if (className.equals(previousClassName)) {
                        node.setTextContent(packageName + "." + newClassName);
                        break;
                    }
                }
            }
        }
    }
}