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.company.processmaker.TreeFilesTopComponent.java

public TreeFilesTopComponent() {
    initComponents();/*from   w w w.  ja  va  2 s.  c  om*/

    setName(Bundle.CTL_TreeFilesTopComponent());
    setToolTipText(Bundle.HINT_TreeFilesTopComponent());
    // new codes
    instance = this;

    MouseListener ml = new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            int selRow = jTree1.getRowForLocation(e.getX(), e.getY());
            TreePath selPath = jTree1.getPathForLocation(e.getX(), e.getY());

            if (selRow != -1) {
                if (e.getClickCount() == 1) {
                    //mySingleClick(selRow, selPath);
                } else if (e.getClickCount() == 2) {

                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1
                            .getLastSelectedPathComponent();
                    if (node == null) {
                        return;
                    }
                    Object nodeInfo = node.getUserObject();
                    int node_level = node.getLevel();

                    if (node_level < 2) {
                        return;
                    }

                    // for each dyna form
                    if (node_level == 2) {

                        Global gl_obj = Global.getInstance();

                        //myDoubleClick(selRow, selPath);
                        conf = Config.getInstance();

                        DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
                        String parentName = (String) parent.getUserObject();

                        // handle triggers
                        if (parentName.equals("Triggers")) {

                            String filePath = "";
                            for (String[] s : res_trigger) {

                                if (s[0].equals(nodeInfo.toString())) {
                                    // get path of dyna in xml forms
                                    filePath = conf.tmp + "triggers/" + s[3] + "/" + s[2] + ".php";
                                    break;
                                }

                            }

                            File toAdd = new File(filePath);

                            try {
                                DataObject dObject = DataObject.find(FileUtil.toFileObject(toAdd));

                                dObject.getLookup().lookup(OpenCookie.class).open();
                                // dont listen for exist listen files
                                if (existFile(filePath)) {
                                    return;
                                }
                                dObject.addPropertyChangeListener(new PropertyChangeListener() {
                                    @Override
                                    public void propertyChange(PropertyChangeEvent evt) {
                                        if (DataObject.PROP_MODIFIED.equals(evt.getPropertyName())) {
                                            //fire a dummy event
                                            if (!Boolean.TRUE.equals(evt.getNewValue())) {

                                                /*String msg = "Saved to" + evt.toString();
                                                NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE);
                                                DialogDisplayer.getDefault().notify(nd);*/
                                                TopComponent activeTC = TopComponent.getRegistry()
                                                        .getActivated();
                                                DataObject dataLookup = activeTC.getLookup()
                                                        .lookup(DataObject.class);
                                                String filePath = FileUtil.toFile(dataLookup.getPrimaryFile())
                                                        .getAbsolutePath();

                                                File userFile = new File(filePath);
                                                String fileName = userFile.getName();
                                                fileName = fileName.substring(0, fileName.lastIndexOf("."));

                                                try {
                                                    String content = new String(
                                                            Files.readAllBytes(Paths.get(filePath)));
                                                    // remote php tag and info "<?php //don't remove this tag! \n"
                                                    content = content.substring(6, content.length());

                                                    String query = "update triggers set TRI_WEBBOT = '"
                                                            + StringEscapeUtils.escapeSql(content)
                                                            + "' where TRI_UID = '" + fileName + "'";
                                                    GooglePanel.updateQuery(query);

                                                } catch (Exception e) {
                                                    //Exceptions.printStackTrace(e);
                                                    String msg = "Can not update trigger";
                                                    NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                                            NotifyDescriptor.INFORMATION_MESSAGE);
                                                    DialogDisplayer.getDefault().notify(nd);
                                                }

                                            }

                                        }

                                    }
                                });

                            } catch (DataObjectNotFoundException ex) {
                                //Exceptions.printStackTrace(ex);
                                String msg = "Trigger not found";
                                NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                        NotifyDescriptor.INFORMATION_MESSAGE);
                                DialogDisplayer.getDefault().notify(nd);
                            }

                            return;
                        }

                        List<String[]> res_dyna = gl_obj.getDyna();
                        String FileDir = "";
                        for (String[] s : res_dyna) {

                            if (s[1].equals(nodeInfo.toString())) {
                                // get path of dyna in xml forms
                                FileDir = s[3];
                                break;
                            }

                        }

                        //String msg = "selRow" + nodeInfo.toString() + "|" + conf.getXmlForms() + FileDir;
                        String filePath = conf.getXmlForms() + FileDir + ".xml";
                        if (conf.isRemote()) {
                            String[] res = FileDir.split("/");
                            filePath = conf.get("local_tmp_for_remote") + "/" + FileDir + "/" + res[1] + ".xml";
                        }

                        File toAdd = new File(filePath);

                        //Result will be null if the user clicked cancel or closed the dialog w/o OK
                        if (toAdd != null) {
                            try {
                                DataObject dObject = DataObject.find(FileUtil.toFileObject(toAdd));

                                dObject.getLookup().lookup(OpenCookie.class).open();
                                // dont listen for exist listen files
                                if (existFile(filePath)) {
                                    return;
                                }
                                dObject.addPropertyChangeListener(new PropertyChangeListener() {
                                    @Override
                                    public void propertyChange(PropertyChangeEvent evt) {
                                        if (DataObject.PROP_MODIFIED.equals(evt.getPropertyName())) {
                                            //fire a dummy event
                                            if (!Boolean.TRUE.equals(evt.getNewValue())) {

                                                /*String msg = "Saved to" + evt.toString();
                                                NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE);
                                                DialogDisplayer.getDefault().notify(nd);*/
                                                TopComponent activeTC = TopComponent.getRegistry()
                                                        .getActivated();
                                                DataObject dataLookup = activeTC.getLookup()
                                                        .lookup(DataObject.class);
                                                String filePath = FileUtil.toFile(dataLookup.getPrimaryFile())
                                                        .getAbsolutePath();

                                                File userFile = new File(filePath);
                                                String fileName = userFile.getName();
                                                fileName = fileName.substring(0, fileName.lastIndexOf("."));

                                                Global gl_obj = Global.getInstance();

                                                List<String[]> res_dyna = gl_obj.getDyna();
                                                String FileDir = "";
                                                for (String[] s : res_dyna) {

                                                    if (filePath.contains(s[0])) {

                                                        FileDir = s[3];
                                                        break;

                                                    }

                                                }

                                                if (conf.isRemote()) {
                                                    boolean res_Upload = SSH.getInstance().uplaodFile(FileDir);
                                                    if (res_Upload) {
                                                        String msg = "file upload Successfully!";
                                                        NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                                                NotifyDescriptor.INFORMATION_MESSAGE);
                                                        DialogDisplayer.getDefault().notify(nd);
                                                    } else {
                                                        String msg = "error in uploading file!";
                                                        NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                                                NotifyDescriptor.INFORMATION_MESSAGE);
                                                        DialogDisplayer.getDefault().notify(nd);
                                                    }
                                                }

                                            }

                                        }

                                    }
                                });

                            } catch (DataObjectNotFoundException ex) {
                                //Exceptions.printStackTrace(ex);
                                String msg = "Can not find xml file";
                                NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                        NotifyDescriptor.INFORMATION_MESSAGE);
                                DialogDisplayer.getDefault().notify(nd);
                            }
                        }
                    }

                    // for each js file
                    if (node_level == 3) {

                        TreeNode parentInfo = node.getParent();

                        Global gl_obj = Global.getInstance();

                        List<String[]> res_dyna = gl_obj.getDyna();
                        String FileDir = "";
                        for (String[] s : res_dyna) {

                            if (s[1].equals(parentInfo.toString())) {
                                // get path of dyna in xml forms
                                FileDir = s[3];
                                break;
                            }

                        }

                        //myDoubleClick(selRow, selPath);
                        conf = Config.getInstance();
                        String filePath = conf.tmp + "xmlForms/" + FileDir + "/" + nodeInfo.toString() + ".js";
                        if (conf.isRemote()) {
                            filePath = conf.get("local_tmp_for_remote") + FileDir + "/" + nodeInfo.toString()
                                    + ".js";
                        }

                        File toAdd = new File(filePath);

                        //Result will be null if the user clicked cancel or closed the dialog w/o OK
                        if (toAdd != null) {
                            try {
                                DataObject dObject = DataObject.find(FileUtil.toFileObject(toAdd));

                                dObject.getLookup().lookup(OpenCookie.class).open();
                                // dont listen for exist listen files
                                if (existFile(filePath)) {
                                    return;
                                }
                                dObject.addPropertyChangeListener(new PropertyChangeListener() {
                                    @Override
                                    public void propertyChange(PropertyChangeEvent evt) {
                                        if (DataObject.PROP_MODIFIED.equals(evt.getPropertyName())) {
                                            //fire a dummy event
                                            if (!Boolean.TRUE.equals(evt.getNewValue())) {

                                                JTextComponent ed = EditorRegistry.lastFocusedComponent();
                                                String jsDoc = "";
                                                try {
                                                    jsDoc = ed.getText();
                                                } catch (Exception ex) {
                                                    //Exceptions.printStackTrace(ex);
                                                    String msg = "Can not get text from editor";
                                                    NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                                            NotifyDescriptor.INFORMATION_MESSAGE);
                                                    DialogDisplayer.getDefault().notify(nd);
                                                }

                                                TopComponent activeTC = TopComponent.getRegistry()
                                                        .getActivated();
                                                DataObject dataLookup = activeTC.getLookup()
                                                        .lookup(DataObject.class);
                                                String filePath = FileUtil.toFile(dataLookup.getPrimaryFile())
                                                        .getAbsolutePath();

                                                File userFile = new File(filePath);
                                                String fileName = userFile.getName();
                                                fileName = fileName.substring(0, fileName.lastIndexOf("."));

                                                Global gl_obj = Global.getInstance();

                                                List<String[]> res_dyna = gl_obj.getDyna();
                                                String FileDir = "";
                                                for (String[] s : res_dyna) {

                                                    if (filePath.contains(s[0])) {

                                                        FileDir = s[3];
                                                        break;

                                                    }

                                                }

                                                String fullPath = conf.getXmlForms() + FileDir + ".xml";
                                                if (conf.isRemote()) {
                                                    String[] res = FileDir.split("/");
                                                    fullPath = conf.get("local_tmp_for_remote") + FileDir + "/"
                                                            + res[1] + ".xml";
                                                }
                                                try {
                                                    DocumentBuilderFactory factory = DocumentBuilderFactory
                                                            .newInstance();
                                                    DocumentBuilder builder = factory.newDocumentBuilder();
                                                    Document mainDoc = builder.parse(fullPath);

                                                    XPath xPath = XPathFactory.newInstance().newXPath();
                                                    Node startDateNode = (Node) xPath
                                                            .compile("//dynaForm/" + fileName)
                                                            .evaluate(mainDoc, XPathConstants.NODE);
                                                    Node cdata = mainDoc.createCDATASection(jsDoc);
                                                    startDateNode.setTextContent("");
                                                    startDateNode.appendChild(cdata);

                                                    /*String msg = evt.getPropertyName() + "-" + fileName;
                                                    NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE);
                                                    DialogDisplayer.getDefault().notify(nd);*/
                                                    // write the content into xml file
                                                    TransformerFactory transformerFactory = TransformerFactory
                                                            .newInstance();
                                                    Transformer transformer = transformerFactory
                                                            .newTransformer();
                                                    DOMSource source = new DOMSource(mainDoc);
                                                    StreamResult result = new StreamResult(new File(fullPath));
                                                    transformer.transform(source, result);

                                                    if (conf.isRemote()) {
                                                        boolean res_Upload = SSH.getInstance()
                                                                .uplaodFile(FileDir);
                                                        if (res_Upload) {
                                                            String msg = "file upload Successfully!";
                                                            NotifyDescriptor nd = new NotifyDescriptor.Message(
                                                                    msg, NotifyDescriptor.INFORMATION_MESSAGE);
                                                            DialogDisplayer.getDefault().notify(nd);
                                                        } else {
                                                            String msg = "error in uploading file!";
                                                            NotifyDescriptor nd = new NotifyDescriptor.Message(
                                                                    msg, NotifyDescriptor.INFORMATION_MESSAGE);
                                                            DialogDisplayer.getDefault().notify(nd);
                                                        }
                                                    }

                                                } catch (Exception ex) {
                                                    //Exceptions.printStackTrace(ex);
                                                    String msg = "Can not save to xml form";
                                                    NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                                            NotifyDescriptor.INFORMATION_MESSAGE);
                                                    DialogDisplayer.getDefault().notify(nd);
                                                }

                                            }

                                        }

                                    }
                                });

                            } catch (DataObjectNotFoundException ex) {
                                //Exceptions.printStackTrace(ex);
                                String msg = "Can not save to xml form";
                                NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                        NotifyDescriptor.INFORMATION_MESSAGE);
                                DialogDisplayer.getDefault().notify(nd);
                            }
                        }
                    }
                }
            }
        }
    };
    jTree1.addMouseListener(ml);
    jTree1.setModel(null);
}

