Example usage for org.w3c.dom Element setAttributeNS

List of usage examples for org.w3c.dom Element setAttributeNS

Introduction

In this page you can find the example usage for org.w3c.dom Element setAttributeNS.

Prototype

public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException;

Source Link

Document

Adds a new attribute.

Usage

From source file:it.imtech.metadata.MetaUtility.java

/**
 * Metodo adibito all'esportazione dei metadati su oggetto Document a
 * partire dai valori dell'interfaccia//from   ww w  . jav  a 2s.com
 *
 * @param pid PID del libro durante upload
 * @param pagenum Numero pagina corrente di esportazione
 * @param objectDefaultValues Valori di default durante upload
 * @return Oggetto xml contenente i metadati inseriti nei campi
 * dell'interfaccia
 * @throws Exception
 */
public Document create_uwmetadata(String pid, int pagenum, HashMap<String, String> objectDefaultValues,
        String collTitle, String panelname) throws Exception {
    String xmlFile = "";

    if (objectDefaultValues != null) {
        this.objectDefaultValues = objectDefaultValues;
    }

    StreamResult result = new StreamResult(new StringWriter());

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // set the factory to be namespace aware
    factory.setNamespaceAware(true);

    // create the xml document builder object and get the DOMImplementation object
    DocumentBuilder builder = factory.newDocumentBuilder();
    DOMImplementation domImpl = builder.getDOMImplementation();
    Document xmlDoc = domImpl.createDocument("http://phaidra.univie.ac.at/XML/metadata/V1.0", "ns0:uwmetadata",
            null);

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

        // get the root element
        Element rootElement = xmlDoc.getDocumentElement();

        //Add namespaces in XML Root
        for (Map.Entry<String, String> field : metadata_namespaces.entrySet()) {
            rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + field.getKey().toString(),
                    field.getValue().toString());
        }
        create_uwmetadata_recursive(xmlDoc, rootElement, BookImporter.getInstance().getMetadata(),
                this.objectDefaultValues, pagenum, collTitle, panelname);
    } catch (TransformerConfigurationException e) {
    } catch (Exception e) {
        throw new Exception(e.getMessage());
    }

    return xmlDoc;
}

From source file:de.betterform.xml.xforms.model.submission.Submission.java

private void submitReplaceEmbedXForms(Map response) throws XFormsException {
    // check for targetid
    String targetid = getXFormsAttribute(TARGETID_ATTRIBUTE);
    String resource = getResource();
    Map eventInfo = new HashMap();
    String error = null;/*  w ww.  j a  v a  2 s.com*/
    if (targetid == null) {
        error = "targetId";
    } else if (resource == null) {
        error = "resource";
    }

    if (error != null && error.length() > 0) {
        eventInfo.put(XFormsConstants.ERROR_TYPE, "no " + error + "defined for submission resource");
        this.container.dispatch(this.target, XFormsEventNames.SUBMIT_ERROR, eventInfo);
        return;
    }

    Document result = getResponseAsDocument(response);
    Node embedElement = result.getDocumentElement();

    if (resource.indexOf("#") != -1) {
        // detected a fragment so extract that from our result Document

        String fragmentid = resource.substring(resource.indexOf("#") + 1);
        if (fragmentid.indexOf("?") != -1) {
            fragmentid = fragmentid.substring(0, fragmentid.indexOf("?"));
        }
        embedElement = DOMUtil.getById(result, fragmentid);
    }

    Element embeddedNode = null;
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("get target element for id: " + targetid);
    }
    Element targetElem = this.container.getElementById(targetid);
    DOMResult domResult = new DOMResult();
    //Test if targetElem exist.
    if (targetElem != null) {
        // destroy existing embedded form within targetNode
        if (targetElem.hasChildNodes()) {
            // destroyembeddedModels(targetElem);
            Initializer.disposeUIElements(targetElem);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("destroyed any existing ui elements for target elem");
        }

        // import referenced embedded form into host document
        embeddedNode = (Element) this.container.getDocument().importNode(embedElement, true);

        //import namespaces
        NamespaceResolver.applyNamespaces(targetElem.getOwnerDocument().getDocumentElement(),
                (Element) embeddedNode);

        // keep original targetElem id within hostdoc
        embeddedNode.setAttributeNS(null, "id", targetElem.getAttributeNS(null, "id"));
        //copy all Attributes that might have been on original mountPoint to embedded node
        DOMUtil.copyAttributes(targetElem, embeddedNode, null);
        targetElem.getParentNode().replaceChild(embeddedNode, targetElem);
        //create model for it
        Initializer.initializeUIElements(model, embeddedNode, null, null);

        try {
            CachingTransformerService transformerService = new CachingTransformerService(
                    new ClasspathResourceResolver("unused"));
            // TODO: MUST BE GENERIFIED USING USERAGENT MECHANISM
            //TODO: check exploded mode!!!
            String path = getClass().getResource("/META-INF/resources/xslt/xhtml.xsl").getPath();

            //String xslFilePath = "file:" + path;
            transformerService.getTransformer(new URI(path));
            XSLTGenerator generator = new XSLTGenerator();
            generator.setTransformerService(transformerService);
            generator.setStylesheetURI(new URI(path));
            generator.setInput(embeddedNode);
            generator.setOutput(domResult);
            generator.generate();
        } catch (TransformerException e) {
            throw new XFormsException(
                    "Transformation error while executing 'Submission.submitReplaceEmbedXForms'", e);
        } catch (URISyntaxException e) {
            throw new XFormsException(
                    "Malformed URI throwed URISyntaxException in 'Submission.submitReplaceEmbedXForms'", e);
        }
    }

    // Map eventInfo = constructEventInfo(response);
    OutputStream outputStream = new ByteArrayOutputStream();
    try {
        DOMUtil.prettyPrintDOM(domResult.getNode(), outputStream);
    } catch (TransformerException e) {
        throw new XFormsException(e);
    }

    eventInfo.put(EMBEDNODE, outputStream.toString());
    eventInfo.put("embedTarget", targetid);
    eventInfo.put("embedXForms", true);

    // dispatch xforms-submit-done
    this.container.dispatch(this.target, XFormsEventNames.SUBMIT_DONE, eventInfo);

}

