Example usage for org.dom4j Node setText

List of usage examples for org.dom4j Node setText

Introduction

In this page you can find the example usage for org.dom4j Node setText.

Prototype

void setText(String text);

Source Link

Document

Sets the text data of this node or this method will throw an UnsupportedOperationException if it is read-only.

Usage

From source file:edu.ucsd.library.xdre.imports.RDFDAMS4ImportHandler.java

/**
 * Update the document for DAMS ARK ID//from ww w.j ava  2  s  . c om
 * @param doc
 * @param record
 * @param title
 * @throws Exception
 */
private void updateDocument(Document doc, Node record, String field, String title, Map<String, String> props)
        throws Exception {
    // Skip if the record detached
    if (record.getDocument() == null)
        return;

    // Subject, Authority records use mads:authoritativeLabel
    Node aboutAttr = record.selectSingleNode("@rdf:about");
    String srcUri = aboutAttr.getStringValue();
    //String nName = record.getName();
    String xPath = record.getPath();
    String elemName = xPath.substring(xPath.lastIndexOf("/") + 1);

    // MADSScheme model: MadsScheme
    if (elemName.endsWith("MADSScheme"))
        elemName = elemName.replace("MADSScheme", "Scheme");
    String modelName = (elemName.substring(0, 1).toUpperCase() + elemName.substring(1)).replace(":", "");
    String nKey = INFO_MODEL_PREFIX + modelName + "::" + title;
    if (props != null) {
        for (Iterator<String> it = props.keySet().iterator(); it.hasNext();) {
            String iKey = it.next();
            nKey += "_" + iKey + "::" + props.get(iKey);
        }
    }
    String oid = idsMap.get(nKey);
    // Retrieve the record
    if (oid == null) {
        /*Map<String, String> props = null;
        if(nName.endsWith(COPYRIGHT)){
           props = copyrightProperties(record);
        }*/
        oid = lookupRecord(damsClient, field, title, modelName, props);

        if (oid == null) {
            // Create the record
            oid = getNewId();
            aboutAttr.setText(oid);
            idsMap.put(nKey, oid);
            log.info("Found new redord " + srcUri + " (" + oid + ": " + field + " -- " + title);

        } else {
            // Record found. Add linking, remove it.
            toResourceLinking(oid, record);
        }
    } else {
        // Record added. Add linking, remove it.
        toResourceLinking(oid, record);
    }
    updateReference(doc, srcUri, oid);
}

From source file:edu.ucsd.library.xdre.imports.RDFDAMS4ImportHandler.java

public void updateReference(Document doc, String srcId, String oid) {
    List<Node> resNodes = doc.selectNodes("//@rdf:resource");
    for (int k = 0; k < resNodes.size(); k++) {
        Node nRes = resNodes.get(k);
        if (nRes.getStringValue().equals(srcId)) {
            nRes.setText(oid);
        }// ww w.  j  a  va2  s.  c  om
    }
}

From source file:edu.ucsd.library.xdre.imports.RDFDAMS4ImportTsHandler.java

/**
 * Procedure to populate the RDF metadata and ingest the files
 */// w  w w. j  a  va  2 s  . c  o  m