From source file:org.corpus_tools.pepper.cli.PepperStarter.java

/**
 * This method writes a module configuration of GroupId, ArtifactId and
 * Maven repository back to the modules.xml file
 *//*ww  w  . j  a v a2s  . co  m*/
private boolean write2ConfigFile(String groupId, String artifactId, String repository) {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    try {
        boolean changes = false;
        File configFile = new File(MODULES_XML_PATH);
        DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(configFile);
        NodeList configuredModules = doc.getElementsByTagName(ModuleTableReader.TAG_ARTIFACTID);
        if (configuredModules.getLength() == 0) {
            return false;
        }
        /* check, if the module is already in the modules.xml file */
        Node item = configuredModules.item(0);
        int j = 0;
        while (j + 1 < configuredModules.getLength() && !artifactId.equals(item.getTextContent())) {
            item = configuredModules.item(++j);
        }
        if (artifactId.equals(item.getTextContent())) {// already contained
            // -> edit
            Node itemGroupId = null;
            Node itemRepo = null;
            Node node = null;
            for (int i = 0; i < item.getParentNode().getChildNodes().getLength()
                    && (itemGroupId == null || itemRepo == null); i++) {
                node = item.getParentNode().getChildNodes().item(i);
                if (ModuleTableReader.TAG_GROUPID.equals(node.getLocalName())) {
                    itemGroupId = node;
                }
                if (ModuleTableReader.TAG_REPO.equals(node.getLocalName())) {
                    itemRepo = node;
                }
            }
            if (itemGroupId != null) {
                itemGroupId.setTextContent(groupId);
                changes = true;
            } else {
                if (!groupId.equals(doc.getElementsByTagName(ModuleTableReader.ATT_DEFAULTGROUPID).item(0)
                        .getTextContent())) {
                    itemGroupId = doc.createElement(ModuleTableReader.TAG_GROUPID);
                    itemGroupId.setTextContent(groupId);
                    item.getParentNode().appendChild(itemGroupId);
                    changes = true;
                }
            }
            if (itemRepo != null) {
                itemRepo.setTextContent(repository);
                changes = true;
            } else {
                // if
                // (!repository.equals(doc.getElementsByTagName(ModuleTableReader.ATT_DEFAULTREPO).item(0).getTextContent()))
                // {
                // itemRepo = doc.createElement(ModuleTableReader.TAG_REPO);
                // itemRepo.setTextContent(repository);
                // item.getParentNode().appendChild(itemRepo);
                // changes = true;
                // }
            }
            itemGroupId = null;
            itemRepo = null;
            node = null;
        } else {// not contained yet -> insert
            changes = true;
            Node listNode = doc.getElementsByTagName(ModuleTableReader.TAG_LIST).item(0);
            Node newModule = doc.createElement(ModuleTableReader.TAG_ITEM);
            Node groupIdNode = doc.createElement(ModuleTableReader.TAG_GROUPID);
            groupIdNode.appendChild(doc.createTextNode(groupId));
            Node artifactIdNode = doc.createElement(ModuleTableReader.TAG_ARTIFACTID);
            artifactIdNode.appendChild(doc.createTextNode(artifactId));
            Node repositoryNode = doc.createElement(ModuleTableReader.TAG_REPO);
            repositoryNode.appendChild(doc.createTextNode(repository));
            newModule.appendChild(groupIdNode);
            newModule.appendChild(artifactIdNode);
            newModule.appendChild(repositoryNode);
            listNode.appendChild(newModule);

            listNode = null;
            newModule = null;
            groupIdNode = null;
            artifactIdNode = null;
            repository = null;
        }

        if (changes) {
            // write back to file
            TransformerFactory trFactory = TransformerFactory.newInstance();
            // trFactory.setAttribute("indent-number", 2);
            Transformer transformer = trFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            DOMSource src = new DOMSource(doc);
            StreamResult result = new StreamResult(configFile);
            transformer.transform(src, result);

            trFactory = null;
            transformer = null;
            src = null;
            result = null;
        }

        docBuilder = null;
        doc = null;
        configuredModules = null;
        item = null;

    } catch (ParserConfigurationException | SAXException | IOException | FactoryConfigurationError
            | TransformerFactoryConfigurationError | TransformerException e) {
        logger.error("Could not read module table.");
        logger.trace(" ", e);
        return false;
    }
    return true;
}

