Example usage for org.dom4j.io XMLWriter write

List of usage examples for org.dom4j.io XMLWriter write

Introduction

In this page you can find the example usage for org.dom4j.io XMLWriter write.

Prototype

public void write(Object object) throws IOException 

Source Link

Document

Writes the given object which should be a String, a Node or a List of Nodes.

Usage

From source file:org.alfresco.module.vti.web.ws.VtiSoapResponse.java

License:Open Source License

/**
 * Write document to response//from w  ww  .j  ava2 s  .c  o m
 */
@Override
public void flushBuffer() throws IOException {
    try {
        XMLWriter output = new XMLWriter(getOutputStream());
        output.write(document);
    } catch (Exception e) {
        // ignore
    }

}

From source file:org.alfresco.repo.security.permissions.impl.model.PermissionModel.java

License:Open Source License

private InputStream processModelDocType(InputStream is, String dtdSchemaUrl)
        throws DocumentException, IOException {
    SAXReader reader = new SAXReader();
    // read document without validation
    Document doc = reader.read(is);
    DocumentType docType = doc.getDocType();
    if (docType != null) {
        // replace DOCTYPE setting the full path to the xsd
        docType.setSystemID(dtdSchemaUrl);
    } else {//from www. j  a  va 2 s  . co m
        // add the DOCTYPE
        docType = new DefaultDocumentType(doc.getRootElement().getName(), dtdSchemaUrl);
        doc.setDocType(docType);
    }

    ByteArrayOutputStream fos = new ByteArrayOutputStream();
    try {
        OutputFormat format = OutputFormat.createPrettyPrint(); // uses UTF-8
        XMLWriter writer = new XMLWriter(fos, format);
        writer.write(doc);
        writer.flush();
    } finally {
        fos.close();
    }

    return new ByteArrayInputStream(fos.toByteArray());
}

From source file:org.alfresco.repo.webdav.PropFindMethod.java

License:Open Source License

/**
 * Generates the required response XML for the current node
 * /*from  w ww  .ja v  a 2 s . c  om*/
 * @param xml XMLWriter
 * @param nodeInfo FileInfo
 * @param path String
 */
protected void generateResponseForNode(XMLWriter xml, FileInfo nodeInfo, String path) throws Exception {
    boolean isFolder = nodeInfo.isFolder();

    // Output the response block for the current node
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_RESPONSE, WebDAV.XML_NS_RESPONSE,
            getDAVHelper().getNullAttributes());

    // Build the href string for the current node
    String strHRef = getURLForPath(m_request, path, isFolder);

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_HREF, WebDAV.XML_NS_HREF, getDAVHelper().getNullAttributes());
    xml.write(strHRef);
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_HREF, WebDAV.XML_NS_HREF);

    switch (m_mode) {
    case GET_NAMED_PROPS:
        generateNamedPropertiesResponse(xml, nodeInfo, isFolder);
        break;
    case GET_ALL_PROPS:
        generateAllPropertiesResponse(xml, nodeInfo, isFolder);
        break;
    case FIND_PROPS:
        generateFindPropertiesResponse(xml, nodeInfo, isFolder);
        break;
    }

    // Close off the response element
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_RESPONSE, WebDAV.XML_NS_RESPONSE);
}

From source file:org.alfresco.repo.webdav.PropFindMethod.java

License:Open Source License

/**
 * Generates the XML response for a PROPFIND request that asks for a
 * specific set of properties/*from w w  w . j a v a  2  s .  co  m*/
 * 
 * @param xml XMLWriter
 * @param nodeInfo FileInfo
 * @param isDir boolean
 */