From source file:de.betterform.connector.SchemaValidator.java

/**
 * validate the instance according to the schema specified on the model
 *
 * @return false if the instance is not valid
 */// w w w.  j  a  v  a2  s  .co m
public boolean validateSchema(Model model, Node instance) throws XFormsException {
    boolean valid = true;
    String message;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("SchemaValidator.validateSchema: validating instance");

    //needed if we want to load schemas from Model + set it as "schemaLocation" attribute
    String schemas = model.getElement().getAttributeNS(NamespaceConstants.XFORMS_NS, "schema");
    if (schemas != null && !schemas.equals("")) {
        //          valid=false;

        //add schemas to element
        //shouldn't it be done on a copy of the doc ?
        Element el = null;
        if (instance.getNodeType() == Node.ELEMENT_NODE)
            el = (Element) instance;
        else if (instance.getNodeType() == Node.DOCUMENT_NODE)
            el = ((Document) instance).getDocumentElement();
        else {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("instance node type is: " + instance.getNodeType());
        }

        String prefix = NamespaceResolver.getPrefix(el, NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
        //test if with targetNamespace or not
        //if more than one schema : namespaces are mandatory ! (optional only for 1)
        StringTokenizer tokenizer = new StringTokenizer(schemas, " ", false);
        String schemaLocations = null;
        String noNamespaceSchemaLocation = null;
        while (tokenizer.hasMoreElements()) {
            String token = (String) tokenizer.nextElement();
            //check that it is an URL
            URI uri = null;
            try {
                uri = new java.net.URI(token);
            } catch (java.net.URISyntaxException ex) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(token + " is not an URI");
            }

            if (uri != null) {
                String ns;
                try {
                    ns = this.getSchemaNamespace(uri);

                    if (ns != null && !ns.equals("")) {
                        if (schemaLocations == null)
                            schemaLocations = ns + " " + token;
                        else
                            schemaLocations = schemaLocations + " " + ns + " " + token;

                        ///add the namespace declaration if it is not on the instance?
                        //TODO: how to know with which prefix ?
                        String nsPrefix = NamespaceResolver.getPrefix(el, ns);
                        if (nsPrefix == null) { //namespace not declared !
                            LOGGER.warn("SchemaValidator: targetNamespace " + ns + " of schema " + token
                                    + " is not declared in instance: declaring it as default...");
                            el.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX, ns);
                        }
                    } else if (noNamespaceSchemaLocation == null)
                        noNamespaceSchemaLocation = token;
                    else { //we have more than one schema without namespace
                        LOGGER.warn("SchemaValidator: There is more than one schema without namespace !");
                    }
                } catch (Exception ex) {
                    LOGGER.warn(
                            "Exception while trying to load schema: " + uri.toString() + ": " + ex.getMessage(),
                            ex);
                    //in case there was an exception: do nothing, do not set the schema
                }
            }
        }
        //write schemaLocations found
        if (schemaLocations != null && !schemaLocations.equals(""))
            el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation",
                    schemaLocations);
        if (noNamespaceSchemaLocation != null)
            el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":noNamespaceSchemaLocation",
                    noNamespaceSchemaLocation);

        //save and parse the doc
        ValidationErrorHandler handler = null;
        File f;
        try {
            //save document
            f = File.createTempFile("instance", ".xml");
            f.deleteOnExit();
            TransformerFactory trFact = TransformerFactory.newInstance();
            Transformer trans = trFact.newTransformer();
            DOMSource source = new DOMSource(el);
            StreamResult result = new StreamResult(f);
            trans.transform(source, result);
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Validator.validateSchema: file temporarily saved in " + f.getAbsolutePath());

            //parse it with error handler to validate it
            handler = new ValidationErrorHandler();
            SAXParserFactory parserFact = SAXParserFactory.newInstance();
            parserFact.setValidating(true);
            parserFact.setNamespaceAware(true);
            SAXParser parser = parserFact.newSAXParser();
            XMLReader reader = parser.getXMLReader();

            //validation activated
            reader.setFeature("http://xml.org/sax/features/validation", true);
            //schema validation activated
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            //used only to validate the schema, not the instance
            //reader.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true);
            //validate only if there is a grammar
            reader.setFeature("http://apache.org/xml/features/validation/dynamic", true);

            parser.parse(f, handler);
        } catch (Exception ex) {
            LOGGER.warn("Validator.validateSchema: Exception in XMLSchema validation: " + ex.getMessage(), ex);
            //throw new XFormsException("XMLSchema validation failed. "+message);
        }

        //if no exception
        if (handler != null && handler.isValid())
            valid = true;
        else {
            message = handler.getMessage();
            //TODO: find a way to get the error message displayed
            throw new XFormsException("XMLSchema validation failed. " + message);
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Validator.validateSchema: result=" + valid);

    }

    return valid;
}