From source file:org.easyrec.service.core.impl.ProfileServiceImpl.java

/**
 * Inserts a new element and value into an XML Document at the position given in xPathExpression
 * relative to the Node given in startNode.
 *
 * @param doc             the Document in which the Element is inserted
 * @param startNode       the Node in the Document used as start point for the XPath Expression
 * @param xPathExpression the XPath from the startNode to the new Element
 * @param value           the value of the new Element
 *//*  w  ww. j  a v a 2  s. c  om*/
private Node insertElement(Document doc, Node startNode, String xPathExpression, String value) {

    if (!"".equals(xPathExpression)) {
        String[] xPathTokens = xPathExpression.split("/");
        for (String tag : xPathTokens) {
            if (!"".equals(tag)) {
                Element el = doc.createElement(tag);
                startNode.appendChild(el);
                startNode = startNode.getLastChild();
            }
        }
        if (value != null)
            startNode.setTextContent(value);
    }
    return startNode;
}

From source file:org.easyrec.service.domain.profile.impl.ProfileServiceImpl.java

public void insertOrUpdateSimpleDimension(Integer tenantId, Integer itemId, String itemTypeId,
        String dimensionXPath, String value) {

    XPathFactory xpf = XPathFactory.newInstance();
    try {//  w  w  w .  j  a  v a  2  s .com
        // load and parse the profile
        DocumentBuilder db = validationParsers.get(tenantId).get(itemTypeId);
        Document doc = db.parse(new InputSource(new StringReader(getProfile(tenantId, itemId, itemTypeId))));
        // check if the element exists
        XPath xp = xpf.newXPath();
        Node node = (Node) xp.evaluate(dimensionXPath, doc, XPathConstants.NODE);
        // if the element exists, just update the value
        if (node != null) {
            // if value doesn't change, there is no need to alter the profile and write it to database
            if (value.equals(node.getTextContent()))
                return;
            node.setTextContent(value);
        } else { // if the element cannot be found, insert it at the position given in the dimensionXPath
            // follow the XPath from bottom to top until you find the first existing path element
            String tmpPath = dimensionXPath;
            while (node == null) {
                tmpPath = dimensionXPath.substring(0, tmpPath.lastIndexOf("/"));
                node = (Node) xp.evaluate(tmpPath, doc, XPathConstants.NODE);
            }
            // found the correct node to insert or ended at Document root, hence insert
            insertElement(doc, node, dimensionXPath.substring(tmpPath.length()/*, dimensionXPath.length()*/),
                    value);
        }

        StringWriter writer = new StringWriter();
        Result result = new StreamResult(writer);
        trans.transform(new DOMSource(doc), result);
        writer.close();
        String xml = writer.toString();
        logger.debug(xml);
        storeProfile(tenantId, itemId, itemTypeId, xml, true);

    } catch (Exception e) {
        logger.error("Error inserting Simple Dimension: " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:org.eclipse.lyo.testsuite.oslcv2.asset.GetAndUpdateXmlTests.java

@Test
public void updateAnAssetProperty() throws IOException, ParseException, ParserConfigurationException,
        SAXException, TransformerException, XPathExpressionException {
    // Get the asset
    String resp = getAssetAsString();
    Document document = OSLCUtils.createXMLDocFromResponseBody(resp);

    // Updates the title
    String name = "updated asset";
    NodeList nodes = getAssetNodeChildren(document);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeName().equals("dcterms:title")) {
            node.setTextContent(name);
        }// w w w .  j  a  v a 2  s. c  o m
    }
    String content = OSLCUtils.createStringFromXMLDoc(document);
    // Update the asset
    putAsset(content);

    // Get the asset again to verify it the asset was updated
    resp = getAssetAsString();
    document = OSLCUtils.createXMLDocFromResponseBody(resp);

    NodeList children = getAssetNodeChildren(document);
    String actualName = getNodeText(children, "dcterms:title");
    assertTrue("Expected " + name + ", received " + actualName, name.equals(actualName));
}

From source file:org.eclipse.lyo.testsuite.oslcv2.asset.UsageCaseXmlTests.java

@Test
public void publishUsageCase() throws IOException, ParseException, ParserConfigurationException, SAXException,
        TransformerException, XPathException {
    // Get url//from   www  .  j a va  2s .  c  o m
    ArrayList<String> serviceUrls = getServiceProviderURLsUsingXML(setupProps.getProperty("baseUri"));
    ArrayList<String> capabilityURLsUsingRdfXml = TestsBase.getCapabilityURLsUsingRdfXml(
            OSLCConstants.CREATION_PROP, serviceUrls, useDefaultUsageForCreation, null);
    currentUrl = capabilityURLsUsingRdfXml.get(0);

    // Create the asset      
    assetUrl = createAsset(xmlCreateTemplate);
    assertTrue("The location of the asset after it was create was not returned", assetUrl != null);

    // Add the artifact to the asset
    String artifactFactory = getArtifactFactory();

    Header[] header = addHeader(new BasicHeader("oslc_asset.name", "/helpFolder/help"));

    //String fileName = setupProps.getProperty("createTemplateArtifactXmlFile");
    String fileName = setupProps.getProperty("createTemplateXmlFile");
    assertTrue("There needs to be an artifact template file", fileName != null);
    String artifact = OSLCUtils.readFileByNameAsString(fileName);

    HttpResponse response = OSLCUtils.postDataToUrl(artifactFactory, creds, OSLCConstants.CT_XML,
            OSLCConstants.CT_XML, artifact, header);
    EntityUtils.consume(response.getEntity());
    assertTrue("Expected " + HttpStatus.SC_OK + ", received " + response.getStatusLine().getStatusCode(),
            response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED);

    // Get updated asset and update the artifact
    HttpResponse resp = getAssetResponse();
    String content = EntityUtils.toString(resp.getEntity());
    Document document = OSLCUtils.createXMLDocFromResponseBody(content);
    EntityUtils.consume(resp.getEntity());
    String path = "/rdf:RDF/oslc_asset:Asset/oslc_asset:artifact[1]/oslc_asset:Artifact";
    XPath xpath = OSLCUtils.getXPath();
    Node artifactNode = (Node) xpath.evaluate(path, document, XPathConstants.NODE);

    NodeList artifactKids = artifactNode.getChildNodes();
    Node label = null;
    for (int i = 0; i < artifactKids.getLength(); i++) {
        if (artifactKids.item(i).getNodeName().equals("oslc:label")) {
            label = artifactKids.item(i);
            break;
        }
    }

    String labelValue = "this value was changed";
    if (label == null) {
        label = document.createElement("oslc:label");
        label.setTextContent(labelValue);
        artifactNode.appendChild(label);
    } else {
        label.setTextContent(labelValue);
    }

    // Update asset
    content = OSLCUtils.createStringFromXMLDoc(document);
    putAsset(content);

    // Check to see if the label was updated
    resp = getAssetResponse();
    content = EntityUtils.toString(resp.getEntity());
    document = OSLCUtils.createXMLDocFromResponseBody(content);
    EntityUtils.consume(resp.getEntity());
    path = "/rdf:RDF/oslc_asset:Asset/oslc_asset:artifact[1]/oslc_asset:Artifact/oslc:label";
    xpath = OSLCUtils.getXPath();
    label = (Node) xpath.evaluate(path, document, XPathConstants.NODE);
    assertTrue("Could not find the artifact's label node", label != null);
    assertEquals("The label was not updated properly", labelValue, label.getTextContent());
}

From source file:org.eclipse.thym.android.core.adt.AndroidProjectGenerator.java

private void updateAppName(String appName) throws CoreException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*ww w  .  ja  v  a2s. c  o m*/
    DocumentBuilder db;

    try {
        db = dbf.newDocumentBuilder();
        IPath stringsPath = new Path(getDestination().toString()).append(DIR_RES).append(DIR_VALUES)
                .append(FILE_XML_STRINGS);
        File strings = stringsPath.toFile();
        Document configDocument = db.parse(strings);
        XPath xpath = XPathFactory.newInstance().newXPath();

        try {
            XPathExpression expr = xpath.compile("//string[@name=\"app_name\"]");
            Node node = (Node) expr.evaluate(configDocument, XPathConstants.NODE);
            node.setTextContent(appName);
            configDocument.setXmlStandalone(true);
            Source source = new DOMSource(configDocument);
            StreamResult result = new StreamResult(strings);
            // Write the DOM document to the file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer xformer = transformerFactory.newTransformer();
            xformer.transform(source, result);

        } catch (XPathExpressionException e) {//We continue because this affects the displayed app name
                                              // which is not a show stopper during development
            AndroidCore.log(IStatus.ERROR, "Error when updating the application name", e);
        } catch (TransformerConfigurationException e) {
            AndroidCore.log(IStatus.ERROR, "Error when updating the application name", e);
        } catch (TransformerException e) {
            AndroidCore.log(IStatus.ERROR, "Error when updating the application name", e);
        }

    } catch (ParserConfigurationException e) {
        throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID,
                "Parser error when parsing /res/values/strings.xml", e));
    } catch (SAXException e) {
        throw new CoreException(
                new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "Parsing error on /res/values/strings.xml", e));
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID,
                "IO error when parsing /res/values/strings.xml", e));
    }
}