private void generateNamedPropertiesResponse(XMLWriter xml, FileInfo nodeInfo, boolean isDir) throws Exception {
    // Get the properties for the node
    Map<QName, Serializable> props = nodeInfo.getProperties();
    Map<QName, String> deadProperties = null;

    // Output the start of the properties element
    Attributes nullAttr = getDAVHelper().getNullAttributes();

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT, nullAttr);
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP, nullAttr);

    ArrayList<WebDAVProperty> propertiesNotFound = new ArrayList<WebDAVProperty>();

    TypeConverter typeConv = DefaultTypeConverter.INSTANCE;

    // Loop through the requested property list
    for (WebDAVProperty property : m_properties) {
        // Get the requested property details

        String propName = property.getName();
        String propNamespaceUri = property.getNamespaceUri();

        // Check if the property is a standard WebDAV property

        Object davValue = null;

        if (WebDAV.DEFAULT_NAMESPACE_URI.equals(propNamespaceUri)) {
            // Check if the client is requesting lock information
            if (propName.equals(WebDAV.XML_LOCK_DISCOVERY)) // && metaData.isLocked())
            {
                generateLockDiscoveryResponse(xml, nodeInfo, isDir);
            } else if (propName.equals(WebDAV.XML_SUPPORTED_LOCK)) {
                // Output the supported lock types
                writeLockTypes(xml);
            }

            // Check if the client is requesting the resource type

            else if (propName.equals(WebDAV.XML_RESOURCE_TYPE)) {
                // If the node is a folder then return as a collection type

                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_RESOURCE_TYPE, WebDAV.XML_NS_RESOURCE_TYPE,
                        nullAttr);
                if (isDir) {
                    xml.write(DocumentHelper.createElement(WebDAV.XML_NS_COLLECTION));
                }
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_RESOURCE_TYPE, WebDAV.XML_NS_RESOURCE_TYPE);
            } else if (propName.equals(WebDAV.XML_DISPLAYNAME)) {
                // Get the node name
                if (getRootNodeRef().equals(nodeInfo.getNodeRef())) {
                    // Output an empty name for the root node
                    xml.write(DocumentHelper.createElement(WebDAV.XML_NS_SOURCE));
                } else {
                    // Get the node name
                    davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_DISPLAYNAME);

                    // Output the node name
                    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_DISPLAYNAME, WebDAV.XML_NS_DISPLAYNAME,
                            nullAttr);
                    if (davValue != null) {
                        String name = typeConv.convert(String.class, davValue);
                        if (name == null || name.length() == 0) {
                            logger.error("WebDAV name is null, value=" + davValue.getClass().getName()
                                    + ", node=" + nodeInfo.getNodeRef());
                        }
                        xml.write(name);
                    }
                    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_DISPLAYNAME, WebDAV.XML_NS_DISPLAYNAME);
                }
            } else if (propName.equals(WebDAV.XML_SOURCE)) {
                // NOTE: source is always a no content element in our
                // implementation

                xml.write(DocumentHelper.createElement(WebDAV.XML_NS_SOURCE));
            } else if (propName.equals(WebDAV.XML_GET_LAST_MODIFIED)) {
                // Get the modifed date/time

                davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_GET_LAST_MODIFIED);

                // Output the last modified date of the node

                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_LAST_MODIFIED, WebDAV.XML_NS_GET_LAST_MODIFIED,
                        nullAttr);
                if (davValue != null)
                    xml.write(WebDAV.formatModifiedDate(typeConv.convert(Date.class, davValue)));
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_LAST_MODIFIED, WebDAV.XML_NS_GET_LAST_MODIFIED);
            } else if (propName.equals(WebDAV.XML_GET_CONTENT_LANGUAGE) && !isDir) {
                // Get the content language
                // TODO:
                // Output the content language
                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LANGUAGE,
                        WebDAV.XML_NS_GET_CONTENT_LANGUAGE, nullAttr);
                // TODO:
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LANGUAGE,
                        WebDAV.XML_NS_GET_CONTENT_LANGUAGE);
            } else if (propName.equals(WebDAV.XML_GET_CONTENT_TYPE) && !isDir) {
                // Get the content type
                davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_GET_CONTENT_TYPE);

                // Output the content type
                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_TYPE, WebDAV.XML_NS_GET_CONTENT_TYPE,
                        nullAttr);
                if (davValue != null)
                    xml.write(typeConv.convert(String.class, davValue));
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_TYPE, WebDAV.XML_NS_GET_CONTENT_TYPE);
            } else if (propName.equals(WebDAV.XML_GET_ETAG) && !isDir) {
                // Output the etag

                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_ETAG, WebDAV.XML_NS_GET_ETAG, nullAttr);
                xml.write(getDAVHelper().makeETag(nodeInfo));
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_ETAG, WebDAV.XML_NS_GET_ETAG);
            } else if (propName.equals(WebDAV.XML_GET_CONTENT_LENGTH)) {
                // Get the content length, if it's not a folder
                long len = 0;

                if (!isDir) {
                    ContentData contentData = (ContentData) props.get(ContentModel.PROP_CONTENT);
                    if (contentData != null)
                        len = contentData.getSize();
                }

                // Output the content length
                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LENGTH, WebDAV.XML_NS_GET_CONTENT_LENGTH,
                        nullAttr);
                xml.write("" + len);
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LENGTH, WebDAV.XML_NS_GET_CONTENT_LENGTH);
            } else if (propName.equals(WebDAV.XML_CREATION_DATE)) {
                // Get the creation date
                davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_CREATION_DATE);

                // Output the creation date
                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_CREATION_DATE, WebDAV.XML_NS_CREATION_DATE,
                        nullAttr);
                if (davValue != null)
                    xml.write(WebDAV.formatCreationDate(typeConv.convert(Date.class, davValue)));
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_CREATION_DATE, WebDAV.XML_NS_CREATION_DATE);
            } else if (propName.equals(WebDAV.XML_ALF_AUTHTICKET)) {
                // Get the users authentication ticket

                SessionUser davUser = (SessionUser) m_request.getSession()
                        .getAttribute(AuthenticationFilter.AUTHENTICATION_USER);

                xml.startElement(WebDAV.DAV_NS, WebDAV.XML_ALF_AUTHTICKET, WebDAV.XML_NS_ALF_AUTHTICKET,
                        nullAttr);
                if (davUser != null)
                    xml.write(davUser.getTicket());
                xml.endElement(WebDAV.DAV_NS, WebDAV.XML_ALF_AUTHTICKET, WebDAV.XML_NS_ALF_AUTHTICKET);
            } else {
                // Could not map the requested property to an Alfresco property
                if (property.getName().equals(WebDAV.XML_HREF) == false)
                    propertiesNotFound.add(property);
            }
        } else {
            // Look in the custom properties

            //                String qualifiedName = propNamespaceUri + WebDAV.NAMESPACE_SEPARATOR + propName;

            String value = (String) nodeInfo.getProperties().get(property.createQName());
            if (value == null) {
                if (deadProperties == null) {
                    deadProperties = loadDeadProperties(nodeInfo.getNodeRef());
                }
                value = deadProperties.get(property.createQName());
            }

            if (value == null) {
                propertiesNotFound.add(property);
            } else {
                if (property.hasNamespaceName()) {
                    xml.startElement(property.getNamespaceName(), property.getName(),
                            property.getNamespaceName() + WebDAV.NAMESPACE_SEPARATOR + property.getName(),
                            nullAttr);
                    xml.write(value);
                    xml.endElement(property.getNamespaceName(), property.getName(),
                            property.getNamespaceName() + WebDAV.NAMESPACE_SEPARATOR + property.getName());
                } else {
                    xml.startElement("", property.getName(), property.getName(), nullAttr);
                    xml.write(value);
                    xml.endElement("", property.getName(), property.getName());
                }
            }

        }
    }

    // Close off the successful part of the response

    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP);

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS, nullAttr);
    xml.write(WebDAV.HTTP1_1 + " " + HttpServletResponse.SC_OK + " " + WebDAV.SC_OK_DESC);
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS);

    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT);

    // If some of the requested properties were not found return another
    // status section

    if (propertiesNotFound.size() > 0) {
        // Start the second status section

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT, nullAttr);
        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP, nullAttr);

        // Loop through the list of properties that were not found

        for (WebDAVProperty property : propertiesNotFound) {
            // Output the property not found status block

            String propName = property.getName();
            String propNamespaceName = property.getNamespaceName();
            String propQName = propName;
            if (propNamespaceName != null && propNamespaceName.length() > 0)
                propQName = propNamespaceName + ":" + propName;

            xml.write(DocumentHelper.createElement(propQName));
        }

        // Close the unsuccessful part of the response

        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP);

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS, nullAttr);
        xml.write(WebDAV.HTTP1_1 + " " + HttpServletResponse.SC_NOT_FOUND + " " + WebDAV.SC_NOT_FOUND_DESC);
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS);

        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT);
    }
}