From source file:br.org.indt.mobisus.common.ResultWriter.java

public void write() throws ParserConfigurationException, Exception {
    logger.info("creatint result file in " + resultPath);
    Document xmldoc = null;/*w  w w .ja  v a 2 s  .  com*/
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    DOMImplementation impl = builder.getDOMImplementation();
    Element answerElement = null;
    Element categoryElement = null;
    Element text = null;
    Element title = null;
    Element lat = null;
    Element lon = null;
    Element other = null;
    Node titleText = null;
    Node nodeStr = null;

    xmldoc = impl.createDocument(null, "result", null);

    Element root = xmldoc.getDocumentElement();

    root.setAttribute("r_id", result.getResultId());
    root.setAttribute("s_id", result.getSurveyId());
    root.setAttribute("u_id", result.getUserId());
    root.setAttribute("time", result.getTime());

    if (result.getLatitude() != null) {
        lat = xmldoc.createElementNS(null, "latitude");
        titleText = xmldoc.createTextNode(result.getLatitude());
        lat.appendChild(titleText);
        root.appendChild(lat);
    }

    if (result.getLongitude() != null) {
        lon = xmldoc.createElementNS(null, "longitude");
        titleText = xmldoc.createTextNode(result.getLongitude());
        lon.appendChild(titleText);
        root.appendChild(lon);
    }

    title = xmldoc.createElementNS(null, "title");
    titleText = xmldoc.createTextNode("");
    title.appendChild(titleText);
    root.appendChild(title);

    TreeMap<Integer, Category> categories = survey.getCategories();
    Iterator<Category> iteratorCat = categories.values().iterator();
    while (iteratorCat.hasNext()) {
        Category category = iteratorCat.next();
        categoryElement = xmldoc.createElementNS(null, "category");
        categoryElement.setAttribute("name", category.getName());
        categoryElement.setAttribute("id", String.valueOf(category.getId()));
        root.appendChild(categoryElement);
        Integer categoryId = new Integer(category.getId());
        Vector<Field> questions = category.getFields();
        for (Field question : questions) {
            answerElement = xmldoc.createElementNS(null, "answer");
            answerElement.setAttributeNS(null, "type", question.getXmlType());
            answerElement.setAttributeNS(null, "id", String.valueOf(question.getId()));
            answerElement.setAttributeNS(null, "visited", "false");
            Field answer = result.getCategories().get(categoryId).getFieldById(question.getId());

            if (question.getFieldType() == FieldType.CHOICE) {
                ArrayList<Item> items = answer.getChoice().getItems();
                for (Item item : items) {
                    if (item.getOtr() == null || item.getOtr().equals("0")) {
                        nodeStr = xmldoc.createTextNode("" + item.getIndex());
                        text = xmldoc.createElementNS(null, question.getElementName());
                        text.appendChild(nodeStr);
                        answerElement.appendChild(text);
                        categoryElement.appendChild(answerElement);
                    } else {
                        nodeStr = xmldoc.createTextNode(item.getValue());
                        other = xmldoc.createElementNS(null, "other");
                        other.setAttributeNS(null, "index", "" + item.getIndex());
                        other.appendChild(nodeStr);
                        answerElement.appendChild(other);
                        categoryElement.appendChild(answerElement);
                    }
                }
            } else {
                nodeStr = xmldoc.createTextNode((answer.getValue() == null ? "" : answer.getValue()));
                text = xmldoc.createElementNS(null, question.getElementName());
                text.appendChild(nodeStr);
                answerElement.appendChild(text);
                categoryElement.appendChild(answerElement);
            }

            if ((question.getCategoryId() == survey.getDisplayCategory())
                    && (question.getId() == survey.getDisplayQuestion())) {
                (root.getElementsByTagName("title")).item(0).setTextContent(answer.getValue());
            }

        }

    }

    ResultDeploy resultDeploy = new ResultDeploy(xmldoc, getNextResultFile());
    resultDeploy.deploy(resultPath);
}

