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:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.FeatureCatalogue.java

/**
 * Transforms the contents of the temporary feature catalogue xml and
 * inserts it into a specific place (denoted by a placeholder) of a docx
 * template file. The result is copied into a new output file. The template
 * file is not modified.// www  .j  a v a2  s  .  com
 * 
 * @param xmlName
 *            Name of the temporary feature catalogue xml file, located in
 *            the output directory.
 * @param outfileBasename
 *            Base name of the output file, without file type ending.
 */
private void writeDOCX(String xmlName, String outfileBasename) {

    if (!OutputFormat.toLowerCase().contains("docx"))
        return;

    StatusBoard.getStatusBoard().statusChanged(STATUS_WRITE_DOCX);

    ZipHandler zipHandler = new ZipHandler();

    String docxfileName = outfileBasename + ".docx";

    try {

        // Setup directories
        File outDir = new File(outputDirectory);
        File tmpDir = new File(outDir, "tmpdocx");
        File tmpinputDir = new File(tmpDir, "input");
        File tmpoutputDir = new File(tmpDir, "output");

        // get docx template

        // create temporary file for the docx template copy
        File docxtemplate_copy = new File(tmpDir, "docxtemplatecopy.tmp");

        // populate temporary file either from remote or local URI
        if (docxTemplateFilePath.toLowerCase().startsWith("http")) {
            URL templateUrl = new URL(docxTemplateFilePath);
            FileUtils.copyURLToFile(templateUrl, docxtemplate_copy);
        } else {
            File docxtemplate = new File(docxTemplateFilePath);
            if (docxtemplate.exists()) {
                FileUtils.copyFile(docxtemplate, docxtemplate_copy);
            } else {
                result.addError(this, 19, docxtemplate.getAbsolutePath());
                return;
            }
        }

        /*
         * Unzip the docx template to tmpinputDir and tmpoutputDir The
         * contents of the tmpinputdir will be used as input for the
         * transformation. The transformation result will overwrite the
         * relevant files in the tmpoutputDir.
         */
        zipHandler.unzip(docxtemplate_copy, tmpinputDir);
        zipHandler.unzip(docxtemplate_copy, tmpoutputDir);

        /*
         * Get hold of the styles.xml file from which the transformation
         * will get relevant information. The path to this file will be used
         * as a transformation parameter.
         */
        File styleXmlFile = new File(tmpinputDir, "word/styles.xml");
        if (!styleXmlFile.canRead()) {
            result.addError(null, 301, styleXmlFile.getName(), "styles.xml");
            return;
        }

        /*
         * Get hold of the temporary feature catalog xml file. The path to
         * this file will be used as a transformation parameter.
         */
        File xmlFile = new File(outDir, xmlName);
        if (!styleXmlFile.canRead()) {
            result.addError(null, 301, styleXmlFile.getName(), xmlName);
            return;
        }

        /*
         * Get hold of the input document.xml file (internal .xml file from
         * the docxtemplate). It will be used as the source for the
         * transformation.
         */
        File indocumentxmlFile = new File(tmpinputDir, "word/document.xml");
        if (!indocumentxmlFile.canRead()) {
            result.addError(null, 301, indocumentxmlFile.getName(), "document.xml");
            return;
        }

        /*
         * Get hold of the output document.xml file. It will be used as the
         * transformation target.
         */
        File outdocumentxmlFile = new File(tmpoutputDir, "word/document.xml");
        if (!outdocumentxmlFile.canWrite()) {
            result.addError(null, 307, outdocumentxmlFile.getName(), "document.xml");
            return;
        }

        /*
         * Prepare the transformation.
         */
        transformationParameters.put("styleXmlPath", styleXmlFile.toURI().toString());
        transformationParameters.put("catalogXmlPath", xmlFile.toURI().toString());
        transformationParameters.put("DOCX_PLACEHOLDER", DOCX_PLACEHOLDER);

        /*
         * Execute the transformation.
         */
        this.xsltWrite(indocumentxmlFile, xsldocxfileName, outdocumentxmlFile);

        if (includeDiagrams) {
            /*
             * === Process image information ===
             */

            /*
             * 1. Copy content of temporary images folder to output folder
             */
            File mediaDir = new File(tmpoutputDir, "word/media");
            FileUtils.copyDirectoryToDirectory(options.imageTmpDir(), mediaDir);

            /*
             * 2. Create image information file. The path to this file will
             * be used as a transformation parameter.
             */

            Document imgInfoDoc = createDocument();

            imgInfoDoc.appendChild(imgInfoDoc.createComment("Temporary file containing image metadata"));

            Element imgInfoRoot = imgInfoDoc.createElement("images");
            imgInfoDoc.appendChild(imgInfoRoot);

            addAttribute(imgInfoDoc, imgInfoRoot, "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");

            List<ImageMetadata> imageList = new ArrayList<ImageMetadata>(imageSet);
            Collections.sort(imageList, new Comparator<ImageMetadata>() {

                @Override
                public int compare(ImageMetadata o1, ImageMetadata o2) {
                    return o1.getId().compareTo(o2.getId());
                }
            });

            for (ImageMetadata im : imageList) {

                Element e1 = imgInfoDoc.createElement("image");

                addAttribute(imgInfoDoc, e1, "id", im.getId());
                addAttribute(imgInfoDoc, e1, "relPath", im.getRelPathToFile());

                imgInfoRoot.appendChild(e1);
            }

            Properties outputFormat = OutputPropertiesFactory.getDefaultMethodProperties("xml");
            outputFormat.setProperty("indent", "yes");
            outputFormat.setProperty("{http://xml.apache.org/xalan}indent-amount", "2");
            if (encoding != null)
                outputFormat.setProperty("encoding", encoding);

            File relsFile = new File(tmpDir, "docx_relationships.tmp.xml");

            try {

                OutputStream fout = new FileOutputStream(relsFile);
                OutputStream bout = new BufferedOutputStream(fout);
                OutputStreamWriter outputXML = new OutputStreamWriter(bout,
                        outputFormat.getProperty("encoding"));

                Serializer serializer = SerializerFactory.getSerializer(outputFormat);
                serializer.setWriter(outputXML);
                serializer.asDOMSerializer().serialize(imgInfoDoc);
                outputXML.close();
            } catch (Exception e) {
                String m = e.getMessage();
                if (m != null) {
                    result.addError(m);
                }
                e.printStackTrace(System.err);
            }

            /*
             * 3. Apply transformation to relationships file
             */

            /*
             * Get hold of the input relationships file (internal file from
             * the docx template). It will be used as the source for the
             * transformation.
             */

            File inRelsXmlFile = new File(tmpinputDir, "word/_rels/document.xml.rels");
            if (!inRelsXmlFile.canRead()) {
                result.addError(null, 301, inRelsXmlFile.getName(), "document.xml.rels");
                return;
            }

            /*
             * Get hold of the output relationships file. It will be used as
             * the transformation target.
             */
            File outRelsXmlFile = new File(tmpoutputDir, "word/_rels/document.xml.rels");
            if (!outRelsXmlFile.canWrite()) {
                result.addError(null, 307, outRelsXmlFile.getName(), "document.xml.rels");
                return;
            }

            /*
             * Prepare the transformation.
             */
            transformationParameters.put("imageInfoXmlPath", relsFile.toURI().toString());

            /*
             * Execute the transformation.
             */
            this.xsltWrite(inRelsXmlFile, xsldocxrelsfileName, outRelsXmlFile);
        }

        /*
         * === Create the docx result file ===
         */

        // Get hold of the output docx file (it will be overwritten or
        // initialized).
        File outFile = new File(outDir, docxfileName);

        /*
         * Zip the temporary output directory and copy it to the output docx
         * file.
         */
        zipHandler.zip(tmpoutputDir, outFile);

        /*
         * === Delete the temporary directory ===
         */

        try {
            FileUtils.deleteDirectory(tmpDir);
        } catch (IOException e) {
            result.addWarning(this, 20, e.getMessage());
        }

        result.addResult(getTargetID(), outputDirectory, docxfileName, null);

    } catch (Exception e) {
        String m = e.getMessage();
        if (m != null) {
            result.addError(m);
        }
        e.printStackTrace(System.err);
    }
}