From source file:org.alfresco.repo.webdav.PropFindMethod.java

License:Open Source License

/**
 * Generates the XML response for a PROPFIND request that asks for all known
 * properties/*from w  ww  .j ava  2 s. c  om*/
 * 
 * @param xml XMLWriter
 * @param nodeInfo FileInfo
 * @param isDir boolean
 */
protected void generateAllPropertiesResponse(XMLWriter xml, FileInfo nodeInfo, boolean isDir) throws Exception {
    // Get the properties for the node

    Map<QName, Serializable> props = nodeInfo.getProperties();

    // Output the start of the properties element

    Attributes nullAttr = getDAVHelper().getNullAttributes();

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT, nullAttr);
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP, nullAttr);

    // Generate a lock status report, if locked

    generateLockDiscoveryResponse(xml, nodeInfo, isDir);

    // Output the supported lock types

    writeLockTypes(xml);

    // If the node is a folder then return as a collection type

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_RESOURCE_TYPE, WebDAV.XML_NS_RESOURCE_TYPE, nullAttr);
    if (isDir)
        xml.write(DocumentHelper.createElement(WebDAV.XML_NS_COLLECTION));
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_RESOURCE_TYPE, WebDAV.XML_NS_RESOURCE_TYPE);

    // Get the node name

    Object davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_DISPLAYNAME);

    TypeConverter typeConv = DefaultTypeConverter.INSTANCE;

    // Output the node name

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_DISPLAYNAME, WebDAV.XML_NS_DISPLAYNAME, nullAttr);
    if (davValue != null) {
        String name = typeConv.convert(String.class, davValue);
        if (name == null || name.length() == 0) {
            logger.error("WebDAV name is null, value=" + davValue.getClass().getName() + ", node="
                    + nodeInfo.getNodeRef());
        }
        xml.write(name);
    }
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_DISPLAYNAME, WebDAV.XML_NS_DISPLAYNAME);

    // Output the source
    //
    // NOTE: source is always a no content element in our implementation

    xml.write(DocumentHelper.createElement(WebDAV.XML_NS_SOURCE));

    // Get the creation date

    davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_CREATION_DATE);

    // Output the creation date

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_CREATION_DATE, WebDAV.XML_NS_CREATION_DATE, nullAttr);
    if (davValue != null)
        xml.write(WebDAV.formatCreationDate(typeConv.convert(Date.class, davValue)));
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_CREATION_DATE, WebDAV.XML_NS_CREATION_DATE);

    // Get the modifed date/time

    davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_GET_LAST_MODIFIED);

    // Output the last modified date of the node

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_LAST_MODIFIED, WebDAV.XML_NS_GET_LAST_MODIFIED, nullAttr);
    if (davValue != null)
        xml.write(WebDAV.formatModifiedDate(typeConv.convert(Date.class, davValue)));
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_LAST_MODIFIED, WebDAV.XML_NS_GET_LAST_MODIFIED);

    // For a file node output the content language and content type

    if (isDir == false) {
        // Get the content language

        // TODO:
        // Output the content language

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LANGUAGE, WebDAV.XML_NS_GET_CONTENT_LANGUAGE,
                nullAttr);
        // TODO:
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LANGUAGE, WebDAV.XML_NS_GET_CONTENT_LANGUAGE);

        // Get the content type
        davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_GET_CONTENT_TYPE);

        // Output the content type
        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_TYPE, WebDAV.XML_NS_GET_CONTENT_TYPE, nullAttr);
        if (davValue != null)
            xml.write(typeConv.convert(String.class, davValue));
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_TYPE, WebDAV.XML_NS_GET_CONTENT_TYPE);

        // Output the etag

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_ETAG, WebDAV.XML_NS_GET_ETAG, nullAttr);
        xml.write(getDAVHelper().makeETag(nodeInfo));
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_ETAG, WebDAV.XML_NS_GET_ETAG);
    }

    // Get the content length, if it's not a folder

    long len = 0;

    if (isDir == false) {
        ContentData contentData = (ContentData) props.get(ContentModel.PROP_CONTENT);
        if (contentData != null)
            len = contentData.getSize();
    }

    // Output the content length

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LENGTH, WebDAV.XML_NS_GET_CONTENT_LENGTH, nullAttr);
    xml.write("" + len);
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LENGTH, WebDAV.XML_NS_GET_CONTENT_LENGTH);

    // Print out all the custom properties

    SessionUser davUser = (SessionUser) m_request.getSession()
            .getAttribute(AuthenticationFilter.AUTHENTICATION_USER);

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_ALF_AUTHTICKET, WebDAV.XML_NS_ALF_AUTHTICKET, nullAttr);
    if (davUser != null)
        xml.write(davUser.getTicket());
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_ALF_AUTHTICKET, WebDAV.XML_NS_ALF_AUTHTICKET);

    // Close off the response

    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP);

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS, nullAttr);
    xml.write(WebDAV.HTTP1_1 + " " + HttpServletResponse.SC_OK + " " + WebDAV.SC_OK_DESC);
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS);

    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT);
}

