Example usage for org.w3c.dom Document createElementNS

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

Introduction

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

Prototype

public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;

Source Link

Document

Creates an element of the given qualified name and namespace URI.

Usage

From source file:com.microsoft.windowsazure.management.compute.DeploymentOperationsImpl.java

/**
* The Delete Role Instances operation deletes a role instance from a
* deployment in a cloud service.  (see//from  ww w.  jav  a 2s . c  om
* http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for
* more information)
*
* @param serviceName Required. The name of the cloud service.
* @param deploymentSlot Required. The name of the deployment slot.
* @param parameters Required. The parameters to delete the role.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse beginDeletingRoleInstanceByBeploymentSlot(String serviceName, String deploymentSlot,
        DeploymentDeleteRoleInstanceParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentSlot == null) {
        throw new NullPointerException("deploymentSlot");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("serviceName", serviceName);
        tracingParameters.put("deploymentSlot", deploymentSlot);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginDeletingRoleInstanceByBeploymentSlotAsync",
                tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deploymentslots/";
    url = url + URLEncoder.encode(deploymentSlot, "UTF-8");
    url = url + "/roleinstances/";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("comp=delete");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPost httpRequest = new HttpPost(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2015-04-01");

    // Serialize Request
    String requestContent = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

    if (parameters.getName() != null) {
        if (parameters.getName() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getName()).isInitialized()) {
            Element roleInstancesSequenceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "RoleInstances");
            for (String roleInstancesItem : parameters.getName()) {
                Element roleInstancesItemElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                roleInstancesItemElement.appendChild(requestDoc.createTextNode(roleInstancesItem));
                roleInstancesSequenceElement.appendChild(roleInstancesItemElement);
            }
            requestDoc.appendChild(roleInstancesSequenceElement);
        }
    }

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_ACCEPTED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:com.microsoft.windowsazure.management.compute.DeploymentOperationsImpl.java

/**
* The Delete Role Instances operation deletes a role instance from a
* deployment in a cloud service.  (see/*from   w  w w.  j  ava2s. c  om*/
* http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for
* more information)
*
* @param serviceName Required. The name of the cloud service.
* @param deploymentName Required. The name of the deployment.
* @param parameters Required. The parameters to delete the role.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse beginDeletingRoleInstanceByDeploymentName(String serviceName, String deploymentName,
        DeploymentDeleteRoleInstanceParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("serviceName", serviceName);
        tracingParameters.put("deploymentName", deploymentName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginDeletingRoleInstanceByDeploymentNameAsync",
                tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/roleinstances/";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("comp=delete");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPost httpRequest = new HttpPost(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2015-04-01");

    // Serialize Request
    String requestContent = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

    if (parameters.getName() != null) {
        if (parameters.getName() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getName()).isInitialized()) {
            Element roleInstancesSequenceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "RoleInstances");
            for (String roleInstancesItem : parameters.getName()) {
                Element roleInstancesItemElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                roleInstancesItemElement.appendChild(requestDoc.createTextNode(roleInstancesItem));
                roleInstancesSequenceElement.appendChild(roleInstancesItemElement);
            }
            requestDoc.appendChild(roleInstancesSequenceElement);
        }
    }

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_ACCEPTED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

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

public Resolution generateSld() throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from w ww  . j  ava 2  s  .c  om
    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:nl.b3p.viewer.stripes.SldActionBean.java

