Example usage for org.w3c.dom Node hasChildNodes

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

Introduction

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

Prototype

public boolean hasChildNodes();

Source Link

Document

Returns whether this node has any children.

Usage

From source file:org.tizzit.util.XercesHelper.java

public static String node2string(Node nde) {
    StringBuffer sb = new StringBuffer();
    String attributes = "";
    if (nde.hasAttributes()) {
        NamedNodeMap attr = nde.getAttributes();
        for (int j = 0; j < attr.getLength(); j++) {
            attributes += " " + attr.item(j).getNodeName() + "=\"" + getHexEncoded(attr.item(j).getNodeValue())
                    + "\"";
        }//from   w w w.  j  a v  a  2  s .  c om
    }
    sb.append("<" + nde.getNodeName() + attributes);
    if (nde.hasChildNodes()) {
        sb.append(">" + nodeList2string(nde.getChildNodes()) + "</" + nde.getNodeName() + ">");
    } else {
        sb.append("/>");
    }
    return sb.toString();
}

From source file:org.tizzit.util.XercesHelper.java

public static String nodeList2string(NodeList nl) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < nl.getLength(); i++) {
        Node nde = nl.item(i);
        String attributes = "";
        if (nde.getNodeType() == Node.TEXT_NODE) {
            sb.append(getHexEncoded(nde.getNodeValue()));
            if (nde.hasChildNodes()) {
                sb.append(nodeList2string(nde.getChildNodes()));
            }//from   w w  w  . j  a va2s. co  m
        } else if (nde.getNodeType() == Node.CDATA_SECTION_NODE) {
            sb.append("<![CDATA[" + nde.getNodeValue() + "]]>");
        } else if (nde.getNodeType() == Node.COMMENT_NODE) {
            sb.append("<!-- -->");
        } else {
            if (nde.hasAttributes()) {
                NamedNodeMap attr = nde.getAttributes();
                for (int j = 0; j < attr.getLength(); j++) {
                    attributes += " " + attr.item(j).getNodeName() + "=\""
                            + getHexEncoded(attr.item(j).getNodeValue()) + "\"";
                }
            }
            sb.append("<" + nde.getNodeName() + attributes);
            if (nde.hasChildNodes()) {
                sb.append(">" + nodeList2string(nde.getChildNodes()) + "</" + nde.getNodeName() + ">");
            } else {
                sb.append("/>");
            }
        }
    }
    return sb.toString();
}

From source file:org.warlock.itk.distributionenvelope.Payload.java

/**
 * Extracts the content of an "Object" element element of the enveloping 
 * signature - see the W3 XML Encryption specification.
 * @param signature//w  w w.  ja v a 2  s.co m
 * @return
 * @throws Exception 
 */
private byte[] getSignatureObject(Element signature) throws Exception {
    //        NodeList nl = signature.getElementsByTagNameNS(CfHNamespaceContext.DSNAMESPACE, "Object");
    //        if (nl.getLength() == 0) {
    //            throw new Exception("Error retrieving object from signature");
    //        }
    //        String object = ((Element)nl.item(0)).getTextContent();
    //        return object.getBytes();
    NodeList nl = signature.getElementsByTagNameNS(CfHNamespaceContext.DSNAMESPACE, "Object");
    if (nl.getLength() == 0) {
        throw new Exception("Error retrieving object from signature");
    }
    StringWriter outfile = new StringWriter();
    StreamResult sr = new StreamResult(outfile);
    Transformer tx = TransformerFactory.newInstance().newTransformer();
    String out;
    Node n = (Node) nl.item(0);
    NodeList subnl = n.getChildNodes();
    Node subn = (Node) subnl.item(0);
    if (subn.hasChildNodes()) {
        tx.transform(new DOMSource((Node) subnl.item(0)), sr);
        out = outfile.toString();
        if (out.indexOf("<?xml ") == 0) {
            out = out.substring(out.indexOf("?>") + "?>".length());
        }
    } else {
        out = n.getTextContent();
    }

    return out.getBytes();
}

From source file:org.wso2.balana.ConfigurationStore.java