From source file:org.alfresco.repo.webdav.PropPatchMethod.java

License:Open Source License

@Override
protected void generateResponseImpl() throws Exception {
    m_response.setStatus(WebDAV.WEBDAV_SC_MULTI_STATUS);

    // Set the response content type
    m_response.setContentType(WebDAV.XML_CONTENT_TYPE);

    // Create multistatus response
    XMLWriter xml = createXMLWriter();

    xml.startDocument();//from   w  ww  .  j  a  v  a  2s. c o m

    String nsdec = generateNamespaceDeclarations(m_namespaces);
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_MULTI_STATUS + nsdec, WebDAV.XML_NS_MULTI_STATUS + nsdec,
            getDAVHelper().getNullAttributes());

    // Output the response block for the current node
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_RESPONSE, WebDAV.XML_NS_RESPONSE,
            getDAVHelper().getNullAttributes());

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_HREF, WebDAV.XML_NS_HREF, getDAVHelper().getNullAttributes());
    xml.write(strHRef);
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_HREF, WebDAV.XML_NS_HREF);

    if (failedProperty != null) {
        generateError(xml);
    }

    for (PropertyAction propertyAction : m_propertyActions) {
        WebDAVProperty property = propertyAction.getProperty();
        int statusCode = propertyAction.getStatusCode();
        String statusCodeDescription = propertyAction.getStatusCodeDescription();
        generatePropertyResponse(xml, property, statusCode, statusCodeDescription);
    }

    // Close off the response element
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_RESPONSE, WebDAV.XML_NS_RESPONSE);

    // Close the outer XML element
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_MULTI_STATUS, WebDAV.XML_NS_MULTI_STATUS);

    // Send remaining data
    flushXML(xml);
}