@Override
public boolean execute() throws Exception {
    if (filesPaths != null) {
        File file = null;
        // List the source files
        for (int i = 0; i < filesPaths.length; i++) {
            file = new File(filesPaths[i]);
            if (file.exists()) {
                listFile(filesMap, file);
            }
        }
    }

    String message = "";
    Document doc = null;
    DamsURI damsURI = null;

    List<String> recordsToReplace = null;
    String oid = null;
    int fLen = rdfFiles.length;
    String currFile = null;
    SAXReader saxReader = new SAXReader();
    for (int i = 0; i < fLen && !interrupted; i++) {
        if (i == 0)
            logMessage("Object Import status:\n[Object title]   -   [URI]   -   [Status]   -   [Timestamp]");

        recordsToReplace = new ArrayList<>();
        currFile = rdfFiles[i].getName();

        preprocessedTimestamp = damsDateFormat.format(rdfFiles[i].lastModified());

        setStatus(
                "Processing external import for file " + currFile + " (" + (i + 1) + " of " + fLen + ") ... ");
        try {
            doc = saxReader.read(rdfFiles[i]);
            List<Node> nodes = doc.selectNodes("//@rdf:about");
            for (int j = 0; j < nodes.size(); j++) {
                Node nUri = nodes.get(j);
                String iUri = nUri.getStringValue();
                Node parentNode = nUri.getParent();
                String nName = parentNode.getName();
                if (iUri.endsWith("/COL") || !(iUri.startsWith("http") && iUri.indexOf("/ark:/") > 0)) {
                    // Assign ARK
                    if (nName.endsWith("Object") || nName.endsWith("Component") || nName.endsWith("File")
                            || (((Element) parentNode).isRootElement()
                                    || (parentNode.getParent().isRootElement()
                                            && parentNode.getParent().getName().equals("RDF")))) {
                        String objId = iUri;

                        if (nName.endsWith("Component") || nName.endsWith("File")) {
                            damsURI = DamsURI.toParts(iUri, null);
                            objId = damsURI.getObject();
                        }
                        String srcObjKey = objId + "::" + rdfFiles[i].getAbsolutePath();
                        oid = idsMap.get(srcObjKey);

                        // Assign new ARK
                        if (oid == null) {
                            oid = getNewId();
                            idsMap.put(srcObjKey, oid);
                        }

                        if (nName.endsWith("Object")) {
                            objId = oid;
                            objRecords.put(objId, currFile);
                        } else if (nName.endsWith("Component") || nName.endsWith("File")) {
                            damsURI.setObject(oid);
                            // XXX
                            // Assign cid and fid for Component and FIle if required
                            objId = damsURI.toString();
                        } else
                            objId = oid;
                        nUri.setText(objId);
                        updateReference(doc, iUri, objId);
                    } else {
                        String field = null;
                        Node tNode = null;
                        String xPath = null;
                        Map<String, String> props = new TreeMap<String, String>();
                        String elemXPath = parentNode.getPath();
                        if (nName.endsWith("Collection") || nName.endsWith("CollectionPart")) {
                            // Retrieve the Collection record
                            field = "dams:title/mads:authoritativeLabel";
                            xPath = "dams:title/mads:Title/mads:authoritativeLabel";
                            tNode = parentNode.selectSingleNode(xPath);
                            if (tNode == null) {
                                // Loop through to locate the rdfs:label if not selected by xPath.
                                Node n = parentNode.selectSingleNode("dams:title");
                                for (Iterator<Element> it = ((Element) n).elementIterator(); it.hasNext();) {
                                    Element elem = it.next();
                                    if (elem.getNamespacePrefix().equals("mads")
                                            && elem.getName().equals("Title"))
                                        tNode = elem.selectSingleNode("mads:authoritativeLabel");
                                }
                            }
                        } /* else if (nName.endsWith("Language") || nName.endsWith("Authority") || nName.endsWith("Subject") || nName.endsWith("Name") || nName.endsWith("Topic") || nName.endsWith("GenreForm") || nName.endsWith("Temporal") || nName.endsWith("Geographic")){
                            // Subject, Authority records use mads:authoritativeLabel
                            field = "name_tesim";
                            xPath = "mads:authoritativeLabel";
                            tNode = parentNode.selectSingleNode(xPath);
                          } */else if (nName.endsWith(COPYRIGHT)) {
                            // Copyright records use dams:copyrightStatus, plus other properties in the next step.
                            field = "dams:copyrightStatus";
                            xPath = "dams:copyrightStatus";
                            tNode = parentNode.selectSingleNode(xPath);
                            props = copyrightProperties(parentNode);
                        } else if (nName.endsWith(LICENSE)) {
                            // License records use dams:LicenseNote, plus other properties in the next step.
                            field = "dams:licenseNote";
                            xPath = "dams:licenseNote";
                            tNode = parentNode.selectSingleNode(xPath);
                            props = licenseProperties(parentNode);
                        } else if (nName.endsWith(OTHERRIGHTS)) {
                            // Copyright records use dams:copyrightStatus, plus other properties in the next step.
                            field = "dams:otherRightsBasis";
                            xPath = "dams:otherRightsBasis";
                            tNode = parentNode.selectSingleNode(xPath);
                            props = otherRightsProperties(parentNode);
                        } else if (nName.endsWith(RELATEDRESOURCE)) {
                            // RelatedResource records use dams:description, plus other properties in the next step.
                            field = "dams:description";
                            xPath = "dams:description";
                            tNode = parentNode.selectSingleNode(xPath);
                            props = relatedResourceProperties(parentNode);
                        } else if (nName.endsWith(SOURCECAPTURE)) {
                            // SourceCapture records use dams:sourceType, plus other properties in the next step.
                            field = "dams:sourceType";
                            xPath = "dams:sourceType";
                            tNode = parentNode.selectSingleNode(xPath);
                            props = sourceCaptureProperties(parentNode);
                        } else if (nName.endsWith(NOTE)) {
                            // Note records use rdf:value, dams:type, dams:displayLabel.
                            field = "rdf:value";
                            xPath = "rdf:value";
                            tNode = parentNode.selectSingleNode(xPath);
                            props = noteProperties(parentNode);
                        } else if (nName.endsWith(PERMISSION) || nName.equals(RESTRICTION)) {
                            field = "dams:type";
                            xPath = "dams:type";
                            tNode = parentNode.selectSingleNode(xPath);
                            props = dateProperties(parentNode);
                        } else if (elemXPath.indexOf("mads", elemXPath.lastIndexOf('/') + 1) >= 0) {
                            // MADSScheme and Language
                            if (nName.endsWith(MADSSCHEME)) {
                                field = "mads:code";
                                xPath = "mads:code";
                                tNode = parentNode.selectSingleNode(xPath);
                                if (tNode == null) {
                                    field = "rdfs:label";
                                    xPath = "rdfs:label";
                                    tNode = parentNode.selectSingleNode("*[name()='" + xPath + "']");
                                }
                            } else if (nName.endsWith(LANGUAGE)) {
                                field = "mads:code";
                                xPath = "mads:code";
                                tNode = parentNode.selectSingleNode(xPath);
                                if (tNode == null) {
                                    field = "mads:authoritativeLabel";
                                    xPath = "mads:authoritativeLabel";
                                    tNode = parentNode.selectSingleNode(xPath);
                                }
                            } else {
                                // Subject, Authority records use mads:authoritativeLabel
                                field = "mads:authoritativeLabel";
                                xPath = "mads:authoritativeLabel";
                                tNode = parentNode.selectSingleNode(xPath);
                                if (tNode == null) {
                                    // Try to use the mads:code for mapping when mads:authoritativeLabel is not available
                                    field = "mads:code";
                                    xPath = "mads:code";
                                    tNode = parentNode.selectSingleNode(xPath);
                                } else {
                                    Node diplayLabelNode = parentNode
                                            .selectSingleNode("*[name()='dams:displayLabel']");
                                    props.put("dams:displayLabel", encodeLiteralValue(diplayLabelNode));
                                }
                                // Mapping for mads:isMemberOfMADSScheme
                                String madsScheme = null;
                                Node madsSchemeNode = parentNode.selectSingleNode("mads:isMemberOfMADSScheme");
                                if (madsSchemeNode != null) {
                                    Node msValueNode = madsSchemeNode.selectSingleNode("@rdf:resource");
                                    if (msValueNode != null) {
                                        madsScheme = madsSchemeNode.getStringValue();
                                        props.put("mads:isMemberOfMADSScheme", "<" + madsScheme + ">");
                                    } else if ((madsSchemeNode = madsSchemeNode
                                            .selectSingleNode("mads:MADSScheme")) != null
                                            && madsSchemeNode.hasContent()) {
                                        if ((msValueNode = madsSchemeNode
                                                .selectSingleNode("mads:code")) != null) {
                                            madsScheme = encodeLiteralValue(msValueNode);
                                            props.put("mads:isMemberOfMADSScheme/mads:code", madsScheme);
                                        } else if ((msValueNode = madsSchemeNode
                                                .selectSingleNode("rdfs:label")) != null) {
                                            madsScheme = encodeLiteralValue(msValueNode);
                                            props.put("mads:isMemberOfMADSScheme/rdfs:label", madsScheme);
                                        }
                                    } else {
                                        props.put("mads:isMemberOfMADSScheme/rdfs:label", "\"\"");
                                    }
                                } else {
                                    props.put("mads:isMemberOfMADSScheme/rdfs:label", null);
                                }
                            }

                        } else {
                            // XXX Other Rights records like Statute, License, Other Rights etc. 
                            field = "rdf:value";
                            xPath = "rdf:value";
                            tNode = parentNode.selectSingleNode(xPath);
                            field = "dams:code";
                            if (tNode == null) {
                                xPath = "dams:code";
                                tNode = parentNode.selectSingleNode(xPath);
                            }
                        }
                        if (tNode == null && !field.equals("dams:licenseNote")) {
                            throw new Exception("Element " + xPath + " is missing from the " + nName
                                    + " record " + iUri + " in file " + currFile + ".");
                        }

                        updateDocument(doc, parentNode, field, encodeLiteralValue(tNode), props);
                    }
                } else {
                    if (nName.endsWith("Object"))
                        objRecords.put(iUri, currFile);
                    if (replace && !(nName.endsWith("Component") || nName.endsWith("File")))
                        recordsToReplace.add(iUri);
                }
            }

            String dams4Rdf = doc.asXML();
            logData("dams4_" + rdfFiles[i].getName(), dams4Rdf);

            // Ingest the records
            String subjectId = null;
            DamsURI objURI = null;
            List<DamsURI> objURIs = null;
            RDFStore graph = null;

            rdfStore = new RDFStore();
            rdfStore.loadRDFXML(dams4Rdf);
            initHandler();

            Model iRdf = null;

            items = sortRecords(items);
            int jLen = items.size();
            //System.out.println(currFile + " records found: " + jLen);
            for (int j = 0; j < jLen && !interrupted; j++) {

                processIndex = 0;
                status = new boolean[processNames.length];
                messages = new StringBuilder[processNames.length];
                for (int k = 0; k < messages.length; k++) {
                    messages[k] = new StringBuilder();
                }

                Model objModel = null;
                graph = new RDFStore();
                recordsCount++;
                // Add subject
                subjectId = items.get(j);
                try {
                    setStatus("Processing metadata for record " + subjectId + " (" + (j + 1) + " of " + jLen
                            + ") in file " + currFile + " ... ");
                    boolean succeeded = false;
                    objURIs = objects.get(subjectId);

                    for (int k = 0; k < objURIs.size(); k++) {
                        objURI = objURIs.get(k);
                        iRdf = rdfStore.querySubject(objURI.toString());
                        objModel = graph.merge(iRdf);
                    }

                    // Update object
                    //log.info(j + " ingesting record " + subjectId + ":\n" + graph.export(RDFStore.RDFXML_ABBREV_FORMAT) + "\n\n");
                    String importMode = Constants.IMPORT_MODE_ADD;
                    if (replace && recordsToReplace.indexOf(subjectId) >= 0)
                        importMode = Constants.IMPORT_MODE_ALL;
                    succeeded = damsClient.updateObject(subjectId, graph.export(RDFStore.RDFXML_ABBREV_FORMAT),
                            importMode);

                    // Logging for Object RDF/XML validation
                    status[processIndex] = succeeded;
                    messages[processIndex].append(damsDateFormat.format(new Date()));

                    if (!succeeded) {
                        if (metadataFailed.indexOf(currFile) < 0)
                            failedCount++;
                        metadataFailed.append(subjectId + " (" + currFile + "), \n");
                        message = "Metadata import for record " + subjectId + " failed (" + (j + 1) + " of "
                                + jLen + ") in file " + currFile + ".";
                        setStatus(message);
                        log.error(message + "\n Error RDF: \n" + graph.export(RDFStore.RDFXML_ABBREV_FORMAT));
                    } else {
                        recordsIngested.add(subjectId);
                        message = "Metadata import for record " + subjectId + " succeeded (" + (j + 1) + " of "
                                + jLen + ") in file " + currFile + ". ";
                        setStatus(message);
                        log.info(message);

                        processIndex++;
                        status[processIndex] = succeeded;
                        messages[processIndex].append(damsDateFormat.format(new Date()));
                        // Ingest the source file only if metadata ingested successfully
                        if (status[processIndex] && importOption.equalsIgnoreCase("metadataAndFiles")) {
                            uploadFiles(objModel, currFile, subjectId);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();

                    if (metadataFailed.indexOf(currFile) < 0)
                        failedCount++;
                    metadataFailed.append(subjectId + " (" + currFile + "), \n");
                    message = "Metadata import failed: " + e.getMessage();
                    setStatus(message + " (" + (j + 1) + " of " + jLen + ") in file " + currFile + ".");
                    log.error(message);

                    String error = e.getMessage();
                    if (error.indexOf("Invalid RDF input") >= 0) {
                        messages[processIndex].append(error);
                    } else {
                        status[processIndex] = true;
                        messages[processIndex].append(damsDateFormat.format(new Date()));
                        processIndex++;
                        messages[processIndex].append(error);
                    }
                } finally {
                    int solrRequestIndex = processNames.length - 1;
                    try {
                        // Update SOLR for the record.
                        status[solrRequestIndex] = updateSOLR(subjectId);
                        messages[solrRequestIndex].append(damsDateFormat.format(new Date()));
                        log.info("SOLR update requested for " + subjectId + ": " + damsClient.getRequestURL()
                                + " " + status[solrRequestIndex]);

                    } catch (Exception e) {
                        e.printStackTrace();
                        exeResult = false;
                        log.error("SOLR Index failed " + subjectId + ": " + e.getMessage());

                        messages[processNames.length - 1].append(e.getMessage());
                    }

                    if (exeResult)
                        exeResult = status[processIndex];

                    String resultMessage = "http://" + Constants.CLUSTER_HOST_NAME + ".ucsd.edu/dc/object/"
                            + subjectId.substring(subjectId.lastIndexOf("/") + 1) + " - "
                            + (status[processIndex] && status[solrRequestIndex] ? "successful" : "failed")
                            + " - " + damsDateFormat.format(new Date());
                    if (objRecords.containsKey(subjectId)) {
                        String title = getTitle(objModel, subjectId);
                        if (StringUtils.isBlank(title))
                            title = "[Unknown Title]";

                        logMessage("\n" + title + " - " + resultMessage);
                        if (!status[processIndex] || !status[solrRequestIndex]) {
                            // Logging for pre-procesing - succeeded. 
                            logMessage("* Pre-processing - successful - " + preprocessedTimestamp);
                            for (int k = 0; k <= processIndex; k++) {
                                if (status[k] || !status[k] && status[k - 1]) {
                                    logMessage("* " + processNames[k] + " - "
                                            + (status[k] ? "successful" : "failed") + " - "
                                            + messages[k].toString());
                                }
                            }

                            // SOLR index request logging
                            if (!status[solrRequestIndex])
                                logMessage("* " + processNames[solrRequestIndex] + " - "
                                        + (status[solrRequestIndex] ? "successful" : "failed") + " - "
                                        + messages[solrRequestIndex].toString());
                        }

                    } else {

                        ingestMessages.append("\n" + resultMessage);
                        if (!status[processIndex]) {
                            for (int k = 0; k + 1 < processIndex; k++) {
                                if (status[k] || !status[k] && status[k - 1]) {
                                    logMessage("* " + processNames[k] + " - "
                                            + (status[k] ? "successful" : "failed") + " - "
                                            + messages[k].toString());
                                }
                            }
                        }
                    }
                }

                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    interrupted = true;
                    exeResult = false;
                    failedCount++;
                    metadataFailed.append(subjectId + " (" + currFile + ") \n");
                    message = "Metadata import interrupted for subject " + subjectId + ". \n Error: "
                            + e.getMessage() + "\n";
                    setStatus("Canceled");
                    clearSession();
                    log.error(message);

                    logMessage("Client Cancled - " + damsDateFormat.format(new Date()));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            exeResult = false;
            failedCount++;
            message = "Import failed for " + currFile + ": " + e.getMessage();
            setStatus(message + " (" + (i + 1) + " of " + fLen + ").");
            log.error(message);
        }

        setProgressPercentage(((i + 1) * 100) / fLen);

        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
            exeResult = false;
            interrupted = true;
            failedCount++;
            message = "Import interrupted for oject in " + currFile + ". \n Error: " + e.getMessage() + "\n";
            setStatus("Canceled");
            clearSession();
            log.error(message);

            messages[processIndex].append("Client canceled - " + damsDateFormat.format(new Date()));
        }
    }
    return exeResult;
}

From source file:edu.ucsd.library.xdre.imports.RDFDAMS4ImportTsHandler.java

/**
 * Update the document for DAMS ARK ID//from   w  ww. java 2  s  .  com
 * @param doc
 * @param record
 * @param title
 * @throws Exception
 */
private void updateDocument(Document doc, Node record, String field, String title, Map<String, String> props)
        throws Exception {
    // Skip if the record detached
    if (record.getDocument() == null)
        return;

    // Subject, Authority records use mads:authoritativeLabel
    Node aboutAttr = record.selectSingleNode("@rdf:about");
    String srcUri = aboutAttr.getStringValue();
    //String nName = record.getName();
    String xPath = record.getPath();
    String elemName = xPath.substring(xPath.lastIndexOf("/") + 1);

    String modelName = elemName;
    String nKey = INFO_MODEL_PREFIX + modelName + "::" + title;
    if (props != null) {
        for (Iterator<String> it = props.keySet().iterator(); it.hasNext();) {
            String iKey = it.next();
            nKey += "_" + iKey + "::" + props.get(iKey);
        }
    }
    String oid = idsMap.get(nKey);

    if (oid == null) {
        //Lookup records from the triplestore, matching the required properties that are null or empty.
        List<Map<String, String>> oids = lookupRecordsFromTs(field, title, "\"" + modelName + "\"", props);
        if (oids != null && oids.size() > 0) {

            String propName = null;
            String propValue = null;
            Document recDoc = null;
            Node cNode = null;
            if (props != null) {
                List<Map<String, String>> oidsCopy = new ArrayList<Map<String, String>>();
                oidsCopy.addAll(oids);
                for (int i = 0; i < oidsCopy.size(); i++) {

                    Collection<String> propValues = props.values();
                    Map<String, String> resolution = oidsCopy.get(i);
                    String rid = resolution.values().iterator().next();
                    if (rid.startsWith("http")) {
                        if (propValues.contains(null)) {

                            recDoc = damsClient.getRecord(rid);
                            for (Iterator<String> it = props.keySet().iterator(); it.hasNext();) {
                                propName = it.next();
                                propValue = props.get(propName);
                                // Test for the nodes for null properties and remove it from the result
                                if (propValue == null) {
                                    int idx = propName.indexOf("/", 1);
                                    if (idx > 0)
                                        cNode = recDoc.selectSingleNode("//" + modelName + "/" + propName);
                                    else
                                        cNode = recDoc.selectSingleNode("//" + modelName + "/" + propName);

                                    if (cNode != null) {
                                        oids.remove(resolution);
                                        break;
                                    }
                                }
                            }
                        }
                    } else // removed internal BlankNodes from the results
                        oids.remove(resolution);
                }
            }

            if (oids.size() > 0) {
                oid = oids.get(0).values().iterator().next();
                if (oids.size() > 1) {
                    String duids = "";
                    for (Iterator<Map<String, String>> it = oids.iterator(); it.hasNext();)
                        duids += (duids.length() > 0 ? ", " : "") + it.next().values().iterator().next();

                    log.warn("Duplicated records found for " + title + " (" + field + "): " + duids + ".");
                }
            }

        }

        if (oid == null) {
            // Create the record
            oid = getNewId();
            aboutAttr.setText(oid);
        } else {
            // Record found. Add to the map, link and remove it.
            toResourceLinking(oid, record);
        }
        idsMap.put(nKey, oid);
    } else {
        // Record added. Add linking, remove it.
        toResourceLinking(oid, record);
    }
    updateReference(doc, srcUri, oid);
}

From source file:hk.hku.cecid.piazza.commons.util.PropertyTree.java

License:Open Source License

/**
 * Sets a property value with the specified key.
 * /*from   w  w  w.j a  v  a 2s  .com*/
 * @param xpath the property xpath.
 * @param value the property value.
 * @return true if the operation is successful. false otherwise.
 * @see hk.hku.cecid.piazza.commons.util.PropertySheet#setProperty(java.lang.String,
 *      java.lang.String)
 */
public boolean setProperty(String xpath, String value) {
    Node node = getPropertyNode(xpath);
    boolean result;

    if (node == null) {
        result = addProperty(xpath, value);
    } else {
        try {
            if (value == null) {
                node.detach();
            } else {
                node.setText(value);
            }
            result = true;
        } catch (Exception e) {
            result = false;
        }
    }
    return result;
}

From source file:iqq.app.util.XmlUtils.java

License:Apache License

/**
 * ?XML//from  w  w w . j  av  a  2  s. com
 *
 * @param filename
 * @param key
 * @param Value
 */
public static void setNodeText(String filename, String key, String value)
        throws DocumentException, IOException {
    Document document = readXml(filename);
    Element rootElement = document.getRootElement();
    Node node = rootElement.selectSingleNode(key);
    if (node == null) {
        node = rootElement.addElement(key);
    }
    node.setText(value);
    writeXml(filename, document);
}

From source file:it.pdfsam.util.XMLConfig.java

License:Open Source License

/**
 * Given a DOM object it sets the new tag value
 * //from  w  w  w.  j  ava2 s . c  o  m
 * @param xpath
 * @param value new value of the xml tag
 * @return true or false
 */
public boolean setXMLConfigValue(String xpath, String value) throws Exception {
    boolean retvalue = false;
    Node node = DOM_document.selectSingleNode(xpath);
    if (node == null) {
        node = DOM_document.selectSingleNode(xpath.substring(0, xpath.lastIndexOf("//") - 1));
        if (node != null) {
            ((Element) node).addElement(xpath.substring(xpath.lastIndexOf("//")));
            retvalue = true;
        }
    } else {
        node.setText(value);
        retvalue = true;
    }
    return retvalue;
}

From source file:net.shopxx.action.admin.InstallAction.java

public String save() throws URISyntaxException, IOException, DocumentException {
    if (isInstalled()) {
        return ajaxJsonErrorMessage("SHOP++?????");
    }// ww  w  . j  a v a2  s. c om
    if (StringUtils.isEmpty(databaseHost)) {
        return ajaxJsonErrorMessage("?!");
    }
    if (StringUtils.isEmpty(databasePort)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(databaseUsername)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(databasePassword)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(databaseName)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(adminUsername)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(adminPassword)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(installStatus)) {
        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, "requiredCheckFinish");
        return ajaxJson(jsonMap);
    }

    String jdbcUrl = "jdbc:mysql://" + databaseHost + ":" + databasePort + "/" + databaseName
            + "?useUnicode=true&characterEncoding=UTF-8";
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    try {
        // ?
        connection = DriverManager.getConnection(jdbcUrl, databaseUsername, databasePassword);
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String[] types = { "TABLE" };
        resultSet = databaseMetaData.getTables(null, databaseName, "%", types);
        if (StringUtils.equalsIgnoreCase(installStatus, "databaseCheck")) {
            Map<String, String> jsonMap = new HashMap<String, String>();
            jsonMap.put(STATUS, "databaseCheckFinish");
            return ajaxJson(jsonMap);
        }

        // ?
        if (StringUtils.equalsIgnoreCase(installStatus, "databaseCreate")) {
            StringBuffer stringBuffer = new StringBuffer();
            BufferedReader bufferedReader = null;
            String sqlFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
                    .getPath() + SQL_INSTALL_FILE_NAME;
            bufferedReader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(sqlFilePath), "UTF-8"));
            String line = "";
            while (null != line) {
                line = bufferedReader.readLine();
                stringBuffer.append(line);
                if (null != line && line.endsWith(";")) {
                    System.out.println("[SHOP++?]SQL: " + line);
                    preparedStatement = connection.prepareStatement(stringBuffer.toString());
                    preparedStatement.executeUpdate();
                    stringBuffer = new StringBuffer();
                }
            }
            String insertAdminSql = "INSERT INTO `admin` VALUES ('402881862bec2a21012bec2bd8de0003','2010-10-10 0:0:0','2010-10-10 0:0:0','','admin@shopxx.net',b'1',b'0',b'0',b'0',NULL,NULL,0,NULL,'?','"
                    + DigestUtils.md5Hex(adminPassword) + "','" + adminUsername + "');";
            String insertAdminRoleSql = "INSERT INTO `admin_role` VALUES ('402881862bec2a21012bec2bd8de0003','402881862bec2a21012bec2b70510002');";
            preparedStatement = connection.prepareStatement(insertAdminSql);
            preparedStatement.executeUpdate();
            preparedStatement = connection.prepareStatement(insertAdminRoleSql);
            preparedStatement.executeUpdate();
        }
    } catch (SQLException e) {
        e.printStackTrace();
        return ajaxJsonErrorMessage("???!");
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
                resultSet = null;
            }
            if (preparedStatement != null) {
                preparedStatement.close();
                preparedStatement = null;
            }
            if (connection != null) {
                connection.close();
                connection = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // ???
    String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()
            + JDBC_CONFIG_FILE_NAME;
    Properties properties = new Properties();
    properties.put("jdbc.driver", "com.mysql.jdbc.Driver");
    properties.put("jdbc.url", jdbcUrl);
    properties.put("jdbc.username", databaseUsername);
    properties.put("jdbc.password", databasePassword);
    properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
    properties.put("hibernate.show_sql", "false");
    properties.put("hibernate.format_sql", "false");
    OutputStream outputStream = new FileOutputStream(configFilePath);
    properties.store(outputStream, JDBC_CONFIG_FILE_DESCRIPTION);
    outputStream.close();

    // ??
    String backupWebConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
            .getPath() + BACKUP_WEB_CONFIG_FILE_NAME;
    String backupApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + BACKUP_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String backupCompassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + BACKUP_COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String backupSecurityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + BACKUP_SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME;

    String webConfigFilePath = new File(
            Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()).getParent() + "/"
            + WEB_CONFIG_FILE_NAME;
    String applicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("")
            .toURI().getPath() + APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String compassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String securityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME;

    FileUtils.copyFile(new File(backupWebConfigFilePath), new File(webConfigFilePath));
    FileUtils.copyFile(new File(backupApplicationContextConfigFilePath),
            new File(applicationContextConfigFilePath));
    FileUtils.copyFile(new File(backupCompassApplicationContextConfigFilePath),
            new File(compassApplicationContextConfigFilePath));
    FileUtils.copyFile(new File(backupSecurityApplicationContextConfigFilePath),
            new File(securityApplicationContextConfigFilePath));

    // ??
    String systemConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
            .getPath() + SystemConfigUtil.CONFIG_FILE_NAME;
    File systemConfigFile = new File(systemConfigFilePath);
    SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(systemConfigFile);
    Element rootElement = document.getRootElement();
    Element systemConfigElement = rootElement.element("systemConfig");
    Node isInstalledNode = document.selectSingleNode("/shopxx/systemConfig/isInstalled");
    if (isInstalledNode == null) {
        isInstalledNode = systemConfigElement.addElement("isInstalled");
    }
    isInstalledNode.setText("true");
    try {
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();// XML?
        outputFormat.setEncoding("UTF-8");// XML?
        outputFormat.setIndent(true);// ?
        outputFormat.setIndent("   ");// TAB?
        outputFormat.setNewlines(true);// ??
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(systemConfigFile), outputFormat);
        xmlWriter.write(document);
        xmlWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ajaxJsonSuccessMessage("SHOP++?????");
}