From source file:nl.b3p.viewer.admin.stripes.GeoServiceActionBean.java

public Resolution generateSld() throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from  w  w w.j  a v a2  s.  c  o m
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document sldDoc = db.newDocument();

    Element sldEl = sldDoc.createElementNS(NS_SLD, "StyledLayerDescriptor");
    sldDoc.appendChild(sldEl);
    sldEl.setAttributeNS(NS_SLD, "version", "1.0.0");
    sldEl.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation",
            "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd");
    sldEl.setAttribute("xmlns:ogc", NS_OGC);
    sldEl.setAttribute("xmlns:gml", NS_GML);
    service.loadLayerTree();

    Queue<Layer> layerStack = new LinkedList();
    Layer l = service.getTopLayer();
    while (l != null) {
        layerStack.addAll(service.getLayerChildrenCache(l));

        if (l.getName() != null) {
            Element nlEl = sldDoc.createElementNS(NS_SLD, "NamedLayer");
            sldEl.appendChild(nlEl);
            String title = l.getTitleAlias() != null ? l.getTitleAlias() : l.getTitle();
            if (title != null) {
                nlEl.appendChild(sldDoc.createComment(" Layer '" + title + "' "));
            }
            Element nEl = sldDoc.createElementNS(NS_SLD, "Name");
            nEl.setTextContent(l.getName());
            nlEl.appendChild(nEl);

            if (l.getFeatureType() != null) {
                String protocol = "";
                if (l.getFeatureType().getFeatureSource() != null) {
                    protocol = " (protocol " + l.getFeatureType().getFeatureSource().getProtocol() + ")";
                }

                String ftComment = " This layer has a feature type" + protocol
                        + " you can use in a FeatureTypeConstraint element as follows:\n";
                ftComment += "            <LayerFeatureConstraints>\n";
                ftComment += "                <FeatureTypeConstraint>\n";
                ftComment += "                    <FeatureTypeName>" + l.getFeatureType().getTypeName()
                        + "</FeatureTypeName>\n";
                ftComment += "                    Add ogc:Filter or Extent element here. ";
                if (l.getFeatureType().getAttributes().isEmpty()) {
                    ftComment += " No feature type attributes are known.\n";
                } else {
                    ftComment += " You can use the following feature type attributes in ogc:PropertyName elements:\n";
                    for (AttributeDescriptor ad : l.getFeatureType().getAttributes()) {
                        ftComment += "                    <ogc:PropertyName>" + ad.getName()
                                + "</ogc:PropertyName>";
                        if (ad.getAlias() != null) {
                            ftComment += " (" + ad.getAlias() + ")";
                        }
                        if (ad.getType() != null) {
                            ftComment += " (type: " + ad.getType() + ")";
                        }
                        ftComment += "\n";
                    }
                }
                ftComment += "                </FeatureTypeConstraint>\n";
                ftComment += "            </LayerFeatureConstraints>\n";
                ftComment += "        ";
                nlEl.appendChild(sldDoc.createComment(ftComment));
            }

            nlEl.appendChild(sldDoc.createComment(" Add a UserStyle or NamedStyle element here "));
            String styleComment = " (no server-side named styles are known other than 'default') ";
            ClobElement styleDetail = l.getDetails().get(Layer.DETAIL_WMS_STYLES);
            if (styleDetail != null) {
                try {
                    JSONArray styles = new JSONArray(styleDetail.getValue());

                    if (styles.length() > 0) {
                        styleComment = " The following NamedStyles are available according to the capabilities: \n";

                        for (int i = 0; i < styles.length(); i++) {
                            JSONObject jStyle = styles.getJSONObject(i);

                            styleComment += "            <NamedStyle><Name>" + jStyle.getString("name")
                                    + "</Name></NamedStyle>";
                            if (jStyle.has("title")) {
                                styleComment += " (" + jStyle.getString("title") + ")";
                            }
                            styleComment += "\n";
                        }
                    }

                } catch (JSONException e) {
                }
                styleComment += "        ";
            }
            nlEl.appendChild(sldDoc.createComment(styleComment));
        }

        l = layerStack.poll();
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    DOMSource source = new DOMSource(sldDoc);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(bos);
    t.transform(source, result);
    generatedSld = new String(bos.toByteArray(), "UTF-8");

    // indent doesn't add newline after XML declaration
    generatedSld = generatedSld.replaceFirst("\"\\?><StyledLayerDescriptor", "\"?>\n<StyledLayerDescriptor");
    return new ForwardResolution(JSP_EDIT_SLD);
}