From source file:org.alfresco.web.bean.dashboard.PageConfig.java

License:Open Source License

/**
 * Convert this config to an XML definition which can be serialized.
 * Example:/*from   w w w.j  a  va2s.c  o m*/
 * <code>
 * <?xml version="1.0"?>
 * <dashboard>
 *    <page id="main" layout-id="narrow-left-2column">
 *       <column>
 *          <dashlet idref="clock" />
 *          <dashlet idref="random-joke" />
 *       </column>
 *       <column>
 *          <dashlet idref="getting-started" />
 *          <dashlet idref="task-list" />
 *          <dashlet idref="my-checkedout-docs" />
 *          <dashlet idref="my-documents" />
 *       </column>
 *    </page>
 * </dashboard>
 * </code>
 * 
 * @return XML for this config
 */
public String toXML() {
    try {
        Document doc = DocumentHelper.createDocument();

        Element root = doc.addElement(ELEMENT_DASHBOARD);
        for (Page page : pages) {
            Element pageElement = root.addElement(ELEMENT_PAGE);
            pageElement.addAttribute(ATTR_ID, page.getId());
            pageElement.addAttribute(ATTR_LAYOUTID, page.getLayoutDefinition().Id);
            for (Column column : page.getColumns()) {
                Element columnElement = pageElement.addElement(ELEMENT_COLUMN);
                for (DashletDefinition dashletDef : column.getDashlets()) {
                    columnElement.addElement(ELEMENT_DASHLET).addAttribute(ATTR_REFID, dashletDef.Id);
                }
            }
        }

        StringWriter out = new StringWriter(512);
        XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
        writer.setWriter(out);
        writer.write(doc);

        return out.toString();
    } catch (Throwable err) {
        throw new AlfrescoRuntimeException(
                "Unable to serialize Dashboard PageConfig to XML: " + err.getMessage(), err);
    }
}