private void addFilterToExistingSld() throws Exception {
    Filter f = CQL.toFilter(filter);

    f = (Filter) f.accept(new ChangeMatchCase(false), null);

    if (featureTypeName == null) {
        featureTypeName = layer;/* w  ww . ja  va  2 s .co m*/
    }
    FeatureTypeConstraint ftc = sldFactory.createFeatureTypeConstraint(featureTypeName, f, new Extent[] {});

    if (newSld == null) {

        SLDTransformer sldTransformer = new SLDTransformer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        sldTransformer.transform(ftc, bos);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document sldXmlDoc = db.parse(new ByteArrayInputStream(sldXml));

        Document ftcDoc = db.parse(new ByteArrayInputStream(bos.toByteArray()));

        String sldVersion = sldXmlDoc.getDocumentElement().getAttribute("version");
        if ("1.1.0".equals(sldVersion)) {
            // replace sld:FeatureTypeName element generated by GeoTools
            // by se:FeatureTypeName
            NodeList sldFTNs = ftcDoc.getElementsByTagNameNS(NS_SLD, "FeatureTypeName");
            if (sldFTNs.getLength() == 1) {
                Node sldFTN = sldFTNs.item(0);
                Node seFTN = ftcDoc.createElementNS(NS_SE, "FeatureTypeName");
                seFTN.setTextContent(sldFTN.getTextContent());
                sldFTN.getParentNode().replaceChild(seFTN, sldFTN);
            }
        }

        // Ignore namespaces to tackle both SLD 1.0.0 and SLD 1.1.0
        // Add constraint to all NamedLayers, not only to the layer specified
        // in layers parameter

        NodeList namedLayers = sldXmlDoc.getElementsByTagNameNS(NS_SLD, "NamedLayer");
        for (int i = 0; i < namedLayers.getLength(); i++) {
            Node namedLayer = namedLayers.item(i);

            // Search where to insert the FeatureTypeConstraint from our ftcDoc

            // Insert LayerFeatureConstraints after sld:Name, se:Name or se:Description
            // and before sld:NamedStyle or sld:UserStyle so search backwards.
            // If we find an existing LayerFeatureConstraints, use that
            NodeList childs = namedLayer.getChildNodes();
            Node insertBefore = null;
            Node layerFeatureConstraints = null;
            int j = childs.getLength() - 1;
            do {
                Node child = childs.item(j);

                if ("LayerFeatureConstraints".equals(child.getLocalName())) {
                    layerFeatureConstraints = child;
                    break;
                }
                if ("Description".equals(child.getLocalName()) || "Name".equals(child.getLocalName())) {
                    break;
                }
                insertBefore = child;
                j--;
            } while (j >= 0);
            Node featureTypeConstraint = sldXmlDoc.adoptNode(ftcDoc.getDocumentElement().cloneNode(true));
            if (layerFeatureConstraints == null) {
                layerFeatureConstraints = sldXmlDoc.createElementNS(NS_SLD, "LayerFeatureConstraints");
                layerFeatureConstraints.appendChild(featureTypeConstraint);
                namedLayer.insertBefore(layerFeatureConstraints, insertBefore);
            } else {
                layerFeatureConstraints.appendChild(featureTypeConstraint);
            }
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        DOMSource source = new DOMSource(sldXmlDoc);
        bos = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(bos);
        t.transform(source, result);
        sldXml = bos.toByteArray();
    }
}

From source file:org.akaza.openclinica.ws.EventEndpoint.java

/**
 * Create Success Response/*  ww  w  .j  a  v a 2 s  . c  o m*/
 * 
 * @param confirmation
 * @return
 * @throws Exception
 */
private Element mapSuccessConfirmation(HashMap<String, String> confirmation) throws Exception {
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
    Document document = docBuilder.newDocument();

    Element responseElement = document.createElementNS(NAMESPACE_URI_V1, "scheduleResponse");
    Element resultElement = document.createElementNS(NAMESPACE_URI_V1, "result");
    Element eventDefinitionOID = document.createElementNS(NAMESPACE_URI_V1, "eventDefinitionOID");
    Element studySubjectOID = document.createElementNS(NAMESPACE_URI_V1, "studySubjectOID");
    Element eventOrdinal = document.createElementNS(NAMESPACE_URI_V1, "studyEventOrdinal");
    resultElement.setTextContent(messages.getMessage("eventEndpoint.success", null, "Success", locale));
    eventDefinitionOID.setTextContent(confirmation.get("eventDefinitionOID"));
    studySubjectOID.setTextContent(confirmation.get("studySubjectOID"));
    eventOrdinal.setTextContent(confirmation.get("studyEventOrdinal"));
    responseElement.appendChild(resultElement);
    responseElement.appendChild(eventDefinitionOID);
    responseElement.appendChild(studySubjectOID);
    responseElement.appendChild(eventOrdinal);
    return responseElement;

}

From source file:org.akaza.openclinica.ws.EventEndpoint.java

/**
 * Create Error Response/*from ww w  . j av  a  2  s  .c o m*/
 * 
 * @param confirmation
 * @return
 * @throws Exception
 */
private Element mapFailConfirmation(Errors errors) throws Exception {
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
    Document document = docBuilder.newDocument();

    Element responseElement = document.createElementNS(NAMESPACE_URI_V1, "scheduleResponse");
    Element resultElement = document.createElementNS(NAMESPACE_URI_V1, "result");
    resultElement.setTextContent(messages.getMessage("eventEndpoint.fail", null, "Fail", locale));
    responseElement.appendChild(resultElement);
    for (ObjectError error : errors.getAllErrors()) {
        Element errorElement = document.createElementNS(NAMESPACE_URI_V1, "error");
        String theMessage = messages.getMessage(error.getCode(), error.getArguments(), locale);
        errorElement.setTextContent(theMessage);
        responseElement.appendChild(errorElement);
    }
    return responseElement;

}

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);//from w  w w  . j  ava2s  .  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.repo.template.XSLTProcessor.java

/**
 * Adds a script element to the xsl which makes static methods on this object available to the xsl tempalte.
 * /*www.  j a v a2s  .  co m*/
 * @param xslTemplate
 *            the xsl template
 */