From source file:com.amalto.workbench.utils.Util.java

/**
 * Returns a namespaced root element of a document Useful to create a namespace holder element
 * /*from  ww  w . ja v  a 2s.c om*/
 * @param namespace
 * @return the root Element
 */
public static Element getRootElement(String elementName, String namespace, String prefix) throws Exception {
    Element rootNS = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        DOMImplementation impl = builder.getDOMImplementation();
        Document namespaceHolder = impl.createDocument(namespace,
                (prefix == null ? "" : prefix + ":") + elementName, null);//$NON-NLS-1$//$NON-NLS-2$
        rootNS = namespaceHolder.getDocumentElement();
        rootNS.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + prefix, namespace);//$NON-NLS-1$//$NON-NLS-2$
    } catch (Exception e) {
        String err = Messages.Util_11 + e.getLocalizedMessage();
        throw new Exception(err);
    }
    return rootNS;
}

From source file:com.codename1.android.AndroidLayoutImporter.java

private List<Element> getSelectorElementsForDrawable(String resourceName) throws SAXException, IOException {
    File drawable = findDrawableResource(resourceName);
    if (drawable != null && drawable.getName().endsWith(".xml")) {
        try {/* w ww . j a  v a2  s.c  o m*/
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document includedDOM = builder.parse(drawable);
            Element root = includedDOM.getDocumentElement();
            if (root.getTagName().equals("selector")) {
                NodeList items = root.getElementsByTagName("item");
                int len = items.getLength();
                List<Element> out = new ArrayList<Element>();
                for (int i = 0; i < len; i++) {
                    out.add((Element) items.item(i));

                }
                return out;
            }
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(AndroidLayoutImporter.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else if (drawable != null
            && (drawable.getName().endsWith(".png") || drawable.getName().endsWith(".jpg"))) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document includedDOM = builder.newDocument();

            Element root = includedDOM.createElement("selector");
            Element item = includedDOM.createElement("item");
            item.setAttributeNS(NS_ANDROID, "drawable", resourceName);
            root.appendChild(item);
            includedDOM.appendChild(root);
            List<Element> out = new ArrayList<Element>();
            out.add(item);
            return out;
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(AndroidLayoutImporter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return null;
}

From source file:net.sourceforge.pmd.RuleSetWriter.java

private Element createRuleSetElement(RuleSet ruleSet) {
    Element ruleSetElement = document.createElementNS(RULESET_2_0_0_NS_URI, "ruleset");
    ruleSetElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    ruleSetElement.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation",
            RULESET_2_0_0_NS_URI + " https://pmd.sourceforge.io/ruleset_2_0_0.xsd");
    ruleSetElement.setAttribute("name", ruleSet.getName());

    Element descriptionElement = createDescriptionElement(ruleSet.getDescription());
    ruleSetElement.appendChild(descriptionElement);

    for (String excludePattern : ruleSet.getExcludePatterns()) {
        Element excludePatternElement = createExcludePatternElement(excludePattern);
        ruleSetElement.appendChild(excludePatternElement);
    }/*from w  w w. java2 s .c  om*/
    for (String includePattern : ruleSet.getIncludePatterns()) {
        Element includePatternElement = createIncludePatternElement(includePattern);
        ruleSetElement.appendChild(includePatternElement);
    }
    for (Rule rule : ruleSet.getRules()) {
        Element ruleElement = createRuleElement(rule);
        if (ruleElement != null) {
            ruleSetElement.appendChild(ruleElement);
        }
    }

    return ruleSetElement;
}

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

public Resolution generateSld() throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//w w w.  j  av  a 2  s .co 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.alfresco.repo.rendition.executer.XSLTRenderingEngine.java

@SuppressWarnings({ "serial", "unchecked" })
protected Object buildModel(RenderingContext context) {
    Map<String, Serializable> suppliedParams = context.getCheckedParam(PARAM_MODEL, Map.class);
    final NodeRef sourceNode = context.getSourceNode();
    final NodeRef parentNode = nodeService.getPrimaryParent(context.getSourceNode()).getParentRef();
    final String sourcePath = getPath(sourceNode);
    final String parentPath = getPath(parentNode);

    XSLTemplateModel model = new XSLTemplateModel();

    // add simple scalar parameters
    model.put(QName.createQName(NamespaceService.ALFRESCO_URI, "date"), new Date());

    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "source_file_name", namespacePrefixResolver),
            nodeService.getProperty(context.getSourceNode(), ContentModel.PROP_NAME));
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "source_path", namespacePrefixResolver),
            sourcePath);// ww w . j  a va2s . co m
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parent_path", namespacePrefixResolver),
            parentPath);

    // add methods
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "encodeQuotes", namespacePrefixResolver),
            new TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) throws IOException, SAXException {
                    if (arguments.length != 1) {
                        throw new IllegalArgumentException(
                                "expected 1 argument to encodeQuotes.  got " + arguments.length);

                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }
                    String text = (String) arguments[0];

                    if (log.isDebugEnabled()) {
                        log.debug("tpm_encodeQuotes('" + text + "'), parentPath = " + parentPath);
                    }

                    final String result = xsltFunctions.encodeQuotes(text);
                    return result;
                }
            });

    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parseXMLDocument", namespacePrefixResolver),
            new TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) throws IOException, SAXException {
                    if (arguments.length != 1) {
                        throw new IllegalArgumentException(
                                "expected 1 argument to parseXMLDocument.  got " + arguments.length);

                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }
                    String path = (String) arguments[0];

                    if (log.isDebugEnabled()) {
                        log.debug("parseXMLDocument('" + path + "'), parentPath = " + parentPath);
                    }

                    Document d = null;
                    try {
                        d = xsltFunctions.parseXMLDocument(parentNode, path);
                    } catch (Exception ex) {
                        log.warn("Received an exception from parseXMLDocument()", ex);
                    }
                    return d == null ? null : d.getDocumentElement();
                }
            });
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parseXMLDocuments", namespacePrefixResolver),
            new TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) throws IOException, SAXException {
                    if (arguments.length > 2) {
                        throw new IllegalArgumentException("expected one or two arguments to "
                                + "parseXMLDocuments.  got " + arguments.length);
                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }

                    if (arguments.length == 2 && !(arguments[1] instanceof String)) {
                        throw new ClassCastException("expected arguments[1] to be a " + String.class.getName()
                                + ".  got a " + arguments[1].getClass().getName() + ".");
                    }

                    String path = arguments.length == 2 ? (String) arguments[1] : "";
                    final String typeName = (String) arguments[0];

                    if (log.isDebugEnabled()) {
                        log.debug("tpm_parseXMLDocuments('" + typeName + "','" + path + "'), parentPath = "
                                + parentPath);
                    }

                    final Map<String, Document> resultMap = xsltFunctions.parseXMLDocuments(typeName,
                            parentNode, path);

                    if (log.isDebugEnabled()) {
                        log.debug("received " + resultMap.size() + " documents in " + path + " with form name "
                                + typeName);
                    }

                    // create a root document for rooting all the results. we do this
                    // so that each document root element has a common parent node
                    // and so that xpath axes work properly
                    final Document rootNodeDocument = XMLUtil.newDocument();
                    final Element rootNodeDocumentEl = rootNodeDocument.createElementNS(
                            NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":file_list");
                    rootNodeDocumentEl.setAttribute("xmlns:" + NamespaceService.ALFRESCO_PREFIX,
                            NamespaceService.ALFRESCO_URI);
                    rootNodeDocument.appendChild(rootNodeDocumentEl);

                    final List<Node> result = new ArrayList<Node>(resultMap.size());
                    for (Map.Entry<String, Document> e : resultMap.entrySet()) {
                        final Element documentEl = e.getValue().getDocumentElement();
                        documentEl.setAttribute("xmlns:" + NamespaceService.ALFRESCO_PREFIX,
                                NamespaceService.ALFRESCO_URI);
                        documentEl.setAttributeNS(NamespaceService.ALFRESCO_URI,
                                NamespaceService.ALFRESCO_PREFIX + ":file_name", e.getKey());
                        final Node n = rootNodeDocument.importNode(documentEl, true);
                        rootNodeDocumentEl.appendChild(n);
                        result.add(n);
                    }
                    return result.toArray(new Node[result.size()]);
                }
            });

    if (suppliedParams != null) {
        for (Map.Entry<String, Serializable> suppliedParam : suppliedParams.entrySet()) {
            model.put(QName.createQName(suppliedParam.getKey()), suppliedParam.getValue());
        }
    }

    // add the xml document
    try {
        model.put(XSLTProcessor.ROOT_NAMESPACE, XMLUtil.parse(sourceNode, contentService));
    } catch (RuntimeException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RenditionServiceException("Failed to parse XML from source node.", ex);
    }
    return model;
}