From source file:org.alfresco.web.bean.search.SearchContext.java

License:Open Source License

/**
 * @return this SearchContext as XML//w  ww  .j  a  v a 2  s  .  c  om
 * 
 * Example:
 * <code>
 * <?xml version="1.0" encoding="UTF-8"?>
 * <search>
 *    <text>CDATA</text>
 *    <mode>int</mode>
 *    <location>XPath</location>
 *    <categories>
 *       <category>XPath</category>
 *    </categories>
 *    <content-type>String</content-type>
 *    <folder-type>String</folder-type>
 *    <mimetype>String</mimetype>
 *    <attributes>
 *       <attribute name="String">String</attribute>
 *    </attributes>
 *    <ranges>
 *       <range name="String">
 *          <lower>String</lower>
 *          <upper>String</upper>
 *          <inclusive>boolean</inclusive>
 *       </range>
 *    </ranges>
 *    <fixed-values>
 *       <value name="String">String</value>
 *    </fixed-values>
 *    <query>CDATA</query>
 * </search>
 * </code>
 */
public String toXML() {
    try {
        NamespaceService ns = Repository.getServiceRegistry(FacesContext.getCurrentInstance())
                .getNamespaceService();

        Document doc = DocumentHelper.createDocument();

        Element root = doc.addElement(ELEMENT_SEARCH);

        root.addElement(ELEMENT_TEXT).addCDATA(this.text);
        root.addElement(ELEMENT_MODE).addText(Integer.toString(this.mode));
        if (this.location != null) {
            root.addElement(ELEMENT_LOCATION).addText(this.location);
        }

        Element categories = root.addElement(ELEMENT_CATEGORIES);
        for (String path : this.categories) {
            categories.addElement(ELEMENT_CATEGORY).addText(path);
        }

        if (this.contentType != null) {
            root.addElement(ELEMENT_CONTENT_TYPE).addText(this.contentType);
        }
        if (this.folderType != null) {
            root.addElement(ELEMENT_FOLDER_TYPE).addText(this.folderType);
        }
        if (this.mimeType != null && this.mimeType.length() != 0) {
            root.addElement(ELEMENT_MIMETYPE).addText(this.mimeType);
        }

        Element attributes = root.addElement(ELEMENT_ATTRIBUTES);
        for (QName attrName : this.queryAttributes.keySet()) {
            attributes.addElement(ELEMENT_ATTRIBUTE).addAttribute(ELEMENT_NAME, attrName.toPrefixString(ns))
                    .addCDATA(this.queryAttributes.get(attrName));
        }

        Element ranges = root.addElement(ELEMENT_RANGES);
        for (QName rangeName : this.rangeAttributes.keySet()) {
            RangeProperties rangeProps = this.rangeAttributes.get(rangeName);
            Element range = ranges.addElement(ELEMENT_RANGE);
            range.addAttribute(ELEMENT_NAME, rangeName.toPrefixString(ns));
            range.addElement(ELEMENT_LOWER).addText(rangeProps.lower);
            range.addElement(ELEMENT_UPPER).addText(rangeProps.upper);
            range.addElement(ELEMENT_INCLUSIVE).addText(Boolean.toString(rangeProps.inclusive));
        }

        Element values = root.addElement(ELEMENT_FIXED_VALUES);
        for (QName valueName : this.queryFixedValues.keySet()) {
            values.addElement(ELEMENT_VALUE).addAttribute(ELEMENT_NAME, valueName.toPrefixString(ns))
                    .addCDATA(this.queryFixedValues.get(valueName));
        }

        // outputing the full lucene query may be useful for some situations
        Element query = root.addElement(ELEMENT_QUERY);
        String queryString = buildQuery(0);
        if (queryString != null) {
            query.addCDATA(queryString);
        }

        StringWriter out = new StringWriter(1024);
        XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
        writer.setWriter(out);
        writer.write(doc);

        return out.toString();
    } catch (Throwable err) {
        throw new AlfrescoRuntimeException("Failed to export SearchContext to XML.", err);
    }
}