From source file:org.ajax4jsf.webapp.tidy.TidyParser.java

private org.w3c.dom.Node importNode(Document document, org.w3c.dom.Node node, boolean recursive) {

    switch (node.getNodeType()) {
    case org.w3c.dom.Node.ELEMENT_NODE:
        Element element = document.createElement(node.getNodeName());

        NamedNodeMap attributes = node.getAttributes();
        if (attributes != null) {
            int length = attributes.getLength();
            for (int i = 0; i < length; i++) {
                element.setAttributeNode((Attr) importNode(document, attributes.item(i), recursive));
            }//w  w  w .ja  va2s.c  o  m
        }

        if (recursive) {
            NodeList childNodes = node.getChildNodes();
            if (childNodes != null) {
                int length = childNodes.getLength();
                for (int i = 0; i < length; i++) {
                    element.appendChild(importNode(document, childNodes.item(i), recursive));
                }
            }
        }

        return element;

    case org.w3c.dom.Node.ATTRIBUTE_NODE:
        Attr attr = document.createAttribute(node.getNodeName());
        attr.setNodeValue(node.getNodeValue());

        return attr;

    case org.w3c.dom.Node.TEXT_NODE:
        String charData = ((CharacterData) node).getData();

        return document.createTextNode(charData);

    case org.w3c.dom.Node.CDATA_SECTION_NODE:
        charData = ((CharacterData) node).getData();

        return document.createCDATASection(charData);
    case org.w3c.dom.Node.COMMENT_NODE:
        charData = ((CharacterData) node).getData();

        return document.createComment(charData);
    case org.w3c.dom.Node.DOCUMENT_FRAGMENT_NODE:
    case org.w3c.dom.Node.DOCUMENT_NODE:
    case org.w3c.dom.Node.ENTITY_NODE:
    case org.w3c.dom.Node.ENTITY_REFERENCE_NODE:
    case org.w3c.dom.Node.NOTATION_NODE:
    case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE:
    default:
        throw new IllegalArgumentException("Unsupported node type: " + node.getNodeType());
    }
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

/**
 * Generate the XForm based on a user supplied XML Schema.
 *
 * @param instanceDocument The document source for the XML Schema.
 * @param schemaDocument Schema document
 * @param rootElementName Name of the root element
 * @param resourceBundle Strings to use/*from   w  ww.  j a v  a 2 s  . c  om*/
 * @return The Document containing the XForm.
 * @throws org.chiba.tools.schemabuilder.FormBuilderException
 *          If an error occurs building the XForm.
 */
public Pair<Document, XSModel> buildXForm(final Document instanceDocument, final Document schemaDocument,
        String rootElementName, final ResourceBundle resourceBundle) throws FormBuilderException {
    final XSModel schema = SchemaUtil.parseSchema(schemaDocument, true);
    this.typeTree = SchemaUtil.buildTypeTree(schema);

    //refCounter = 0;
    this.counter.clear();

    final Document xformsDocument = this.createFormTemplate(rootElementName);

    //find form element: last element created
    final Element formSection = (Element) xformsDocument.getDocumentElement().getLastChild();
    final Element modelSection = (Element) xformsDocument.getDocumentElement()
            .getElementsByTagNameNS(NamespaceConstants.XFORMS_NS, "model").item(0);

    //add XMLSchema if we use schema types      
    final Element importedSchemaDocumentElement = (Element) xformsDocument
            .importNode(schemaDocument.getDocumentElement(), true);
    importedSchemaDocumentElement.setAttributeNS(null, "id", "schema-1");

    NodeList nl = importedSchemaDocumentElement.getChildNodes();
    boolean hasExternalSchema = false;

    for (int i = 0; i < nl.getLength(); i++) {
        Node current = nl.item(i);
        if (current.getNamespaceURI() != null
                && current.getNamespaceURI().equals(NamespaceConstants.XMLSCHEMA_NS)) {
            String localName = current.getLocalName();
            if (localName.equals("include") || localName.equals("import")) {
                hasExternalSchema = true;
                break;
            }
        }
    }

    // ALF-8105 / ETWOTWO-1384: Only embed the schema if it does not reference externals
    if (!hasExternalSchema) {
        modelSection.appendChild(importedSchemaDocumentElement);
    }

    //check if target namespace
    final StringList schemaNamespaces = schema.getNamespaces();
    final HashMap<String, String> schemaNamespacesMap = new HashMap<String, String>();
    if (schemaNamespaces.getLength() != 0) {
        // will return null if no target namespace was specified
        this.targetNamespace = schemaNamespaces.item(0);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("[buildXForm] using targetNamespace " + this.targetNamespace);

        for (int i = 0; i < schemaNamespaces.getLength(); i++) {
            if (schemaNamespaces.item(i) == null) {
                continue;
            }
            final String prefix = addNamespace(xformsDocument.getDocumentElement(),
                    schemaDocument.lookupPrefix(schemaNamespaces.item(i)), schemaNamespaces.item(i));
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[buildXForm] adding namespace " + schemaNamespaces.item(i) + " with prefix "
                        + prefix + " to xform and default instance element");
            }
            schemaNamespacesMap.put(prefix, schemaNamespaces.item(i));
        }
    }

    //if target namespace & we use the schema types: add it to form ns declarations
    //   if (this.targetNamespace != null && this.targetNamespace.length() != 0)
    //       envelopeElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
    //                  "xmlns:schema",
    //                  this.targetNamespace);

    final XSElementDeclaration rootElementDecl = schema.getElementDeclaration(rootElementName,
            this.targetNamespace);
    if (rootElementDecl == null) {
        throw new FormBuilderException("Invalid root element tag name [" + rootElementName
                + ", targetNamespace = " + this.targetNamespace + "]");
    }

    rootElementName = this.getElementName(rootElementDecl, xformsDocument);
    final Element instanceElement = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS,
            NamespaceConstants.XFORMS_PREFIX + ":instance");
    modelSection.appendChild(instanceElement);
    this.setXFormsId(instanceElement);

    final Element defaultInstanceDocumentElement = xformsDocument.createElement(rootElementName);
    addNamespace(defaultInstanceDocumentElement, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
    if (this.targetNamespace != null) {
        final String targetNamespacePrefix = schemaDocument.lookupPrefix(this.targetNamespace);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[buildXForm] adding target namespace " + this.targetNamespace + " with prefix "
                    + targetNamespacePrefix + " to xform and default instance element");
        }

        addNamespace(defaultInstanceDocumentElement, targetNamespacePrefix, this.targetNamespace);
        addNamespace(xformsDocument.getDocumentElement(), targetNamespacePrefix, this.targetNamespace);
    }

    Element prototypeInstanceElement = null;
    if (instanceDocument == null || instanceDocument.getDocumentElement() == null) {
        instanceElement.appendChild(defaultInstanceDocumentElement);
    } else {
        Element instanceDocumentElement = instanceDocument.getDocumentElement();
        if (!instanceDocumentElement.getNodeName().equals(rootElementName)) {
            throw new IllegalArgumentException("instance document root tag name invalid.  " + "expected "
                    + rootElementName + ", got " + instanceDocumentElement.getNodeName());
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("[buildXForm] importing rootElement from other document");

        prototypeInstanceElement = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS,
                NamespaceConstants.XFORMS_PREFIX + ":instance");
        modelSection.appendChild(prototypeInstanceElement);
        this.setXFormsId(prototypeInstanceElement, "instance_prototype");
        prototypeInstanceElement.appendChild(defaultInstanceDocumentElement);
    }

    final Element rootGroup = this.addElement(xformsDocument, modelSection, defaultInstanceDocumentElement,
            formSection, schema, rootElementDecl, "/" + this.getElementName(rootElementDecl, xformsDocument),
            new SchemaUtil.Occurrence(1, 1), resourceBundle);
    if (rootGroup.getNodeName() != NamespaceConstants.XFORMS_PREFIX + ":group") {
        throw new FormBuilderException("Expected root form element to be a " + NamespaceConstants.XFORMS_PREFIX
                + ":group, not a " + rootGroup.getNodeName() + ".  Ensure that "
                + this.getElementName(rootElementDecl, xformsDocument)
                + " is a concrete type that has no extensions.  "
                + "Types with extensions are not supported for " + "the root element of a form.");
    }
    this.setXFormsId(rootGroup, "alfresco-xforms-root-group");

    if (prototypeInstanceElement != null) {
        Schema2XForms.rebuildInstance(prototypeInstanceElement, instanceDocument, instanceElement,
                schemaNamespacesMap);
    }

    this.createSubmitElements(xformsDocument, modelSection, rootGroup);
    this.createTriggersForRepeats(xformsDocument, rootGroup);

    final Comment comment = xformsDocument.createComment(
            "This XForm was generated by " + this.getClass().getName() + " on " + (new Date()) + " from the '"
                    + rootElementName + "' element of the '" + this.targetNamespace + "' XML Schema.");
    xformsDocument.getDocumentElement().insertBefore(comment,
            xformsDocument.getDocumentElement().getFirstChild());
    xformsDocument.normalizeDocument();

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("[buildXForm] Returning XForm =\n" + XMLUtil.toString(xformsDocument));

    return new Pair<Document, XSModel>(xformsDocument, schema);
}

