Example usage for org.w3c.dom Document createComment

List of usage examples for org.w3c.dom Document createComment

Introduction

In this page you can find the example usage for org.w3c.dom Document createComment.

Prototype

public Comment createComment(String data);

Source Link

Document

Creates a Comment node given the specified string.

Usage

From source file:org.noerp.webtools.labelmanager.SaveLabelsToXmlFile.java

public static Map<String, Object> saveLabelsToXmlFile(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Locale locale = (Locale) context.get("locale");
    String fileName = (String) context.get("fileName");
    if (UtilValidate.isEmpty(fileName)) {
        Debug.logError("labelFileName cannot be empty", module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resource,
                "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale));
    }/* w w  w  .j  a v  a2s . c om*/
    String key = (String) context.get("key");
    String keyComment = (String) context.get("keyComment");
    String update_label = (String) context.get("update_label");
    String confirm = (String) context.get("confirm");
    String removeLabel = (String) context.get("removeLabel");
    List<String> localeNames = UtilGenerics.cast(context.get("localeNames"));
    List<String> localeValues = UtilGenerics.cast(context.get("localeValues"));
    List<String> localeComments = UtilGenerics.cast(context.get("localeComments"));
    String apacheLicenseText = null;
    try {
        apacheLicenseText = FileUtil.readString("UTF-8",
                FileUtil.getFile("component://webtools/config/APACHE2_HEADER_FOR_XML"));
    } catch (IOException e) {
        Debug.logWarning(e, "Unable to read Apache License text file", module);
    }
    try {
        LabelManagerFactory factory = LabelManagerFactory.getInstance();
        LabelFile labelFile = factory.getLabelFile(fileName);
        if (labelFile == null) {
            Debug.logError("Invalid file name: " + fileName, module);
            return ServiceUtil.returnFailure(UtilProperties.getMessage(resource,
                    "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale));
        }
        synchronized (SaveLabelsToXmlFile.class) {
            factory.findMatchingLabels(null, fileName, null, null);
            Map<String, LabelInfo> labels = factory.getLabels();
            Set<String> labelsList = factory.getLabelsList();
            Set<String> localesFound = factory.getLocalesFound();
            for (String localeName : localeNames) {
                localesFound.add(localeName);
            }
            // Remove a Label
            if (UtilValidate.isNotEmpty(removeLabel)) {
                labels.remove(key + LabelManagerFactory.keySeparator + fileName);
            } else if (UtilValidate.isNotEmpty(confirm)) {
                LabelInfo label = labels.get(key + LabelManagerFactory.keySeparator + fileName);
                // Update a Label
                if (update_label.equalsIgnoreCase("Y")) {
                    if (UtilValidate.isNotEmpty(label)) {
                        factory.updateLabelValue(localeNames, localeValues, localeComments, label, key,
                                keyComment, fileName);
                    }
                    // Insert a new Label
                } else {
                    if (UtilValidate.isNotEmpty(label)) {
                        return ServiceUtil.returnError(
                                UtilProperties.getMessage(resource, "WebtoolsLabelManagerNewLabelExisting",
                                        UtilMisc.toMap("key", key, "fileName", fileName), locale));
                    } else {
                        if (UtilValidate.isEmpty(key)) {
                            return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                                    "WebtoolsLabelManagerNewLabelEmptyKey", locale));
                        } else {
                            int notEmptyLabels = factory.updateLabelValue(localeNames, localeValues,
                                    localeComments, null, key, keyComment, fileName);
                            if (notEmptyLabels == 0) {
                                return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                                        "WebtoolsLabelManagerNewLabelEmpty", locale));
                            }
                        }
                    }
                }
            }
            Document resourceDocument = UtilXml.makeEmptyXmlDocument("resource");
            Element resourceElem = resourceDocument.getDocumentElement();
            resourceElem.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            resourceElem.setAttribute("xsi:noNamespaceSchemaLocation",
                    "http://noerp.apache.org/dtds/noerp-properties.xsd");
            for (String labelKey : labelsList) {
                LabelInfo labelInfo = labels.get(labelKey);
                if (!(labelInfo.getFileName().equalsIgnoreCase(fileName))) {
                    continue;
                }
                Element propertyElem = UtilXml.addChildElement(resourceElem, "property", resourceDocument);
                propertyElem.setAttribute("key", StringEscapeUtils.unescapeHtml(labelInfo.getLabelKey()));
                if (UtilValidate.isNotEmpty(labelInfo.getLabelKeyComment())) {
                    Comment labelKeyComment = resourceDocument
                            .createComment(StringEscapeUtils.unescapeHtml(labelInfo.getLabelKeyComment()));
                    Node parent = propertyElem.getParentNode();
                    parent.insertBefore(labelKeyComment, propertyElem);
                }
                for (String localeFound : localesFound) {
                    LabelValue labelValue = labelInfo.getLabelValue(localeFound);
                    String valueString = null;
                    if (labelValue != null) {
                        valueString = labelValue.getLabelValue();
                    }
                    if (UtilValidate.isNotEmpty(valueString)) {
                        valueString = StringEscapeUtils.unescapeHtml(valueString);
                        Element valueElem = UtilXml.addChildElementValue(propertyElem, "value", valueString,
                                resourceDocument);
                        valueElem.setAttribute("xml:lang", localeFound);
                        if (UtilValidate.isNotEmpty(labelValue.getLabelComment())) {
                            Comment labelComment = resourceDocument.createComment(
                                    StringEscapeUtils.unescapeHtml(labelValue.getLabelComment()));
                            Node parent = valueElem.getParentNode();
                            parent.insertBefore(labelComment, valueElem);
                        }
                    }
                }
                FileOutputStream fos = new FileOutputStream(labelFile.file);
                try {
                    if (apacheLicenseText != null) {
                        fos.write(apacheLicenseText.getBytes());
                    }
                    UtilXml.writeXmlDocument(resourceElem, fos, "UTF-8", !(apacheLicenseText == null), true, 4);
                } finally {
                    fos.close();
                    // clear cache to see immediately the new labels and
                    // translations in OFBiz
                    UtilCache.clearCache("properties.UtilPropertiesBundleCache");
                }
            }
        }
    } catch (Exception e) {
        Debug.logError(e, "Exception during save labels to xml file:", module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resource,
                "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale));
    }
    return ServiceUtil.returnSuccess();
}