/**
 * Private helper that is used by all the code to load an instance of the given class...this
 * assumes that the class is in the classpath, both for simplicity and for stronger security
 *//*from  www .  ja  va  2  s .  c  o m*/
private Object loadClass(String prefix, Node root) throws ParsingException {
    // get the name of the class
    String className = root.getAttributes().getNamedItem("class").getNodeValue();

    if (logger.isDebugEnabled()) {
        logger.debug("Loading [ " + prefix + ": " + className + " ]");
    }

    // load the given class using the local classloader
    Class c = null;
    try {
        c = loader.loadClass(className);
    } catch (ClassNotFoundException cnfe) {
        throw new ParsingException("couldn't load class " + className, cnfe);
    }
    Object instance = null;

    // figure out if there are any parameters to the constructor
    if (!root.hasChildNodes()) {
        // we're using a null constructor, so this is easy
        try {
            instance = c.newInstance();
        } catch (InstantiationException ie) {
            throw new ParsingException("couldn't instantiate " + className + " with empty constructor", ie);
        } catch (IllegalAccessException iae) {
            throw new ParsingException("couldn't get access to instance " + "of " + className, iae);
        }
    } else {
        // parse the arguments to the constructor
        Set<Object> args = null;
        try {
            args = getArgs(root);
        } catch (IllegalArgumentException iae) {
            throw new ParsingException("illegal class arguments", iae);
        }
        int argLength = args.size();

        // next we need to see if there's a constructor that matches the
        // arguments provided...this has to be done by hand since
        // Class.getConstructor(Class []) doesn't handle sub-classes and
        // generic types (for instance, a constructor taking List won't
        // match a parameter list containing ArrayList)

        // get the list of all available constructors
        Constructor[] cons = c.getConstructors();
        Constructor constructor = null;

        for (int i = 0; i < cons.length; i++) {
            // get the parameters for this constructor
            Class[] params = cons[i].getParameterTypes();
            if (params.length == argLength) {
                Iterator it = args.iterator();
                int j = 0;

                // loop through the parameters and see if each one is
                // assignable from the coresponding input argument
                while (it.hasNext()) {
                    if (!params[j].isAssignableFrom(it.next().getClass()))
                        break;
                    j++;
                }

                // if we looked at all the parameters, then this
                // constructor matches the input
                if (j == argLength)
                    constructor = cons[i];
            }

            // if we've found a matching constructor then stop looping
            if (constructor != null)
                break;
        }

        // make sure we found a matching constructor
        if (constructor == null)
            throw new ParsingException("couldn't find a matching " + "constructor");

        // finally, instantiate the class
        try {
            instance = constructor.newInstance(args.toArray());
        } catch (InstantiationException ie) {
            throw new ParsingException("couldn't instantiate " + className, ie);
        } catch (IllegalAccessException iae) {
            throw new ParsingException("couldn't get access to instance " + "of " + className, iae);
        } catch (InvocationTargetException ite) {
            throw new ParsingException("couldn't create " + className, ite);
        }
    }

    return instance;
}

From source file:org.wso2.carbon.dashboard.template.deployer.DashboardTemplateDeployer.java