From source file:org.apache.axis.wsdl.fromJava.Emitter.java

/**
 * Generates a WSDL document for a given <code>Class</code>.
 * The WSDL generated is controlled by the mode parameter
 * mode 0: All//  w w w .  ja  va2s.c o  m
 * mode 1: Interface
 * mode 2: Implementation
 * 
 * @param mode generation mode - all, interface, implementation
 * @return Document
 * @throws IOException                  
 * @throws WSDLException                
 * @throws SAXException                 
 * @throws ParserConfigurationException 
 */
public Document emit(int mode) throws IOException, WSDLException, SAXException, ParserConfigurationException {

    Document doc;
    Definition def;

    switch (mode) {

    default:
    case MODE_ALL:
        def = getWSDL();

        for (int i = 0; (extraClasses != null) && (i < extraClasses.length); i++) {
            types.writeTypeForPart(extraClasses[i], null);
        }

        // types.updateNamespaces();
        doc = WSDLFactory.newInstance().newWSDLWriter().getDocument(def);

        types.insertTypesFragment(doc);
        break;

    case MODE_INTERFACE:
        def = getIntfWSDL();

        for (int i = 0; (extraClasses != null) && (i < extraClasses.length); i++) {
            types.writeTypeForPart(extraClasses[i], null);
        }

        // types.updateNamespaces();
        doc = WSDLFactory.newInstance().newWSDLWriter().getDocument(def);

        types.insertTypesFragment(doc);
        break;

    case MODE_IMPLEMENTATION:
        def = getImplWSDL();
        doc = WSDLFactory.newInstance().newWSDLWriter().getDocument(def);
        break;
    }

    // Add Axis version info as comment to beginnning of generated WSDL
    if (versionMessage == null) {
        versionMessage = Messages.getMessage("wsdlCreated00", XMLUtils.xmlEncodeString(Version.getVersion()));
    }
    // If version is empty string, don't emit one
    if (versionMessage != null && versionMessage.length() > 0) {
        Comment wsdlVersion = doc.createComment(versionMessage);
        doc.getDocumentElement().insertBefore(wsdlVersion, doc.getDocumentElement().getFirstChild());
    }

    // Return the document
    return doc;
}