From source file:org.eclipse.thym.blackberry.core.bdt.BlackBerryProjectGenerator.java

private void updateAppName(String appName) throws CoreException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//w w w  .  j ava 2 s  .  com
    DocumentBuilder db;

    try {
        db = dbf.newDocumentBuilder();
        IPath stringsPath = new Path(getDestination().toString()).append(DIR_RES).append(DIR_VALUES)
                .append(FILE_XML_STRINGS);
        File strings = stringsPath.toFile();
        Document configDocument = db.parse(strings);
        XPath xpath = XPathFactory.newInstance().newXPath();

        try {
            XPathExpression expr = xpath.compile("//string[@name=\"app_name\"]");
            Node node = (Node) expr.evaluate(configDocument, XPathConstants.NODE);
            node.setTextContent(appName);

            configDocument.setXmlStandalone(true);

            Source source = new DOMSource(configDocument);

            StreamResult result = new StreamResult(strings);

            // Write the DOM document to the file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer xformer = transformerFactory.newTransformer();

            xformer.transform(source, result);

        } catch (XPathExpressionException e) {//We continue because this affects the displayed app name
                                              // which is not a show stopper during development
            BlackBerryCore.log(IStatus.ERROR, "Error when updating the application name", e);
        } catch (TransformerConfigurationException e) {
            BlackBerryCore.log(IStatus.ERROR, "Error when updating the application name", e);
        } catch (TransformerException e) {
            BlackBerryCore.log(IStatus.ERROR, "Error when updating the application name", e);
        }

    } catch (ParserConfigurationException e) {
        throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID,
                "Parser error when parsing /res/values/strings.xml", e));
    } catch (SAXException e) {
        throw new CoreException(
                new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "Parsing error on /res/values/strings.xml", e));
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID,
                "IO error when parsing /res/values/strings.xml", e));
    }
}