From source file:org.apereo.portal.io.xml.SpELDataTemplatingStrategy.java

License:Apache License

@Override
public Source processTemplates(Document data, String filename) {

    log.trace("Processing templates for document XML={}", data.asXML());
    for (String xpath : XPATH_EXPRESSIONS) {
        @SuppressWarnings("unchecked")
        List<Node> nodes = data.selectNodes(xpath);
        for (Node n : nodes) {
            String inpt, otpt;/* ww  w .j  ava 2s .  co  m*/
            switch (n.getNodeType()) {
            case org.w3c.dom.Node.ATTRIBUTE_NODE:
                Attribute a = (Attribute) n;
                inpt = a.getValue();
                otpt = processText(inpt);
                if (otpt == null) {
                    throw new RuntimeException("Invalid expression '" + inpt + "' in file " + filename);
                }
                if (!otpt.equals(inpt)) {
                    a.setValue(otpt);
                }
                break;
            case org.w3c.dom.Node.TEXT_NODE:
            case org.w3c.dom.Node.CDATA_SECTION_NODE:
                inpt = n.getText();
                otpt = processText(inpt);
                if (otpt == null) {
                    throw new RuntimeException("Invalid expression '" + inpt + "' in file " + filename);
                }
                if (!otpt.equals(inpt)) {
                    n.setText(otpt);
                }
                break;
            default:
                String msg = "Unsupported node type:  " + n.getNodeTypeName();
                throw new RuntimeException(msg);
            }
        }
    }

    final SAXSource rslt = new DocumentSource(data);
    rslt.setSystemId(filename); // must be set, else import chokes
    return rslt;
}

From source file:org.collectionspace.chain.util.xtmpl.XTmplDocument.java

License:Educational Community License

@SuppressWarnings("unchecked")
public void setTexts(String key, String[] texts) {
    Node basis = document.selectSingleNode(attach.get(key));
    Element parent = basis.getParent();
    int pos = parent.indexOf(basis);
    List<Node> nodes = (List<Node>) parent.content();
    List<Node> after = new ArrayList(nodes.subList(pos + 1, nodes.size()));
    basis.detach();//from www  .jav a 2 s. co  m
    if (texts.length > 0) {
        for (Node n : after)
            n.detach();
        for (String text : texts) {
            Node renewed = (Node) basis.clone();
            renewed.setText(text);
            parent.add(renewed);
        }
        for (Node n : after)
            parent.add(n);
    }
}