From source file:org.apache.ode.utils.DOMUtils.java

private static void parse(XMLStreamReader reader, Document doc, Node parent) throws XMLStreamException {
    int event = reader.getEventType();

    while (reader.hasNext()) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            // create element
            Element e = doc.createElementNS(reader.getNamespaceURI(), reader.getLocalName());
            if (reader.getPrefix() != null && reader.getPrefix() != "") {
                e.setPrefix(reader.getPrefix());
            }/* w  ww  .  j a va  2s  . co m*/
            parent.appendChild(e);

            // copy namespaces
            for (int ns = 0; ns < reader.getNamespaceCount(); ns++) {
                String uri = reader.getNamespaceURI(ns);
                String prefix = reader.getNamespacePrefix(ns);
                declare(e, uri, prefix);
            }

            // copy attributes
            for (int att = 0; att < reader.getAttributeCount(); att++) {
                String name = reader.getAttributeLocalName(att);
                String prefix = reader.getAttributePrefix(att);
                if (prefix != null && prefix.length() > 0) {
                    name = prefix + ":" + name;
                }
                Attr attr = doc.createAttributeNS(reader.getAttributeNamespace(att), name);
                attr.setValue(reader.getAttributeValue(att));
                e.setAttributeNode(attr);
            }
            // sub-nodes
            if (reader.hasNext()) {
                reader.next();
                parse(reader, doc, e);
            }
            if (parent instanceof Document) {
                while (reader.hasNext())
                    reader.next();
                return;
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            return;
        case XMLStreamConstants.CHARACTERS:
            if (parent != null) {
                parent.appendChild(doc.createTextNode(reader.getText()));
            }
            break;
        case XMLStreamConstants.COMMENT:
            if (parent != null) {
                parent.appendChild(doc.createComment(reader.getText()));
            }
            break;
        case XMLStreamConstants.CDATA:
            parent.appendChild(doc.createCDATASection(reader.getText()));
            break;
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData()));
            break;
        case XMLStreamConstants.ENTITY_REFERENCE:
            parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData()));
            break;
        case XMLStreamConstants.NAMESPACE:
        case XMLStreamConstants.ATTRIBUTE:
            break;
        default:
            break;
        }

        if (reader.hasNext()) {
            event = reader.next();
        }
    }
}