From source file:org.alfresco.web.forms.RenderingEngineTemplateImpl.java

/**
  * Builds the model to pass to the rendering engine.
  *///from w  ww  .ja va2s.  c  o m
protected Map<QName, Object> buildModel(final FormInstanceData formInstanceData, final Rendition rendition)
        throws IOException, SAXException {
    final String formInstanceDataAvmPath = formInstanceData.getPath();
    final String renditionAvmPath = rendition.getPath();
    final String parentPath = AVMNodeConverter.SplitBase(formInstanceDataAvmPath)[0];
    final String sandboxUrl = AVMUtil.getPreviewURI(AVMUtil.getStoreName(formInstanceDataAvmPath));
    final String webappUrl = AVMUtil.buildWebappUrl(formInstanceDataAvmPath);
    final HashMap<QName, Object> model = new HashMap<QName, Object>();
    // add simple scalar parameters
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "date", namespacePrefixResolver), new Date());
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "avm_sandbox_url", namespacePrefixResolver),
            sandboxUrl);
    model.put(RenderingEngineTemplateImpl.PROP_RESOURCE_RESOLVER,
            new RenderingEngine.TemplateResourceResolver() {
                public InputStream resolve(final String name) {
                    final NodeService nodeService = RenderingEngineTemplateImpl.this.getServiceRegistry()
                            .getNodeService();
                    final NodeRef parentNodeRef = nodeService
                            .getPrimaryParent(RenderingEngineTemplateImpl.this.getNodeRef()).getParentRef();

                    if (logger.isDebugEnabled()) {
                        logger.debug("request to resolve resource " + name + " webapp url is " + webappUrl
                                + " and data dictionary workspace is " + parentNodeRef);
                    }

                    final NodeRef result = nodeService.getChildByName(parentNodeRef,
                            ContentModel.ASSOC_CONTAINS, name);
                    if (result != null) {
                        final ContentService contentService = RenderingEngineTemplateImpl.this
                                .getServiceRegistry().getContentService();
                        try {
                            if (logger.isDebugEnabled()) {
                                logger.debug("found " + name + " in data dictonary: " + result);
                            }

                            return contentService.getReader(result, ContentModel.PROP_CONTENT)
                                    .getContentInputStream();
                        } catch (Exception e) {
                            logger.warn(e);
                        }
                    }

                    if (name.startsWith(WEBSCRIPT_PREFIX)) {
                        try {
                            final FacesContext facesContext = FacesContext.getCurrentInstance();
                            final ExternalContext externalContext = facesContext.getExternalContext();
                            final HttpServletRequest request = (HttpServletRequest) externalContext
                                    .getRequest();

                            String decodedName = URLDecoder.decode(name.substring(WEBSCRIPT_PREFIX.length()));
                            String rewrittenName = decodedName;

                            if (decodedName.contains("${storeid}")) {
                                rewrittenName = rewrittenName.replace("${storeid}",
                                        AVMUtil.getStoreName(formInstanceDataAvmPath));
                            } else {
                                if (decodedName.contains("{storeid}")) {
                                    rewrittenName = rewrittenName.replace("{storeid}",
                                            AVMUtil.getStoreName(formInstanceDataAvmPath));
                                }
                            }

                            if (decodedName.contains("${ticket}")) {
                                AuthenticationService authenticationService = Repository
                                        .getServiceRegistry(facesContext).getAuthenticationService();
                                final String ticket = authenticationService.getCurrentTicket();
                                rewrittenName = rewrittenName.replace("${ticket}", ticket);
                            } else {
                                if (decodedName.contains("{ticket}")) {
                                    AuthenticationService authenticationService = Repository
                                            .getServiceRegistry(facesContext).getAuthenticationService();
                                    final String ticket = authenticationService.getCurrentTicket();
                                    rewrittenName = rewrittenName.replace("{ticket}", ticket);
                                }
                            }

                            final String webscriptURI = (request.getScheme() + "://" + request.getServerName()
                                    + ':' + request.getServerPort() + request.getContextPath() + "/wcservice/"
                                    + rewrittenName);

                            if (logger.isDebugEnabled()) {
                                logger.debug("loading webscript: " + webscriptURI);
                            }

                            final URI uri = new URI(webscriptURI);
                            return uri.toURL().openStream();
                        } catch (Exception e) {
                            logger.warn(e);
                        }
                    }

                    try {
                        final String[] path = (name.startsWith("/") ? name.substring(1) : name).split("/");
                        for (int i = 0; i < path.length; i++) {
                            path[i] = URLEncoder.encode(path[i]);
                        }

                        final URI uri = new URI(webappUrl + '/' + StringUtils.join(path, '/'));

                        if (logger.isDebugEnabled()) {
                            logger.debug("loading " + uri);
                        }

                        return uri.toURL().openStream();
                    } catch (Exception e) {
                        logger.warn(e);
                        return null;
                    }
                }
            });
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "form_instance_data_file_name",
            namespacePrefixResolver), AVMNodeConverter.SplitBase(formInstanceDataAvmPath)[1]);
    model.put(
            QName.createQName(NamespaceService.ALFRESCO_PREFIX, "rendition_file_name", namespacePrefixResolver),
            AVMNodeConverter.SplitBase(renditionAvmPath)[1]);
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parent_path", namespacePrefixResolver),
            parentPath);
    final FacesContext fc = FacesContext.getCurrentInstance();
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "request_context_path",
            namespacePrefixResolver), fc.getExternalContext().getRequestContextPath());

    // add methods
    final FormDataFunctions fdf = this.getFormDataFunctions();

    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "encodeQuotes", namespacePrefixResolver),
            new RenderingEngine.TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) throws IOException, SAXException {
                    if (arguments.length != 1) {
                        throw new IllegalArgumentException(
                                "expected 1 argument to encodeQuotes.  got " + arguments.length);

                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }
                    String text = (String) arguments[0];

                    if (logger.isDebugEnabled()) {
                        logger.debug("tpm_encodeQuotes('" + text + "'), parentPath = " + parentPath);
                    }

                    final String result = fdf.encodeQuotes(text);
                    return result;
                }
            });

    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parseXMLDocument", namespacePrefixResolver),
            new RenderingEngine.TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) throws IOException, SAXException {
                    if (arguments.length != 1) {
                        throw new IllegalArgumentException(
                                "expected 1 argument to parseXMLDocument.  got " + arguments.length);

                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }
                    String path = (String) arguments[0];
                    path = AVMUtil.buildPath(parentPath, path, AVMUtil.PathRelation.WEBAPP_RELATIVE);

                    if (logger.isDebugEnabled()) {
                        logger.debug("tpm_parseXMLDocument('" + path + "'), parentPath = " + parentPath);
                    }

                    final Document d = fdf.parseXMLDocument(path);
                    return d != null ? d.getDocumentElement() : null;
                }
            });
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parseXMLDocuments", namespacePrefixResolver),
            new RenderingEngine.TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) throws IOException, SAXException {
                    if (arguments.length > 2) {
                        throw new IllegalArgumentException("expected exactly one or two arguments to "
                                + "parseXMLDocuments.  got " + arguments.length);
                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }

                    if (arguments.length == 2 && !(arguments[1] instanceof String)) {
                        throw new ClassCastException("expected arguments[1] to be a " + String.class.getName()
                                + ".  got a " + arguments[1].getClass().getName() + ".");
                    }

                    String path = arguments.length == 2 ? (String) arguments[1] : "";
                    path = AVMUtil.buildPath(parentPath, path, AVMUtil.PathRelation.WEBAPP_RELATIVE);
                    final String formName = (String) arguments[0];

                    if (logger.isDebugEnabled()) {
                        logger.debug("tpm_parseXMLDocuments('" + formName + "','" + path + "'), parentPath = "
                                + parentPath);
                    }

                    final Map<String, Document> resultMap = fdf.parseXMLDocuments(formName, path);

                    if (logger.isDebugEnabled()) {
                        logger.debug("received " + resultMap.size() + " documents in " + path
                                + " with form name " + formName);
                    }

                    // create a root document for rooting all the results.  we do this
                    // so that each document root element has a common parent node
                    // and so that xpath axes work properly
                    final Document rootNodeDocument = XMLUtil.newDocument();
                    final Element rootNodeDocumentEl = rootNodeDocument.createElementNS(
                            NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":file_list");
                    rootNodeDocumentEl.setAttribute("xmlns:" + NamespaceService.ALFRESCO_PREFIX,
                            NamespaceService.ALFRESCO_URI);
                    rootNodeDocument.appendChild(rootNodeDocumentEl);

                    final List<Node> result = new ArrayList<Node>(resultMap.size());
                    for (Map.Entry<String, Document> e : resultMap.entrySet()) {
                        final Element documentEl = e.getValue().getDocumentElement();
                        documentEl.setAttribute("xmlns:" + NamespaceService.ALFRESCO_PREFIX,
                                NamespaceService.ALFRESCO_URI);
                        documentEl.setAttributeNS(NamespaceService.ALFRESCO_URI,
                                NamespaceService.ALFRESCO_PREFIX + ":file_name", e.getKey());
                        final Node n = rootNodeDocument.importNode(documentEl, true);
                        rootNodeDocumentEl.appendChild(n);
                        result.add(n);
                    }
                    return result.toArray(new Node[result.size()]);
                }
            });
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "_getAVMPath", namespacePrefixResolver),
            new RenderingEngine.TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) {
                    if (arguments.length != 1) {
                        throw new IllegalArgumentException(
                                "expected one argument to _getAVMPath.  got " + arguments.length);
                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }

                    final String path = (String) arguments[0];

                    if (logger.isDebugEnabled()) {
                        logger.debug("tpm_getAVMPAth('" + path + "'), parentPath = " + parentPath);
                    }

                    return AVMUtil.buildPath(parentPath, path, AVMUtil.PathRelation.WEBAPP_RELATIVE);
                }
            });

    // add the xml document
    model.put(RenderingEngine.ROOT_NAMESPACE, formInstanceData.getDocument());
    return model;
}