From source file:org.ofbiz.webtools.labelmanager.SaveLabelsToXmlFile.java

public static Map<String, Object> saveLabelsToXmlFile(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Locale locale = (Locale) context.get("locale");
    String fileName = (String) context.get("fileName");
    if (UtilValidate.isEmpty(fileName)) {
        Debug.logError("labelFileName cannot be empty", module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resource,
                "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale));
    }//from w  w w .  jav a 2s. c om
    String key = (String) context.get("key");
    String keyComment = (String) context.get("keyComment");
    String update_label = (String) context.get("update_label");
    String confirm = (String) context.get("confirm");
    String removeLabel = (String) context.get("removeLabel");
    List<String> localeNames = UtilGenerics.cast(context.get("localeNames"));
    List<String> localeValues = UtilGenerics.cast(context.get("localeValues"));
    List<String> localeComments = UtilGenerics.cast(context.get("localeComments"));
    String apacheLicenseText = null;
    try {
        apacheLicenseText = FileUtil.readString("UTF-8",
                FileUtil.getFile("component://webtools/config/APACHE2_HEADER_FOR_XML"));
    } catch (IOException e) {
        Debug.logWarning(e, "Unable to read Apache License text file", module);
    }
    try {
        LabelManagerFactory factory = LabelManagerFactory.getInstance();
        LabelFile labelFile = factory.getLabelFile(fileName);
        if (labelFile == null) {
            Debug.logError("Invalid file name: " + fileName, module);
            return ServiceUtil.returnFailure(UtilProperties.getMessage(resource,
                    "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale));
        }
        synchronized (SaveLabelsToXmlFile.class) {
            factory.findMatchingLabels(null, fileName, null, null);
            Map<String, LabelInfo> labels = factory.getLabels();
            Set<String> labelsList = factory.getLabelsList();
            Set<String> localesFound = factory.getLocalesFound();
            for (String localeName : localeNames) {
                localesFound.add(localeName);
            }
            // Remove a Label
            if (UtilValidate.isNotEmpty(removeLabel)) {
                labels.remove(key + LabelManagerFactory.keySeparator + fileName);
            } else if (UtilValidate.isNotEmpty(confirm)) {
                LabelInfo label = labels.get(key + LabelManagerFactory.keySeparator + fileName);
                // Update a Label
                if (update_label.equalsIgnoreCase("Y")) {
                    if (UtilValidate.isNotEmpty(label)) {
                        factory.updateLabelValue(localeNames, localeValues, localeComments, label, key,
                                keyComment, fileName);
                    }
                    // Insert a new Label
                } else {
                    if (UtilValidate.isNotEmpty(label)) {
                        return ServiceUtil.returnError(
                                UtilProperties.getMessage(resource, "WebtoolsLabelManagerNewLabelExisting",
                                        UtilMisc.toMap("key", key, "fileName", fileName), locale));
                    } else {
                        if (UtilValidate.isEmpty(key)) {
                            return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                                    "WebtoolsLabelManagerNewLabelEmptyKey", locale));
                        } else {
                            int notEmptyLabels = factory.updateLabelValue(localeNames, localeValues,
                                    localeComments, null, key, keyComment, fileName);
                            if (notEmptyLabels == 0) {
                                return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                                        "WebtoolsLabelManagerNewLabelEmpty", locale));
                            }
                        }
                    }
                }
            }
            Document resourceDocument = UtilXml.makeEmptyXmlDocument("resource");
            Element resourceElem = resourceDocument.getDocumentElement();
            resourceElem.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            resourceElem.setAttribute("xsi:noNamespaceSchemaLocation",
                    "http://ofbiz.apache.org/dtds/ofbiz-properties.xsd");
            for (String labelKey : labelsList) {
                LabelInfo labelInfo = labels.get(labelKey);
                if (!(labelInfo.getFileName().equalsIgnoreCase(fileName))) {
                    continue;
                }
                Element propertyElem = UtilXml.addChildElement(resourceElem, "property", resourceDocument);
                propertyElem.setAttribute("key", StringEscapeUtils.unescapeHtml(labelInfo.getLabelKey()));
                if (UtilValidate.isNotEmpty(labelInfo.getLabelKeyComment())) {
                    Comment labelKeyComment = resourceDocument
                            .createComment(StringEscapeUtils.unescapeHtml(labelInfo.getLabelKeyComment()));
                    Node parent = propertyElem.getParentNode();
                    parent.insertBefore(labelKeyComment, propertyElem);
                }
                for (String localeFound : localesFound) {
                    LabelValue labelValue = labelInfo.getLabelValue(localeFound);
                    String valueString = null;
                    if (labelValue != null) {
                        valueString = labelValue.getLabelValue();
                    }
                    if (UtilValidate.isNotEmpty(valueString)) {
                        valueString = StringEscapeUtils.unescapeHtml(valueString);
                        Element valueElem = UtilXml.addChildElementValue(propertyElem, "value", valueString,
                                resourceDocument);
                        valueElem.setAttribute("xml:lang", localeFound);
                        if (UtilValidate.isNotEmpty(labelValue.getLabelComment())) {
                            Comment labelComment = resourceDocument.createComment(
                                    StringEscapeUtils.unescapeHtml(labelValue.getLabelComment()));
                            Node parent = valueElem.getParentNode();
                            parent.insertBefore(labelComment, valueElem);
                        }
                    }
                }
                FileOutputStream fos = new FileOutputStream(labelFile.file);
                try {
                    if (apacheLicenseText != null) {
                        fos.write(apacheLicenseText.getBytes());
                    }
                    UtilXml.writeXmlDocument(resourceElem, fos, "UTF-8", !(apacheLicenseText == null), true, 4);
                } finally {
                    fos.close();
                    // clear cache to see immediately the new labels and
                    // translations in OFBiz
                    UtilCache.clearCache("properties.UtilPropertiesBundleCache");
                }
            }
        }
    } catch (Exception e) {
        Debug.logError(e, "Exception during save labels to xml file:", module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resource,
                "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale));
    }
    return ServiceUtil.returnSuccess();
}