From source file:org.apache.ode.utils.DOMUtils.java

/**
 * Deep clone, but don't fry, the given node in the context of the given document.
 * For all intents and purposes, the clone is the exact same copy of the node,
 * except that it might have a different owner document.
 *
 * This method is fool-proof, unlike the <code>adoptNode</code> or <code>adoptNode</code> methods,
 * in that it doesn't assume that the given node has a parent or a owner document.
 *
 * @param document/* www  .j a  v  a2  s . c om*/
 * @param sourceNode
 * @return a clone of node
 */
public static Node cloneNode(Document document, Node sourceNode) {
    Node clonedNode = null;

    // what is my name?
    QName sourceQName = getNodeQName(sourceNode);
    String nodeName = sourceQName.getLocalPart();
    String namespaceURI = sourceQName.getNamespaceURI();

    // if the node is unqualified, don't assume that it inherits the WS-BPEL target namespace
    if (Namespaces.WSBPEL2_0_FINAL_EXEC.equals(namespaceURI)) {
        namespaceURI = null;
    }

    switch (sourceNode.getNodeType()) {
    case Node.ATTRIBUTE_NODE:
        if (namespaceURI == null) {
            clonedNode = document.createAttribute(nodeName);
        } else {
            String prefix = ((Attr) sourceNode).lookupPrefix(namespaceURI);
            // the prefix for the XML namespace can't be looked up, hence this...
            if (prefix == null && namespaceURI.equals(NS_URI_XMLNS)) {
                prefix = "xmlns";
            }
            // if a prefix exists, qualify the name with it
            if (prefix != null && !"".equals(prefix)) {
                nodeName = prefix + ":" + nodeName;
            }
            // create the appropriate type of attribute
            if (prefix != null) {
                clonedNode = document.createAttributeNS(namespaceURI, nodeName);
            } else {
                clonedNode = document.createAttribute(nodeName);
            }
        }
        break;
    case Node.CDATA_SECTION_NODE:
        clonedNode = document.createCDATASection(((CDATASection) sourceNode).getData());
        break;
    case Node.COMMENT_NODE:
        clonedNode = document.createComment(((Comment) sourceNode).getData());
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        clonedNode = document.createDocumentFragment();
        break;
    case Node.DOCUMENT_NODE:
        clonedNode = document;
        break;
    case Node.ELEMENT_NODE:
        // create the appropriate type of element
        if (namespaceURI == null) {
            clonedNode = document.createElement(nodeName);
        } else {
            String prefix = namespaceURI.equals(Namespaces.XMLNS_URI) ? "xmlns"
                    : ((Element) sourceNode).lookupPrefix(namespaceURI);
            if (prefix != null && !"".equals(prefix)) {
                nodeName = prefix + ":" + nodeName;
                clonedNode = document.createElementNS(namespaceURI, nodeName);
            } else {
                clonedNode = document.createElement(nodeName);
            }
        }
        // attributes are not treated as child nodes, so copy them explicitly
        NamedNodeMap attributes = ((Element) sourceNode).getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Attr attributeClone = (Attr) cloneNode(document, attributes.item(i));
            if (attributeClone.getNamespaceURI() == null) {
                ((Element) clonedNode).setAttributeNode(attributeClone);
            } else {
                ((Element) clonedNode).setAttributeNodeNS(attributeClone);
            }
        }
        break;
    case Node.ENTITY_NODE:
        // TODO
        break;
    case Node.ENTITY_REFERENCE_NODE:
        clonedNode = document.createEntityReference(nodeName);
        // TODO
        break;
    case Node.NOTATION_NODE:
        // TODO
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        clonedNode = document.createProcessingInstruction(((ProcessingInstruction) sourceNode).getData(),
                nodeName);
        break;
    case Node.TEXT_NODE:
        clonedNode = document.createTextNode(((Text) sourceNode).getData());
        break;
    default:
        break;
    }

    // clone children of element and attribute nodes
    NodeList sourceChildren = sourceNode.getChildNodes();
    if (sourceChildren != null) {
        for (int i = 0; i < sourceChildren.getLength(); i++) {
            Node sourceChild = sourceChildren.item(i);
            Node clonedChild = cloneNode(document, sourceChild);
            clonedNode.appendChild(clonedChild);
            // if the child has a textual value, parse it for any embedded prefixes
            if (clonedChild.getNodeType() == Node.TEXT_NODE
                    || clonedChild.getNodeType() == Node.CDATA_SECTION_NODE) {
                parseEmbeddedPrefixes(sourceNode, clonedNode, clonedChild);
            }
        }
    }
    return clonedNode;
}

From source file:org.apache.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));
    }/* w w w  . ja  va  2s.  co  m*/
    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, false);
            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.apache.ws.security.message.SignatureTest.java

/**
 * This is a test for WSS-234 - //from ww w . java 2s. co  m
 * "When a document contains a comment as its first child element, 
 * wss4j will not find the SOAP body." 
 */