From source file:org.apache.cxf.jaxrs.provider.dom4j.DOM4JProvider.java

License:Apache License

public void writeTo(org.dom4j.Document doc, Class<?> cls, Type type, Annotation[] anns, MediaType mt,
        MultivaluedMap<String, Object> headers, OutputStream os) throws IOException, WebApplicationException {
    if (!convertAlways && mt.getSubtype().contains("xml")) {

        XMLWriter writer;
        if (MessageUtils.getContextualBoolean(getCurrentMessage(), SUPPRESS_XML_DECLARATION, false)) {
            OutputFormat format = new org.dom4j.io.OutputFormat();
            format.setSuppressDeclaration(true);
            writer = new org.dom4j.io.XMLWriter(os, format);
        } else {//from w  w  w .  j a  v a 2 s. c o  m
            writer = new org.dom4j.io.XMLWriter(os);
        }
        writer.write(doc);
        writer.flush();
    } else {
        org.w3c.dom.Document domDoc = convertToDOM(doc);

        MessageBodyWriter<org.w3c.dom.Document> writer = providers.getMessageBodyWriter(DOM_DOC_CLS,
                DOM_DOC_CLS, anns, mt);
        if (writer == null) {
            throw ExceptionUtils.toNotAcceptableException(null, null);
        }
        writer.writeTo(domDoc, DOM_DOC_CLS, DOM_DOC_CLS, anns, mt, headers, os);
    }
}

From source file:org.apache.ddlutils.task.DumpMetadataTask.java

License:Apache License

/**
 * {@inheritDoc}/*from  w w w . j a  va 2 s .  c  o  m*/
 */
public void execute() throws BuildException {
    if (_dataSource == null) {
        log("No data source specified, so there is nothing to do.", Project.MSG_INFO);
        return;
    }

    Connection connection = null;
    try {
        Document document = DocumentFactory.getInstance().createDocument();
        Element root = document.addElement("metadata");

        root.addAttribute("driverClassName", _dataSource.getDriverClassName());

        connection = _dataSource.getConnection();

        dumpMetaData(root, connection.getMetaData());

        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = null;

        outputFormat.setEncoding(_outputEncoding);
        if (_outputFile == null) {
            xmlWriter = new XMLWriter(System.out, outputFormat);
        } else {
            xmlWriter = new XMLWriter(new FileOutputStream(_outputFile), outputFormat);
        }
        xmlWriter.write(document);
        xmlWriter.close();
    } catch (Exception ex) {
        throw new BuildException(ex);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException ex) {
            }
        }
    }
}