From source file:org.sakaiproject.tool.assessment.qti.asi.ASIBaseClass.java

protected void wrappingMattext() {
    log.debug("wrappingMattext()");

    try {//from w  w  w  .j a v a  2s .  co m
        NodeList list = this.getDocument().getElementsByTagName(QTIConstantStrings.MATTEXT);
        int size = list.getLength();
        for (int i = 0; i < size; i++) {
            Node node = list.item(i);
            Node childNode = node.getFirstChild();
            if ((childNode != null) && childNode instanceof CharacterData) {
                CharacterData cdi = (CharacterData) childNode;
                String data = cdi.getData();

                //modify this string;
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.newDocument();
                Comment comment = doc.createComment(data);
                node.appendChild(node.getOwnerDocument().importNode(comment, true));
                cdi.setData("");
            }
        }
    } catch (ParserConfigurationException e) {
        log.error(e.getMessage(), e);
    } catch (SAXException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:org.structr.websocket.command.dom.CreateAndAppendDOMNodeCommand.java

@Override
public void processMessage(WebSocketMessage webSocketData) {

    final Map<String, Object> nodeData = webSocketData.getNodeData();
    final String parentId = (String) nodeData.get("parentId");
    final String childContent = (String) nodeData.get("childContent");
    final String pageId = webSocketData.getPageId();

    nodeData.remove("parentId");

    if (pageId != null) {

        // check for parent ID before creating any nodes
        if (parentId == null) {

            getWebSocket().send(/*  w  ww . j a v a  2  s  . c o m*/
                    MessageBuilder.status().code(422).message("Cannot add node without parentId").build(),
                    true);
            return;
        }

        // check if parent node with given ID exists
        final DOMNode parentNode = getDOMNode(parentId);
        if (parentNode == null) {

            getWebSocket().send(MessageBuilder.status().code(404).message("Parent node not found").build(),
                    true);
            return;
        }

        final Document document = getPage(pageId);
        if (document != null) {

            final String tagName = (String) nodeData.get("tagName");

            nodeData.remove("tagName");

            try {

                DOMNode newNode;

                if (tagName != null && "comment".equals(tagName)) {

                    newNode = (DOMNode) document.createComment("#comment");

                } else if (tagName != null && "template".equals(tagName)) {

                    newNode = (DOMNode) document.createTextNode("#template");

                    try {

                        newNode.setProperty(NodeInterface.type, Template.class.getSimpleName());

                    } catch (FrameworkException fex) {

                        logger.log(Level.WARNING, "Unable to set type of node {1} to Template: {3}",
                                new Object[] { newNode.getUuid(), fex.getMessage() });

                    }

                } else if (tagName != null && !tagName.isEmpty()) {

                    newNode = (DOMNode) document.createElement(tagName);

                } else {

                    newNode = (DOMNode) document.createTextNode("#text");
                }

                // Instantiate node again to get correct class
                newNode = getDOMNode(newNode.getUuid());

                // append new node to parent
                if (newNode != null) {

                    parentNode.appendChild(newNode);

                    for (Entry entry : nodeData.entrySet()) {

                        final String key = (String) entry.getKey();
                        final Object val = entry.getValue();

                        PropertyKey propertyKey = StructrApp.getConfiguration()
                                .getPropertyKeyForDatabaseName(newNode.getClass(), key);
                        if (propertyKey != null) {

                            try {
                                Object convertedValue = val;

                                PropertyConverter inputConverter = propertyKey
                                        .inputConverter(SecurityContext.getSuperUserInstance());
                                if (inputConverter != null) {

                                    convertedValue = inputConverter.convert(val);
                                }

                                //newNode.unlockReadOnlyPropertiesOnce();
                                newNode.setProperty(propertyKey, convertedValue);

                            } catch (FrameworkException fex) {

                                logger.log(Level.WARNING,
                                        "Unable to set node property {0} of node {1} to {2}: {3}",
                                        new Object[] { propertyKey, newNode.getUuid(), val, fex.getMessage() });

                            }
                        }

                    }

                    // create a child text node if content is given
                    if (StringUtils.isNotBlank(childContent)) {

                        final DOMNode childNode = (DOMNode) document.createTextNode(childContent);

                        newNode.appendChild(childNode);

                    }

                }

            } catch (DOMException dex) {

                // send DOM exception
                getWebSocket().send(MessageBuilder.status().code(422).message(dex.getMessage()).build(), true);

            }

        } else {

            getWebSocket().send(MessageBuilder.status().code(404).message("Page not found").build(), true);
        }

    } else {

        getWebSocket().send(
                MessageBuilder.status().code(422).message("Cannot create node without pageId").build(), true);
    }
}

From source file:org.talend.designer.maven.tools.creator.CreateMavenJobPom.java

@SuppressWarnings("nls")
private void addAssemblyFiles(Node filesElem, String source, String outputDirectory, String destName,
        String fileMode, String lineEnding, boolean filtered, String comment) {
    Assert.isNotNull(filesElem);//ww w.  ja  va  2 s.c  o  m
    Assert.isNotNull(source);
    Assert.isNotNull(outputDirectory);

    Document doc = filesElem.getOwnerDocument();

    Element fileEle = doc.createElement("file");
    filesElem.appendChild(fileEle);

    if (comment != null) {
        fileEle.appendChild(doc.createComment(comment));
    }

    Element sourceElement = doc.createElement("source");
    sourceElement.setTextContent(source);
    fileEle.appendChild(sourceElement);

    Element outputDirectoryElement = doc.createElement("outputDirectory");
    outputDirectoryElement.setTextContent(outputDirectory);
    fileEle.appendChild(outputDirectoryElement);

    if (destName != null) { // if not set, will be same as source
        Element destNameElement = doc.createElement("destName");
        destNameElement.setTextContent(destName);
        fileEle.appendChild(destNameElement);
    }
    if (fileMode != null) {
        Element fileModeElement = doc.createElement("fileMode");
        fileModeElement.setTextContent(fileMode);
        fileEle.appendChild(fileModeElement);
    }
    if (lineEnding != null) {
        Element lineEndingElement = doc.createElement("lineEnding");
        lineEndingElement.setTextContent(lineEnding);
        fileEle.appendChild(lineEndingElement);
    }
    if (filtered) { // by default is false
        Element filteredElement = doc.createElement("filtered");
        filteredElement.setTextContent(Boolean.TRUE.toString());
        fileEle.appendChild(filteredElement);
    }
}

From source file:org.talend.designer.maven.tools.creator.CreateMavenJobPom.java

@SuppressWarnings("nls")
private void addAssemblyFileSets(Node fileSetsNode, String directory, String outputDirectory,
        boolean useDefaultExcludes, List<String> includes, List<String> excludes, String fileMode,
        String directoryMode, String lineEnding, boolean filtered, String comment) {
    Assert.isNotNull(fileSetsNode);/*  www.j  a  va  2s  .  co  m*/
    Assert.isNotNull(outputDirectory);
    Assert.isNotNull(directory);

    Document doc = fileSetsNode.getOwnerDocument();

    Element fileSetEle = doc.createElement("fileSet");
    fileSetsNode.appendChild(fileSetEle);

    if (comment != null) {
        fileSetEle.appendChild(doc.createComment(comment));
    }

    Element outputDirectoryElement = doc.createElement("outputDirectory");
    outputDirectoryElement.setTextContent(outputDirectory);
    fileSetEle.appendChild(outputDirectoryElement);

    Element directoryElement = doc.createElement("directory");
    directoryElement.setTextContent(directory);
    fileSetEle.appendChild(directoryElement);

    if (useDefaultExcludes) { // false by default
        Element useDefaultExcludesElement = doc.createElement("useDefaultExcludes");
        useDefaultExcludesElement.setTextContent(Boolean.TRUE.toString());
        fileSetEle.appendChild(useDefaultExcludesElement);
    }

    if (includes != null && !includes.isEmpty()) {

        Element includesEle = doc.createElement("includes");
        fileSetEle.appendChild(includesEle);
        for (String in : includes) {
            Element includeElement = doc.createElement("include");
            includeElement.setTextContent(in);
            includesEle.appendChild(includeElement);
        }
    }

    if (excludes != null && !excludes.isEmpty()) {
        Element excludesEle = doc.createElement("excludes");
        fileSetEle.appendChild(excludesEle);
        for (String ex : excludes) {
            Element excludeElement = doc.createElement("exclude");
            excludeElement.setTextContent(ex);
            excludesEle.appendChild(excludeElement);

        }
    }
    if (fileMode != null) {
        Element fileModeElement = doc.createElement("fileMode");
        fileModeElement.setTextContent(fileMode);
        fileSetEle.appendChild(fileModeElement);
    }
    if (directoryMode != null) {
        Element directoryModeElement = doc.createElement("directoryMode");
        directoryModeElement.setTextContent(directoryMode);
        fileSetEle.appendChild(directoryModeElement);
    }

    if (lineEnding != null) {
        Element lineEndingElement = doc.createElement("lineEnding");
        lineEndingElement.setTextContent(lineEnding);
        fileSetEle.appendChild(lineEndingElement);
    }
    if (filtered) { // by default is false
        Element filteredElement = doc.createElement("filtered");
        filteredElement.setTextContent(Boolean.TRUE.toString());
        fileSetEle.appendChild(filteredElement);
    }
}

From source file:org.xwiki.officeimporter.internal.filter.ImageFilter.java

/**
 * {@inheritDoc}/*from  ww w .  j  a v  a 2  s  . co  m*/
 */
public void filter(Document htmlDocument, Map<String, String> cleaningParams) {
    String targetDocument = cleaningParams.get("targetDocument");
    DocumentReference targetDocumentReference = null;

    List<Element> images = filterDescendants(htmlDocument.getDocumentElement(), new String[] { TAG_IMG });
    for (Element image : images) {
        if (targetDocumentReference == null && !StringUtils.isBlank(targetDocument)) {
            targetDocumentReference = documentStringReferenceResolver.resolve(targetDocument);
        }
        String src = image.getAttribute(ATTRIBUTE_SRC);
        if (!StringUtils.isBlank(src) && targetDocumentReference != null) {
            // OpenOffice 3.2 server generates relative image paths, extract image name.
            int separator = src.lastIndexOf("/");
            if (-1 != separator) {
                src = src.substring(separator + 1);
            }
            try {
                // We have to decode the image file name in case it contains URL special characters.
                src = URLDecoder.decode(src, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // This should never happen.
            }

            // Set image source attribute relative to the reference document.
            AttachmentReference attachmentReference = new AttachmentReference(src, targetDocumentReference);
            image.setAttribute(ATTRIBUTE_SRC,
                    documentAccessBridge.getAttachmentURL(attachmentReference, false));

            // The 'align' attribute of images creates a lot of problems. First, OO server has a problem with
            // center aligning images (it aligns them to left). Next, OO server uses <br clear"xxx"> for
            // avoiding content wrapping around images which is not valid xhtml. There for, to be consistent and
            // simple we will remove the 'align' attribute of all the images so that they are all left aligned.
            image.removeAttribute(ATTRIBUTE_ALIGN);
        } else if (src.startsWith("file://")) {
            src = "Missing.png";
            image.setAttribute(ATTRIBUTE_SRC, src);
            image.setAttribute(ATTRIBUTE_ALT, src);
        }
        ResourceReference imageReference = new ResourceReference(src, ResourceType.ATTACHMENT);
        imageReference.setTyped(false);
        Comment beforeComment = htmlDocument
                .createComment("startimage:" + this.xhtmlMarkerSerializer.serialize(imageReference));
        Comment afterComment = htmlDocument.createComment("stopimage");
        image.getParentNode().insertBefore(beforeComment, image);
        image.getParentNode().insertBefore(afterComment, image.getNextSibling());
    }
}

From source file:sos.scheduler.cron.CronConverter.java

/**
 * Converts a crontab to a Scheduler XML as DOM document and
 * provides easy access to the job elements by putting them to the vector
 * jobs/*ww w. j a  va2  s . c om*/
 * @param cronFile crontab file
 * @param cron2jobMapping empty vector which will be filled with cron lines mapped to job DOM Elements
 * @return DOM Document with scheduler configuration
 * @throws Exception
 */
public Document cronFile2SchedulerXML(final File cronFile, final HashMap<String, Element> cron2jobMapping)
        throws Exception {
    try {
        HashSet<String> jobNames = new HashSet<String>();
        if (reservedJobNames != null) {
            jobNames.addAll(reservedJobNames);
        }
        HashMap<String, String> environmentVariables = new HashMap<String, String>();
        Document configurationDoc = docBuilder.newDocument();
        Element spoolerElement = configurationDoc.createElement(conTagSPOOLER);
        configurationDoc.appendChild(spoolerElement);
        Element configElement = configurationDoc.createElement("config");
        spoolerElement.appendChild(configElement);
        Element jobsElement = configurationDoc.createElement("jobs");
        configElement.appendChild(jobsElement);

        BufferedReader in = new BufferedReader(new FileReader(cronFile));
        Vector<Element> vecJobs = new Vector<Element>();
        Vector<String> vecCronRecords = new Vector<String>();
        lastComment = "";
        String lastCommentJobName = "";
        String lastCommentJobTitle = "";
        String lastCommentJobTimeout = "";

        while ((strCronLine = in.readLine()) != null) {
            if (strCronLine.trim().length() == 0) {
                lastComment = "";
                continue;
            }
            if (skipLines != null && skipLines.contains(strCronLine)) {
                logger.debug("Skipping line " + strCronLine);
                lastComment = "";
                lastCommentJobName = "";
                lastCommentJobTitle = "";
                lastCommentJobTimeout = "";
                continue;
            }

            Matcher commentMatcher = cronRegExCommentPattern.matcher(strCronLine);
            if (commentMatcher.matches()) {
                Matcher jobNameMatcher = cronRegExJobNamePattern.matcher(commentMatcher.group(1));
                Matcher jobTitleMatcher = cronRegExJobTitlePattern.matcher(commentMatcher.group(1));
                Matcher jobTimeoutMatcher = cronRegExJobTimeoutPattern.matcher(commentMatcher.group(1));
                if (jobNameMatcher.matches()) {
                    lastCommentJobName = jobNameMatcher.group(1);
                    logger.debug("Found job name in comment: " + lastCommentJobName);
                    continue;
                }
                if (jobTitleMatcher.matches()) {
                    lastCommentJobTitle = jobTitleMatcher.group(1);
                    logger.debug("Found job title in comment: " + lastCommentJobTitle);
                    continue;
                }
                if (jobTimeoutMatcher.matches()) {
                    lastCommentJobTimeout = jobTimeoutMatcher.group(1);
                    logger.debug("Found job timeout in comment: " + lastCommentJobTimeout);
                    continue;
                }
                if (lastComment.length() > 0) {
                    lastComment += conNewline;
                }
                lastComment += commentMatcher.group(1);
                continue;
            }

            Matcher environmentMatcher = cronRegExEnvironmentPattern.matcher(strCronLine);
            if (environmentMatcher.matches()) {
                String envName = environmentMatcher.group(1);
                String envValue = environmentMatcher.group(2);
                logger.debug("Found environment variable [" + envName + "]: " + envValue);
                if (envValue.startsWith("\"") && envValue.endsWith("\"")) {
                    envValue = envValue.substring(1, envValue.length() - 1);
                }
                environmentVariables.put(envName, envValue);
                lastComment = "";
            }

            Matcher cronMatcher = currentCronPattern.matcher(strCronLine);
            Matcher cronAliasMatcher = cronRegExAliasPattern.matcher(strCronLine);
            if (cronMatcher.matches() || cronAliasMatcher.matches()) {
                vecCronRecords.add(strCronLine);
                Document jobDocument = createJobElement(strCronLine, environmentVariables);
                Element jobElement = jobDocument.getDocumentElement();
                //NodeList jobChildren = jobElement.getChildNodes();
                //Element paramsElement = null;
                /*for (int i=0; i<jobChildren.getLength() && paramsElement==null;i++){
                   Node currentNode = jobChildren.item(i);
                   if (currentNode.getNodeName().equals("params")) paramsElement = (Element) currentNode;
                }*/

                boolean jobNameChanged = false;
                if (lastCommentJobName.length() > 0) {
                    jobElement.setAttribute(conAttributeNAME, lastCommentJobName.replaceAll("/", "_"));
                    lastCommentJobName = "";
                }
                if (lastCommentJobTitle.length() > 0) {
                    jobElement.setAttribute(conAttributeTITLE, lastCommentJobTitle);
                    lastCommentJobTitle = "";
                }
                if (lastCommentJobTimeout.length() > 0) {
                    jobElement.setAttribute(conOptionTIMEOUT, lastCommentJobTimeout);
                    lastCommentJobTimeout = "";
                }
                String jobName = jobElement.getAttribute(conAttributeNAME);
                while (jobNames.contains(jobName)) {
                    //                  logger.debug("Configuration already contains a job named \"" + jobName + "\". Looking for new name.");
                    jobName = incrementJobName(jobName);
                    jobNameChanged = true;
                }
                if (jobNameChanged) {
                    logger.debug("Setting new job name \"" + jobName + "\"");
                    jobElement.setAttribute(conAttributeNAME, jobName);
                }
                jobNames.add(jobName);
                Node importedJob = configurationDoc.importNode(jobElement, true);
                cron2jobMapping.put(strCronLine, jobElement);

                if (lastComment.length() > 0) {
                    // change "--" to "__" due to problems with xml-comment parser
                    lastComment = lastComment.replaceAll("--", "__");
                    Comment jobComment = configurationDoc.createComment(lastComment);
                    jobsElement.appendChild(jobComment);
                }
                jobsElement.appendChild(importedJob);
                lastComment = "";
                vecJobs.add(jobElement);
            }
        }
        if (isCreateJobChainJobs()) {
            Element jobChainsElement = configurationDoc.createElement("job_chains");
            configElement.appendChild(jobChainsElement);

            int i = 0;
            for (Element objJobElement : vecJobs) {
                strCronLine = vecCronRecords.get(i++);
                Document objJCD = createJobChainElement(objJobElement);
                Element objJC = objJCD.getDocumentElement();
                jobChainsElement.appendChild(configurationDoc.importNode(objJC, true));
            }

            Element commandsElement = configurationDoc.createElement("commands");
            configElement.appendChild(commandsElement);

            i = 0;
            for (Element objJobElement : vecJobs) {
                strCronLine = vecCronRecords.get(i++);
                Document objJCD = createOrderElement(objJobElement);
                Element objJC = objJCD.getDocumentElement();
                commandsElement.appendChild(configurationDoc.importNode(objJC, true));
            }

        }
        in.close();
        return configurationDoc;
    } catch (Exception e) {
        throw new JobSchedulerException(
                "Error converting file " + cronFile.getAbsolutePath() + " to JobScheduler XML: " + e, e);
    }

}

From source file:sos.scheduler.cron.CronConverter.java

public Document createJobElement(String cronline, final HashMap<String, String> environmentVariables)
        throws Exception {
    try {/*from   www.ja  v  a2s .  c  o m*/
        logger.info("processing line: " + cronline);
        Document eleJob = docBuilder.newDocument();
        Element jobElement = eleJob.createElement(conTagJOB);

        Matcher cronRegExAliasMatcher = cronRegExAliasPattern.matcher(cronline);
        if (cronRegExAliasMatcher.matches()) {
            logger.debug("Current line matches pattern " + cronRegExAlias);
            cronline = convertAlias(cronRegExAliasMatcher);
        }
        Matcher cronRegExMatcher = cronRegExPattern.matcher(cronline);
        int commandIndex = 6;

        if (isSystemCronTab()) {
            commandIndex = 7;
            cronRegExMatcher = cronRegExSystemPattern.matcher(cronline);
        }
        if (!cronRegExMatcher.matches()) {
            throw new JobSchedulerException("Fail to parse cron line \"" + cronline + "\"");
        }
        String jobname = getJobName(cronRegExMatcher.group(commandIndex));
        jobElement.setAttribute(conAttributeNAME, jobname);
        if (isCreateJobChainJobs()) {
            jobElement.setAttribute(conAttributeORDER, "yes");
        } else {
            jobElement.setAttribute(conAttributeORDER, "no");
        }
        jobElement.setAttribute(conAttributeTITLE, "Cron Job " + cronRegExMatcher.group(commandIndex).trim());
        //jobElement.setAttribute("replace", "yes");
        if (timeout != null && !timeout.equals("0")) {
            jobElement.setAttribute(conOptionTIMEOUT, timeout);
        }

        String schedulerUser = "";
        String command = cronRegExMatcher.group(commandIndex);
        if (isSystemCronTab()) {
            schedulerUser = cronRegExMatcher.group(6);
            command = (changeUserCommand + " " + command).trim();
        }

        jobElement.appendChild(createExtension(eleJob));

        if (isCreateJobChainJobs() == false) {
            logger.debug("Creating params element");
            Element paramsElement = eleJob.createElement("params");
            logger.debug("Creating param element (command)");
            Element paramCommandElement = eleJob.createElement("param");
            paramCommandElement.setAttribute("name", "command");
            paramCommandElement.setAttribute("value", command);
            paramsElement.appendChild(paramCommandElement);
            jobElement.appendChild(paramsElement);
        }

        logger.debug("Creating script element");
        Element scriptElement = eleJob.createElement(conTagSCRIPT);
        scriptElement.setAttribute(conAttributeLANGUAGE, "shell");
        String script = conNewline;
        if (schedulerUser.length() > 0) {
            script += "export SCHEDULER_CRONTAB_USER=" + schedulerUser + conNewline;
        }
        Iterator<String> envIter = environmentVariables.keySet().iterator();
        // set environment variables on job
        while (envIter.hasNext()) {
            String envName = envIter.next().toString();
            String envValue = environmentVariables.get(envName).toString();
            script += envName + "=" + envValue + conNewline;
            script += "export " + envName;
        }

        script += "echo created by " + conClassName + ", at " + SOSDate.getCurrentTimeAsString() + conNewline;
        if (isCreateAMock() == true) {
            script += "echo mock-mode: " + command + conNewline;
            if (strMockCommand.length() > 0) {
                script += strMockCommand + conNewline;
            }
            script += "exit 0" + conNewline;
        } else {
            script += command;
        }

        Node scriptData = eleJob.createCDATASection(script);
        scriptElement.appendChild(scriptData);
        jobElement.appendChild(scriptElement);

        if (isCreateJobChainJobs() == false) {
            Element runTimeElement = eleJob.createElement(conTagRUN_TIME);
            createRunTime(cronRegExMatcher, runTimeElement);
            if (usedNewRunTime && oldRunTime) {
                // workaround while <month> Element is not available
                // can later be deleted (keep only else branch)
                usedNewRunTime = false;
                Document runTimeDocument = docBuilder.newDocument();
                runTimeDocument.appendChild(runTimeDocument.importNode(runTimeElement, true));
                StringWriter out = new StringWriter();
                OutputFormat format = new OutputFormat(runTimeDocument);
                format.setIndenting(true);
                format.setIndent(2);
                format.setOmitXMLDeclaration(true);
                XMLSerializer serializer = new XMLSerializer(out, format);
                serializer.serialize(runTimeDocument);
                Comment runTimeComment = eleJob
                        .createComment("This run_time is currently not supported:\n" + out.toString());
                jobElement.appendChild(runTimeComment);
            } else {
                jobElement.appendChild(runTimeElement);
            }
        }

        eleJob.appendChild(jobElement);
        return eleJob;
    } catch (Exception e) {
        throw new JobSchedulerException("Error occured creating job from cron line: " + cronline, e);
    }
}

From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java

@Test
public void testCheckDigestedNode() throws Exception {
    // setup/*from www. j  a  v  a 2 s . c  o  m*/
    Init.init();
    KeyPair keyPair = PkiTestUtils.generateKeyPair();

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.newDocument();
    Element rootElement = document.createElementNS("urn:test", "tns:root");
    rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:test");
    document.appendChild(rootElement);
    Element dataElement = document.createElementNS("urn:test", "tns:data");
    dataElement.setAttributeNS(null, "Id", "id-1234");
    dataElement.setTextContent("data to be signed");
    rootElement.appendChild(dataElement);

    Element data2Element = document.createElementNS("urn:test", "tns:data2");
    rootElement.appendChild(data2Element);
    data2Element.setTextContent("hello world");
    data2Element.setAttribute("name", "value");
    Element data3Element = document.createElementNS("urn:test", "tns:data3");
    data2Element.appendChild(data3Element);
    data3Element.setTextContent("data 3");
    data3Element.appendChild(document.createComment("some comments"));

    Element emptyElement = document.createElementNS("urn:test", "tns:empty");
    rootElement.appendChild(emptyElement);

    org.apache.xml.security.signature.XMLSignature xmlSignature = new org.apache.xml.security.signature.XMLSignature(
            document, "", org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);
    rootElement.appendChild(xmlSignature.getElement());

    Transforms transforms = new Transforms(document);
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    xmlSignature.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);

    xmlSignature.addKeyInfo(keyPair.getPublic());
    xmlSignature.sign(keyPair.getPrivate());

    NodeList signatureNodeList = document.getDocumentElement()
            .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature");
    Element signatureElement = (Element) signatureNodeList.item(0);

    // operate & verify
    assertTrue(isDigested(dataElement, signatureElement));
    assertTrue(isDigested(data2Element, signatureElement));
    assertTrue(isDigested(emptyElement, signatureElement));
}