@Override
public void deployArtifact(DeployableTemplate template) throws TemplateDeploymentException {

    String artifactId = template.getArtifactId();
    String content = null;/*www.  j a  v  a 2s  . c o m*/

    Map<String, String> properties = new HashMap<>();

    DocumentBuilderFactory factory = getSecuredDocumentBuilder();
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(template.getArtifact())));
        NodeList configNodes = document.getElementsByTagName(DashboardTemplateDeployerConstants.CONFIG_TAG);
        if (configNodes.getLength() > 0) {
            Node configNode = configNodes.item(0); // Only one node is expected
            if (configNode.hasChildNodes()) {

                // Extract the details
                NodeList nodeList = configNode.getChildNodes();
                for (int i = 0; i < nodeList.getLength(); i++) {
                    Node node = nodeList.item(i);
                    if (DashboardTemplateDeployerConstants.PROPERTIES_TAG.equalsIgnoreCase(node.getNodeName())
                            && node.hasChildNodes()) {
                        // Properties
                        NodeList propertiesNodeList = node.getChildNodes();
                        for (int j = 0; j < propertiesNodeList.getLength(); j++) {
                            Node propertyNode = propertiesNodeList.item(j);
                            if (DashboardTemplateDeployerConstants.PROPERTY_TAG
                                    .equalsIgnoreCase(propertyNode.getNodeName())) {
                                Attr attr = (Attr) propertyNode.getAttributes()
                                        .getNamedItem(DashboardTemplateDeployerConstants.NAME_ATTRIBUTE);
                                properties.put(attr.getValue(),
                                        propertyNode.getFirstChild().getNodeValue().trim());
                            }
                        }
                    } else if (DashboardTemplateDeployerConstants.CONTENT_TAG
                            .equalsIgnoreCase(node.getNodeName())) {
                        content = node.getFirstChild().getNodeValue();
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        throw new DashboardTemplateDeployerException("Error in creating XML document builder.", e);
    } catch (SAXException e) {
        throw new DashboardTemplateDeployerException("Error in parsing XML content of: " + artifactId, e);
    } catch (IOException e) {
        throw new DashboardTemplateDeployerException("Error in loading XML content of: " + artifactId, e);
    }

    if (content == null || content.trim().isEmpty()) {
        throw new DashboardTemplateDeployerException("Empty dashboard content for artifact: " + artifactId);
    }

    // Store the directory name for the artifact id
    Registry registry = DashboardTemplateDeployerUtility.getRegistry();
    try {
        Resource resource;
        if (registry.resourceExists(DashboardTemplateDeployerConstants.ARTIFACT_DASHBOARD_ID_MAPPING_PATH)) {
            // If same gadgets for same artifact exist, remove them first
            resource = registry.get(DashboardTemplateDeployerConstants.ARTIFACT_DASHBOARD_ID_MAPPING_PATH);

            // Delete this artifact if exists
            if (resource.getProperty(artifactId) != null) {
                undeployArtifact(artifactId);
            }
        } else {
            resource = registry.newResource();
        }
        resource.setProperty(artifactId, properties.get(DashboardTemplateDeployerConstants.DASHBOARD_ID));
        // Save the resource
        registry.put(DashboardTemplateDeployerConstants.ARTIFACT_DASHBOARD_ID_MAPPING_PATH, resource);
    } catch (RegistryException e) {
        throw new DashboardTemplateDeployerException("Failed to access resource at: "
                + DashboardTemplateDeployerConstants.ARTIFACT_DASHBOARD_ID_MAPPING_PATH + " in registry", e);
    }

    try {
        Resource resource = registry.newResource();
        resource.setContent(content);
        resource.setMediaType("application/json");
        registry.put(DashboardTemplateDeployerConstants.DASHBOARDS_RESOURCE_PATH
                + properties.get(DashboardTemplateDeployerConstants.DASHBOARD_ID), resource);

        log.info("Dashboard definition of [" + artifactId + "] has been created.");
    } catch (RegistryException e) {
        throw new DashboardTemplateDeployerException("Failed to access resource at: "
                + DashboardTemplateDeployerConstants.ARTIFACT_DASHBOARD_ID_MAPPING_PATH + " in registry", e);
    }

}

From source file:org.wso2.carbon.datasource.core.utils.RDBMSDataSourceUtils.java

public static void resolveLeafNodeValue(Node node) {
    if (node != null) {
        Element element = (Element) node;
        NodeList childNodeList = element.getChildNodes();
        for (int j = 0; j < childNodeList.getLength(); j++) {
            Node chileNode = childNodeList.item(j);
            if (!chileNode.hasChildNodes()) {
                String nodeValue = resolveSystemProperty(chileNode.getTextContent());
                childNodeList.item(j).setTextContent(nodeValue);
            } else {
                resolveLeafNodeValue(chileNode);
            }// w w  w .  j  a v a2  s.c  o  m
        }
    }
}

From source file:org.wso2.carbon.gadget.template.deployer.GadgetTemplateDeployer.java

@Override
public void deployArtifact(DeployableTemplate template) throws TemplateDeploymentException {

    String artifactId = template.getArtifactId();
    String content = template.getArtifact();

    Map<String, String> artifacts = new HashMap<>();
    Map<String, String> properties = new HashMap<>();

    DocumentBuilderFactory factory = getSecuredDocumentBuilder();
    try {/* w w  w  . j a  v  a2s.co  m*/
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(content)));
        NodeList configNodes = document.getElementsByTagName(GadgetTemplateDeployerConstants.CONFIG_TAG);
        if (configNodes.getLength() > 0) {
            Node configNode = configNodes.item(0); // Only one node is expected
            if (configNode.hasChildNodes()) {

                // Extract the details
                NodeList nodeList = configNode.getChildNodes();
                for (int i = 0; i < nodeList.getLength(); i++) {
                    Node node = nodeList.item(i);
                    if (GadgetTemplateDeployerConstants.PROPERTIES_TAG.equalsIgnoreCase(node.getNodeName())
                            && node.hasChildNodes()) {
                        // Properties
                        NodeList propertiesNodeList = node.getChildNodes();
                        for (int j = 0; j < propertiesNodeList.getLength(); j++) {
                            Node propertyNode = propertiesNodeList.item(j);
                            if (GadgetTemplateDeployerConstants.PROPERTY_TAG
                                    .equalsIgnoreCase(propertyNode.getNodeName())) {
                                Attr attr = (Attr) propertyNode.getAttributes()
                                        .getNamedItem(GadgetTemplateDeployerConstants.NAME_ATTRIBUTE);
                                properties.put(attr.getValue(),
                                        propertyNode.getFirstChild().getNodeValue().trim());
                            }
                        }
                    } else if (GadgetTemplateDeployerConstants.ARTIFACTS_TAG
                            .equalsIgnoreCase(node.getNodeName()) && node.hasChildNodes()) {
                        NodeList artifactNodeList = node.getChildNodes();
                        for (int j = 0; j < artifactNodeList.getLength(); j++) {
                            Node artifactNode = artifactNodeList.item(j);
                            if (GadgetTemplateDeployerConstants.ARTIFACT_TAG
                                    .equalsIgnoreCase(artifactNode.getNodeName())) {
                                Attr attr = (Attr) artifactNode.getAttributes()
                                        .getNamedItem(GadgetTemplateDeployerConstants.FILE_ATTRIBUTE);
                                artifacts.put(attr.getValue(), artifactNode.getFirstChild().getNodeValue());
                            }
                        }
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        throw new GadgetTemplateDeployerException("Error in creating XML document builder.", e);
    } catch (SAXException e) {
        throw new GadgetTemplateDeployerException("Error in parsing XML content of: " + artifactId, e);
    } catch (IOException e) {
        throw new GadgetTemplateDeployerException("Error in loading XML content of: " + artifactId, e);
    }

    if (!properties.containsKey(GadgetTemplateDeployerConstants.DIRECTORY_NAME)) {
        throw new GadgetTemplateDeployerException(
                "Artifact does not contain " + GadgetTemplateDeployerConstants.DIRECTORY_NAME + " property.");
    }

    String gadgetArtifactPath = GadgetTemplateDeployerUtility.getGadgetArtifactPath();
    File destination = new File(
            gadgetArtifactPath + properties.get(GadgetTemplateDeployerConstants.DIRECTORY_NAME));
    GadgetTemplateDeployerUtility.validatePath(properties.get(GadgetTemplateDeployerConstants.DIRECTORY_NAME));

    // Store the directory name for the artifact id
    Registry registry = GadgetTemplateDeployerUtility.getRegistry();
    try {
        Resource resource;
        if (registry.resourceExists(GadgetTemplateDeployerConstants.ARTIFACT_DIRECTORY_MAPPING_PATH)) {
            // If same gadgets for same artifact exist, remove them first
            resource = registry.get(GadgetTemplateDeployerConstants.ARTIFACT_DIRECTORY_MAPPING_PATH);

            // Delete this artifact if exists
            if (resource.getProperty(artifactId) != null) {
                undeployArtifact(artifactId);
            }
        } else {
            resource = registry.newResource();
        }
        resource.setProperty(artifactId, properties.get(GadgetTemplateDeployerConstants.DIRECTORY_NAME));
        // Save the resource
        registry.put(GadgetTemplateDeployerConstants.ARTIFACT_DIRECTORY_MAPPING_PATH, resource);
    } catch (RegistryException e) {
        throw new GadgetTemplateDeployerException(
                "Failed to access resource at: "
                        + GadgetTemplateDeployerConstants.ARTIFACT_DIRECTORY_MAPPING_PATH + " from registry",
                e);
    }

    // Copy the static files
    String templateParentDir = new StringBuilder(CarbonUtils.getCarbonConfigDirPath()).append(File.separator)
            .append(GadgetTemplateDeployerConstants.TEMPLATE_MANAGER).append(File.separator)
            .append(GadgetTemplateDeployerConstants.GADGET_TEMPLATES).toString();
    File templateDirectory = new File(templateParentDir,
            properties.get(GadgetTemplateDeployerConstants.TEMPLATE_DIRECTORY));
    GadgetTemplateDeployerUtility
            .validatePath(properties.get(GadgetTemplateDeployerConstants.TEMPLATE_DIRECTORY));

    // Copy all the default templates
    try {
        FileUtils.copyDirectory(templateDirectory, destination);
    } catch (IOException e) {
        throw new GadgetTemplateDeployerException("Failed to copy " + templateDirectory.getAbsolutePath()
                + " to " + destination.getAbsolutePath(), e);
    }

    // Save the artifacts
    for (Map.Entry<String, String> entry : artifacts.entrySet()) {
        String fileName = entry.getKey();
        GadgetTemplateDeployerUtility.validatePath(fileName);
        File targetFile = new File(destination, fileName);
        FileWriter writer = null;
        try {
            writer = new FileWriter(targetFile);
            writer.write(entry.getValue());
        } catch (IOException e) {
            throw new GadgetTemplateDeployerException(
                    "Failed to write artifact to: " + targetFile.getAbsolutePath(), e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    log.warn("Failed to close FileWriter of " + targetFile.getAbsolutePath());
                }
            }
        }
    }
    log.info("Deployed successfully gadget: " + artifactId);
}

From source file:org.wso2.carbon.governance.taxonomy.util.TaxonomyCategoryParser.java

/***
 * This method is use to go through xml DOM and push the elements names into a stack
 *
 * @param childNodes//from  www .j  a v a 2s .  c om
 */
private static void loopNodes(NodeList childNodes) throws JSONException {
    for (int i = 0; i < childNodes.getLength(); ++i) {
        HashMap<String, String> tempHashMap = new HashMap<>();
        Node node = childNodes.item(i);
        String nodeName = node.getNodeName();
        if (!"#text".equals(nodeName)) {

            Attr attr = (Attr) node.getAttributes().getNamedItem("displayname");
            String attribute = null;
            if (attr != null) {
                attribute = attr.getValue();
            }

            if (attribute != null) {
                tempHashMap.put(node.getNodeName(), attribute);
                elementStack.push(tempHashMap);
            } else {
                tempHashMap.put(node.getNodeName(), null);
                elementStack.push(tempHashMap);
            }

            if (node.hasChildNodes()) {
                loopNodes(node.getChildNodes());
            } else {
                addPathToCategories();
            }

            if (elementStack.size() > 0) {
                elementStack.pop();
            }

        }
    }

}

From source file:org.wso2.carbon.humantask.core.engine.runtime.xpath.JaxpFunctionResolver.java

public void parseOrgEntityTypeOrUser(Node node1, Set<String> resoledUsers) {
    if (node1.getNodeType() == Node.ELEMENT_NODE) {
        if (organizationalEntityQname.getNamespaceURI().equals(node1.getNamespaceURI())
                && organizationalEntityQname.getLocalPart().equals(node1.getLocalName())) {
            //Parsing organizationalEntity element
            parseOrgEntity(node1, resoledUsers);
        } else if (userQname.getNamespaceURI().equals(node1.getNamespaceURI())
                && userQname.getLocalPart().equals(node1.getLocalName())) {
            //Parsing user element
            String username = node1.getTextContent();
            if (username != null) {
                username = username.trim();
                if (username.length() > 0) {
                    resoledUsers.add(username);
                }/*from w w  w.  j  a va  2  s. c o m*/
            }
        } else if (node1.hasChildNodes()) {
            NodeList nodeList = node1.getChildNodes();
            Node childNode = null;
            for (int j = 0; j < nodeList.getLength(); j++) {
                if (Node.ELEMENT_NODE == nodeList.item(j).getNodeType()) {
                    childNode = nodeList.item(j);
                    break;
                }
            }
            //Parsing tOrganizationalEntity type also to have consistence the expression logic.
            if (childNode != null) {
                if (childNode.getNodeType() == Node.ELEMENT_NODE
                        && organizationalEntityQname.getNamespaceURI().equals(childNode.getNamespaceURI())) {
                    if (userQname.getLocalPart().equals(childNode.getLocalName())
                            || groupQname.getLocalPart().equals(childNode.getLocalName())) {
                        parseOrgEntity(node1, resoledUsers);
                    }
                }
            } else { // No element found. this is text content.
                String username = node1.getTextContent();
                if (username != null) {
                    username = username.trim();
                    if (username.length() > 0) {
                        resoledUsers.add(username);
                    }
                }
            }
        } else {
            throw new HumanTaskRuntimeException(
                    "This function should be provided with htt:organizationalEntity or htt:user element as an argument.");
        }
    }
}

From source file:org.wso2.carbon.jaggeryapp.template.deployer.JaggeryappTemplateDeployer.java

@Override
public void deployArtifact(DeployableTemplate template) throws TemplateDeploymentException {
    String artifactId = template.getArtifactId();
    String content = template.getArtifact();

    Map<String, String> artifacts = new HashMap<>();
    Map<String, String> properties = new HashMap<>();

    DocumentBuilderFactory factory = JaggeryappTemplateDeployerHelper.getSecuredDocumentBuilder();
    try {/*w  w  w  .  j  a  v a  2  s .  co  m*/
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(content)));
        NodeList configNodes = document.getElementsByTagName(JaggeryappTemplateDeployerConstants.CONFIG_TAG);
        if (configNodes.getLength() > 0) {
            Node configNode = configNodes.item(0); // Only one node is expected
            if (configNode.hasChildNodes()) {

                // Extract the details
                NodeList nodeList = configNode.getChildNodes();
                for (int i = 0; i < nodeList.getLength(); i++) {
                    Node node = nodeList.item(i);
                    if (JaggeryappTemplateDeployerConstants.PROPERTIES_TAG.equalsIgnoreCase(node.getNodeName())
                            && node.hasChildNodes()) {
                        // Properties
                        NodeList propertiesNodeList = node.getChildNodes();
                        for (int j = 0; j < propertiesNodeList.getLength(); j++) {
                            Node propertyNode = propertiesNodeList.item(j);
                            if (JaggeryappTemplateDeployerConstants.PROPERTY_TAG
                                    .equalsIgnoreCase(propertyNode.getNodeName())) {
                                Attr attr = (Attr) propertyNode.getAttributes()
                                        .getNamedItem(JaggeryappTemplateDeployerConstants.NAME_ATTRIBUTE);
                                properties.put(attr.getValue(),
                                        propertyNode.getFirstChild().getNodeValue().trim());
                            }
                        }
                    } else if (JaggeryappTemplateDeployerConstants.ARTIFACTS_TAG
                            .equalsIgnoreCase(node.getNodeName()) && node.hasChildNodes()) {
                        NodeList artifactNodeList = node.getChildNodes();
                        for (int j = 0; j < artifactNodeList.getLength(); j++) {
                            Node artifactNode = artifactNodeList.item(j);
                            if (JaggeryappTemplateDeployerConstants.ARTIFACT_TAG
                                    .equalsIgnoreCase(artifactNode.getNodeName())) {
                                Attr attr = (Attr) artifactNode.getAttributes()
                                        .getNamedItem(JaggeryappTemplateDeployerConstants.FILE_ATTRIBUTE);
                                artifacts.put(attr.getValue(), artifactNode.getFirstChild().getNodeValue());
                            }
                        }
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        throw new JaggeryappTemplateDeployerException("Error in creating XML document builder. ", e);
    } catch (SAXException e) {
        throw new JaggeryappTemplateDeployerException("Error in parsing XML content of: " + artifactId, e);
    } catch (IOException e) {
        throw new JaggeryappTemplateDeployerException("Error in loading XML content of: " + artifactId, e);
    }

    if (!properties.containsKey(JaggeryappTemplateDeployerConstants.DIRECTORY_NAME)) {
        throw new JaggeryappTemplateDeployerException("Artifact does not contain "
                + JaggeryappTemplateDeployerConstants.DIRECTORY_NAME + " property.");
    }
    String jaggeryArtifactPath = JaggeryappTemplateDeployerUtility.getJaggeryappArtifactPath();
    File destination = new File(
            jaggeryArtifactPath + properties.get(JaggeryappTemplateDeployerConstants.DIRECTORY_NAME));
    JaggeryappTemplateDeployerHelper
            .validateFilePath(properties.get(JaggeryappTemplateDeployerConstants.DIRECTORY_NAME));

    String templateParentDirectory = new StringBuilder(CarbonUtils.getCarbonConfigDirPath())
            .append(File.separator).append(JaggeryappTemplateDeployerConstants.TEMPLATE_MANAGER)
            .append(File.separator).append(JaggeryappTemplateDeployerConstants.JAGGERYAPP_TEMPLATES)
            .append(File.separator).toString();
    File templateDirectory = new File(
            templateParentDirectory + properties.get(JaggeryappTemplateDeployerConstants.TEMPLATE_DIRECTORY));
    JaggeryappTemplateDeployerHelper
            .validateFilePath(properties.get(JaggeryappTemplateDeployerConstants.TEMPLATE_DIRECTORY));

    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        Registry registry = JaggeryappTemplateDeployerValueHolder.getRegistryService()
                .getConfigSystemRegistry(tenantId);
        Resource resource;
        if (registry.resourceExists(JaggeryappTemplateDeployerConstants.META_INFO_COLLECTION_PATH)) {
            resource = registry.get(JaggeryappTemplateDeployerConstants.META_INFO_COLLECTION_PATH);
            // If same artifact id exists it is an edit
            if (resource.getProperty(artifactId) != null) {
                undeployArtifact(artifactId);
            }
            // Throw exception if same jaggeryapp exists
            if (destination.exists()) {
                throw new JaggeryappTemplateDeployerException("Jaggeryapp with same name "
                        + properties.get(JaggeryappTemplateDeployerConstants.DIRECTORY_NAME)
                        + " already exists");
            }
        } else {
            resource = registry.newResource();
        }
        resource.setProperty(artifactId, properties.get(JaggeryappTemplateDeployerConstants.DIRECTORY_NAME));
        // Save the resource
        registry.put(JaggeryappTemplateDeployerConstants.META_INFO_COLLECTION_PATH, resource);
    } catch (RegistryException e) {
        throw new JaggeryappTemplateDeployerException("Failed to access resource at: "
                + JaggeryappTemplateDeployerConstants.META_INFO_COLLECTION_PATH + " from registry", e);
    }

    boolean failedToDeploy = false;
    try {
        // Copy all the default templates
        FileUtils.copyDirectory(templateDirectory, destination);
        // Save the artifacts
        for (Map.Entry<String, String> entry : artifacts.entrySet()) {
            String fileName = entry.getKey();
            File targetFile = new File(destination, fileName);
            FileWriter writer = null;
            try {
                writer = new FileWriter(targetFile);
                writer.write(entry.getValue());
            } catch (IOException e) {
                failedToDeploy = true;
                log.error("Failed to write artifact to: " + targetFile.getAbsolutePath());
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        log.warn("Failed to close FileWriter of " + targetFile.getAbsolutePath());
                    }
                }
            }
        }
    } catch (IOException e) {
        failedToDeploy = true;
        log.error("Failed to copy " + templateDirectory.getAbsolutePath() + " to "
                + destination.getAbsolutePath());
    }
    if (failedToDeploy) {
        undeployArtifact(artifactId);
        throw new JaggeryappTemplateDeployerException("Failed to deploy jaggerapp " + artifactId);
    } else {
        log.info("Deployed successfully jaggeryapp: " + artifactId);
    }
}