From source file:org.gvnix.web.screen.roo.addon.SeleniumServicesImpl.java

/**
 * Create a html section to open register pattern URL.
 * /* w  w w.ja  v  a2s. c  o  m*/
 * @param document Document where create section
 * @param linkTarget Base URL to the server
 * @param name Name of pattern
 * @return Html node with register pattern open URL
 */
protected Node openCommandRegister(Document document, String linkTarget, String name) {

    Node tr = document.createElement("tr");

    Node td1 = tr.appendChild(document.createElement("td"));
    td1.setTextContent("open");

    // Add pattern request attributes
    Node td2 = tr.appendChild(document.createElement("td"));

    td2.setTextContent(linkTarget + (linkTarget.contains("?") ? "&" : "?") + "gvnixform" + "&gvnixpattern="
            + name + "&index=1" + "&lang=" + Locale.getDefault());

    Node td3 = tr.appendChild(document.createElement("td"));
    td3.setTextContent(" ");

    return tr;
}

From source file:org.gvnix.web.screen.roo.addon.SeleniumServicesImpl.java

/**
 * Create a html section to open tabular pattern URL.
 * /*from  w  ww .j a v a  2s .co  m*/
 * @param document Document where create section
 * @param linkTarget Base URL to the server
 * @param name Name of pattern
 * @return Html node with tabular pattern open URL
 */
protected Node openCommandTabular(Document document, String linkTarget, String name) {

    Node tr = document.createElement("tr");

    Node td1 = tr.appendChild(document.createElement("td"));
    td1.setTextContent("open");

    // Add pattern request attributes
    Node td2 = tr.appendChild(document.createElement("td"));

    td2.setTextContent(linkTarget + (linkTarget.contains("?") ? "&" : "?") + "gvnixpattern=" + name + "&lang="
            + Locale.getDefault());

    Node td3 = tr.appendChild(document.createElement("td"));
    td3.setTextContent(" ");

    return tr;
}