protected List<String> addScripts(final XSLTemplateModel xsltModel, final Document xslTemplate) {
    final Map<QName, List<Map.Entry<QName, Object>>> methods = new HashMap<QName, List<Map.Entry<QName, Object>>>();
    for (final Map.Entry<QName, Object> entry : xsltModel.entrySet()) {
        if (entry.getValue() instanceof TemplateProcessorMethod) {
            final String prefix = QName.splitPrefixedQName(entry.getKey().toPrefixString())[0];
            final QName qn = QName.createQName(entry.getKey().getNamespaceURI(), prefix);
            if (!methods.containsKey(qn)) {
                methods.put(qn, new LinkedList<Map.Entry<QName, Object>>());
            }
            methods.get(qn).add(entry);
        }
    }

    final Element docEl = xslTemplate.getDocumentElement();
    final String XALAN_NS = Constants.S_BUILTIN_EXTENSIONS_URL;
    final String XALAN_NS_PREFIX = "xalan";
    docEl.setAttribute("xmlns:" + XALAN_NS_PREFIX, XALAN_NS);

    final Set<String> excludePrefixes = new HashSet<String>();
    if (docEl.hasAttribute("exclude-result-prefixes")) {
        excludePrefixes.addAll(Arrays.asList(docEl.getAttribute("exclude-result-prefixes").split(" ")));
    }
    excludePrefixes.add(XALAN_NS_PREFIX);

    final List<String> result = new LinkedList<String>();
    for (QName ns : methods.keySet()) {
        final String prefix = ns.getLocalName();
        docEl.setAttribute("xmlns:" + prefix, ns.getNamespaceURI());
        excludePrefixes.add(prefix);

        final Element compEl = xslTemplate.createElementNS(XALAN_NS, XALAN_NS_PREFIX + ":component");
        compEl.setAttribute("prefix", prefix);
        docEl.appendChild(compEl);
        String functionNames = null;
        final Element scriptEl = xslTemplate.createElementNS(XALAN_NS, XALAN_NS_PREFIX + ":script");
        scriptEl.setAttribute("lang", "javascript");
        final StringBuilder js = new StringBuilder("var _xsltp_invoke = java.lang.Class.forName('"
                + XSLTProcessorMethodInvoker.class.getName() + "').newInstance();\n"
                + "function _xsltp_to_java_array(js_array) {\n"
                + "var java_array = java.lang.reflect.Array.newInstance(java.lang.Object, js_array.length);\n"
                + "for (var i = 0; i < js_array.length; i++) { java_array[i] = js_array[i]; }\n"
                + "return java_array; }\n");
        for (final Map.Entry<QName, Object> entry : methods.get(ns)) {
            if (functionNames == null) {
                functionNames = entry.getKey().getLocalName();
            } else {
                functionNames += " " + entry.getKey().getLocalName();
            }
            final String id = entry.getKey().getLocalName() + entry.getValue().hashCode();
            js.append("function " + entry.getKey().getLocalName() + "() { return _xsltp_invoke.invokeMethod('"
                    + id + "', _xsltp_to_java_array(arguments)); }\n");
            XSLTProcessorMethodInvoker.addMethod(id, (TemplateProcessorMethod) entry.getValue());
            result.add(id);
        }
        log.debug("generated JavaScript bindings:\n" + js);
        scriptEl.appendChild(xslTemplate.createTextNode(js.toString()));
        compEl.setAttribute("functions", functionNames);
        compEl.appendChild(scriptEl);
    }
    docEl.setAttribute("exclude-result-prefixes",
            StringUtils.join(excludePrefixes.toArray(new String[excludePrefixes.size()]), " "));
    return result;
}

From source file:org.alfresco.repo.template.XSLTProcessor.java

/**
 * Adds the specified parameters to the xsl template as variables within the alfresco namespace.
 * /* w  w  w  .j  a va2  s  . c  o  m*/
 * @param xsltModel
 *            the variables to place within the xsl template
 * @param xslTemplate
 *            the xsl template
 */
protected void addParameters(final XSLTemplateModel xsltModel, final Document xslTemplate) {
    final Element docEl = xslTemplate.getDocumentElement();
    final String XSL_NS = docEl.getNamespaceURI();
    final String XSL_NS_PREFIX = docEl.getPrefix();

    for (Map.Entry<QName, Object> e : xsltModel.entrySet()) {
        if (ROOT_NAMESPACE.equals(e.getKey())) {
            continue;
        }
        final Element el = xslTemplate.createElementNS(XSL_NS, XSL_NS_PREFIX + ":variable");
        el.setAttribute("name", e.getKey().toPrefixString());
        final Object o = e.getValue();
        if (o instanceof String || o instanceof Number || o instanceof Boolean) {
            el.appendChild(xslTemplate.createTextNode(o.toString()));
            // ALF-15413. Add the variables at the end of the list of children
            docEl.insertBefore(el, null);
        }
    }
}

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

/**
  * Builds the model to pass to the rendering engine.
  *//*from ww w .j a v  a  2  s.  c om*/
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;
}