@org.junit.Test
public void testWSS234() throws Exception {
    WSSecSignature builder = new WSSecSignature();
    builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security");
    LOG.info("Before Signing....");
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Document signedDoc = builder.build(doc, crypto, secHeader);

    // Add a comment node as the first node element
    org.w3c.dom.Node firstChild = signedDoc.getFirstChild();
    org.w3c.dom.Node newNode = signedDoc.removeChild(firstChild);
    org.w3c.dom.Node commentNode = signedDoc.createComment("This is a comment");
    signedDoc.appendChild(commentNode);
    signedDoc.appendChild(newNode);

    if (LOG.isDebugEnabled()) {
        LOG.debug("After Signing....");
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc);
        LOG.debug(outputString);
    }

    verify(signedDoc);
}

From source file:org.apache.xml.security.samples.signature.CreateMerlinsExampleSixteen.java

/**
 * Method main/*from  w ww .  ja  v  a  2s. c  o  m*/
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {
    Constants.setSignatureSpecNSprefix("ds");
    //J-
    String keystoreType = "JKS";
    String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("merlinsSixteenRecreatedNoRetrievalMethod.xml");
    //J+
    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    ks.load(fis, keystorePass.toCharArray());

    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());

    if (privateKey == null) {
        throw new RuntimeException("Private key is null");
    }

    X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();

    //////////////////////////////////////////////////
    Element envelope = doc.createElementNS("http://www.usps.gov/", "Envelope");

    envelope.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "http://www.usps.gov/");
    envelope.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:foo", "http://www.usps.gov/foo");
    envelope.appendChild(doc.createTextNode("\n"));
    doc.appendChild(doc.createComment(" Preamble "));
    doc.appendChild(envelope);
    doc.appendChild(doc.createComment(" Postamble "));

    Element dearSir = doc.createElementNS("http://www.usps.gov/", "DearSir");

    dearSir.appendChild(doc.createTextNode("foo"));
    envelope.appendChild(dearSir);
    envelope.appendChild(doc.createTextNode("\n"));

    Element body = doc.createElementNS("http://www.usps.gov/", "Body");

    body.appendChild(doc.createTextNode("bar"));
    envelope.appendChild(body);
    envelope.appendChild(doc.createTextNode("\n"));

    Element YoursSincerely = doc.createElementNS("http://www.usps.gov/", "YoursSincerely");
    YoursSincerely.appendChild(doc.createTextNode("\n"));

    envelope.appendChild(YoursSincerely);

    Element PostScript = doc.createElementNS("http://www.usps.gov/", "PostScript");

    PostScript.appendChild(doc.createTextNode("bar"));
    envelope.appendChild(PostScript);

    Element Notaries = doc.createElementNS(null, "Notaries");

    Notaries.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
    Notaries.setAttributeNS(null, "Id", "notaries");
    IdResolver.registerElementById(Notaries, "Id");

    {
        Element Notary = doc.createElementNS(null, "Notary");

        Notary.setAttributeNS(null, "name", "Great, A. T.");
        Notaries.appendChild(Notary);
    }

    {
        Element Notary = doc.createElementNS(null, "Notary");

        Notary.setAttributeNS(null, "name", "Hun, A. T.");
        Notaries.appendChild(Notary);
    }

    envelope.appendChild(Notaries);
    envelope.appendChild(doc.createComment(" Commentary "));

    //////////////////////////////////////////////////
    String BaseURI = signatureFile.toURL().toString();
    XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA);

    YoursSincerely.appendChild(sig.getElement());
    sig.setId("signature");

    /*
     * Add the Objects
     */

    // object-1
    {
        ObjectContainer object1 = new ObjectContainer(doc);

        object1.setId("object-1");
        object1.setMimeType("text/plain");
        object1.appendChild(doc.createTextNode("I am the text."));
        sig.appendObject(object1);
    }

    // object-2
    {
        ObjectContainer object2 = new ObjectContainer(doc);

        object2.setId("object-2");
        object2.setMimeType("text/plain");
        object2.setEncoding("http://www.w3.org/2000/09/xmldsig#base64");
        object2.appendChild(doc.createTextNode("SSBhbSB0aGUgdGV4dC4="));
        sig.appendObject(object2);
    }

    // object-3
    {
        ObjectContainer object = new ObjectContainer(doc);

        object.setId("object-3");

        Element nonc = doc.createElementNS(null, "NonCommentandus");

        nonc.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
        nonc.appendChild(doc.createComment(" Commentandum "));
        object.appendChild(doc.createTextNode("\n        "));
        object.appendChild(nonc);
        object.appendChild(doc.createTextNode("\n      "));
        sig.appendObject(object);
    }

    // object number 4
    {
        ObjectContainer object = new ObjectContainer(doc);

        object.appendChild(createObject4(sig));
        sig.appendObject(object);
    }

    // object number 4
    {
        ObjectContainer object = new ObjectContainer(doc);
        SignatureProperties sps = new SignatureProperties(doc);

        sps.setId("signature-properties-1");

        SignatureProperty sp = new SignatureProperty(doc, "#signature");
        Element signedAdress = doc.createElementNS("urn:demo", "SignedAddress");

        signedAdress.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "urn:demo");

        Element IP = doc.createElementNS("urn:demo", "IP");

        IP.appendChild(doc.createTextNode("192.168.21.138"));
        signedAdress.appendChild(IP);
        sp.appendChild(signedAdress);
        sps.addSignatureProperty(sp);
        object.appendChild(sps.getElement());
        sig.appendObject(object);
    }

    {
        ObjectContainer object = new ObjectContainer(doc);

        object.setId("object-4");

        X509Data x509data = new X509Data(doc);

        x509data.add(new XMLX509SubjectName(doc, cert));
        x509data.add(new XMLX509IssuerSerial(doc, cert));
        x509data.add(new XMLX509Certificate(doc, cert));
        object.appendChild(x509data.getElement());
        sig.appendObject(object);
    }

    /*
     * Add References
     */
    sig.getSignedInfo()
            .addResourceResolver(new org.apache.xml.security.samples.utils.resolver.OfflineResolver());
    sig.addDocument("http://www.w3.org/TR/xml-stylesheet");

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_BASE64_DECODE);
        sig.addDocument("http://xmldsig.pothole.com/xml-stylesheet.txt", transforms,
                Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);
        XPathContainer xpathC = new XPathContainer(doc);

        xpathC.setXPath("self::text()");
        transforms.addTransform(Transforms.TRANSFORM_XPATH, xpathC.getElementPlusReturns());
        sig.addDocument("#object-1", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }
    /*
    {
       Transforms transforms = new Transforms(doc);
       XPathContainer xpathC = new XPathContainer(doc);
            
       //J-
       xpathC.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);
       xpathC.setXPath("\n"
        + " ancestor-or-self::ds:SignedInfo                    " + "\n"
        + "  and                                               " + "\n"
        + " count(ancestor-or-self::ds:Reference |             " + "\n"
        + "      here()/ancestor::ds:Reference[1]) >           " + "\n"
        + " count(ancestor-or-self::ds:Reference)              " + "\n"
        + "  or                                                " + "\n"
        + " count(ancestor-or-self::node() |                   " + "\n"
        + "      id('notaries')) =                             " + "\n"
        + " count(ancestor-or-self::node())                    " + "\n");
       //J+
       transforms.addTransform(Transforms.TRANSFORM_XPATH,
                         xpathC.getElementPlusReturns());
       sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                 "http://www.w3.org/2000/09/xmldsig#Object");
    }
    */

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_BASE64_DECODE);
        sig.addDocument("#object-2", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    sig.addDocument("#manifest-1", null, Constants.ALGO_ID_DIGEST_SHA1, null,
            "http://www.w3.org/2000/09/xmldsig#Manifest");
    sig.addDocument("#signature-properties-1", null, Constants.ALGO_ID_DIGEST_SHA1, null,
            "http://www.w3.org/2000/09/xmldsig#SignatureProperties");

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        sig.addDocument("#xpointer(/)", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("#xpointer(/)", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        sig.addDocument("#object-3", null, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("#object-3", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        sig.addDocument("#xpointer(id('object-3'))", null, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("#xpointer(id('object-3'))", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        sig.addDocument("#manifest-reference-1", null, Constants.ALGO_ID_DIGEST_SHA1, "reference-1",
                "http://www.w3.org/2000/09/xmldsig#Reference");
    }

    {
        sig.addDocument("#reference-1", null, Constants.ALGO_ID_DIGEST_SHA1, "reference-2",
                "http://www.w3.org/2000/09/xmldsig#Reference");
    }

    {
        sig.addDocument("#reference-2", null, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Reference");
    }

    /*
     * Add KeyInfo and sign()
     */
    {
        Transforms retrievalTransforms = new Transforms(doc);
        XPathContainer xpathC = new XPathContainer(doc);

        xpathC.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);
        xpathC.setXPath("ancestor-or-self::ds:X509Data");
        retrievalTransforms.addTransform(Transforms.TRANSFORM_XPATH, xpathC.getElement());
        sig.getKeyInfo().add(new RetrievalMethod(doc, "#object-4", retrievalTransforms,
                "http://www.w3.org/2000/09/xmldsig#X509Data"));

        /*
        X509Data x509data = new X509Data(doc);
                
        x509data.add(new XMLX509SubjectName(doc, cert));
        x509data.add(new XMLX509IssuerSerial(doc, cert));
        x509data.add(new XMLX509Certificate(doc, cert));
        sig.getKeyInfo().add(x509data);
        */

        System.out.println("Start signing");
        sig.sign(privateKey);
        System.out.println("Finished signing");
    }

    FileOutputStream f = new FileOutputStream(signatureFile);

    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();
    System.out.println("Wrote signature to " + BaseURI);

    SignedInfo s = sig.getSignedInfo();
    for (int i = 0; i < s.getLength(); i++) {
        Reference r = s.item(i);
        String fn = "merlin16_" + i + ".html";
        System.out.println("Wrote Reference " + i + " to file " + fn);
        JavaUtils.writeBytesToFilename(fn, r.getHTMLRepresentation().getBytes());
    }

    /*
    for (int i=0; i<s.getSignedContentLength(); i++) {
       if (s.item(i).getType().equals(Reference.MANIFEST_URI)) {
    System.out.println("################ Signed Manifest " + i + " ################");
       } else {
    System.out.println("################ Signed Resource " + i + " ################");
       }
       System.out.println(new String(s.getSignedContentItem(i)));
       System.out.println();
    }
    */
}