Example usage for org.dom4j.io OutputFormat createCompactFormat

List of usage examples for org.dom4j.io OutputFormat createCompactFormat

Introduction

In this page you can find the example usage for org.dom4j.io OutputFormat createCompactFormat.

Prototype

public static OutputFormat createCompactFormat() 

Source Link

Document

A static helper method to create the default compact format.

Usage

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

License:Open Source License

public static void write(Document document, String filePath, String printMode, String encoding)
        throws IOException {

    OutputFormat format = null;//from www  .j a va2  s  .co  m

    if (printMode.toLowerCase().equals("pretty")) {//$NON-NLS-1$
        // Pretty print the document
        format = OutputFormat.createPrettyPrint();
    } else if (printMode.toLowerCase().equals("compact")) {//$NON-NLS-1$
        // Compact format
        format = OutputFormat.createCompactFormat();
    }

    format.setEncoding(encoding);

    // lets write to a file
    XMLWriter writer = new XMLWriter(new FileOutputStream(filePath), format);

    // XMLWriter logger = new XMLWriter( System.out, format );

    writer.write(document);

    logger.info(Messages.bind(Messages.XmlUtil_Loginfo1, filePath));

    // logger.write( document );

    // logger.close();

    writer.close();
}

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

License:Open Source License

public static String formatCompact(String xml, String encoding) throws DocumentException {
    Document document = fromXml(xml);
    return format(document, OutputFormat.createCompactFormat(), encoding);
}

From source file:com.anite.zebra.ext.xmlloader.XMLLoadProcess.java

License:Apache License

/**
 * Read in a file of XML, strip out the pretty printing via some juggling of objects and then return a
 * org.w3.document DOM object.//from  www  .j a va 2s  . c o  m
 * 
 * @param xmlFile
 *            The file to be read in.
 * @return A ready to use org.w3.Document with pretty printing stripped out.
 * @throws DocumentException
 * @throws MalformedURLException
 * @throws UnsupportedEncodingException
 * @throws IOException
 */
private Document readDocument(File xmlFile)
        throws DocumentException, MalformedURLException, UnsupportedEncodingException, IOException {
    SAXReader xmlReader = new SAXReader();
    xmlReader.setStripWhitespaceText(true);

    org.dom4j.Document dom4jDocument = xmlReader.read(xmlFile);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OutputFormat format = OutputFormat.createCompactFormat();
    XMLWriter writer = new XMLWriter(baos, format);

    writer.write(dom4jDocument);

    dom4jDocument = DocumentHelper.parseText(baos.toString());

    DOMWriter domWriter = new DOMWriter();
    Document doc = domWriter.write(dom4jDocument);
    return doc;
}

From source file:com.chingo247.structureapi.plan.io.export.StructurePlanExporter.java

License:Open Source License

public void export(IStructurePlan plan, File destinationDirectory, String fileName, boolean prettyPrint)
        throws IOException, UnsupportedPlacementException {
    Preconditions.checkArgument(destinationDirectory.isDirectory());

    IPlacement placement = plan.getPlacement();
    if (!(placement instanceof IExportablePlacement)) {
        throw new UnsupportedPlacementException("Placement does not implement IWriteablePlacement");
    }/*from   w ww .j a va2 s.  c  o  m*/

    Document d = DocumentHelper.createDocument();

    Element root = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_ROOT_ELEMENT);
    d.add(root);

    Element nameElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_NAME_ELEMENT);
    nameElement.setText(plan.getName());
    root.add(nameElement);

    Element priceElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_PRICE_ELEMENT);
    priceElement.setText(String.valueOf(plan.getPrice()));
    root.add(priceElement);

    Element categoryElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_CATEGORY_ELEMENT);
    categoryElement.setText(plan.getCategory() == null ? "None" : plan.getCategory());
    root.add(categoryElement);

    Element descriptionElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_DESCRIPTION_ELEMENT);
    descriptionElement.setText(plan.getDescription() == null ? "None" : plan.getDescription());
    root.add(descriptionElement);

    Element placementElement = PlacementAPI.getInstance().handle((IExportablePlacement) plan.getPlacement());
    root.add(placementElement);

    //        if (plan instanceof SubStructuresPlan) {
    //            SubStructuresPlan ssp = (SubStructuresPlan) plan;
    //            
    //            Element substructuresElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_SUBSTRUCTURES);
    //            root.add(substructuresElement);
    //            
    //            for(Placement p : ssp.getSubPlacements()) {
    //                try {
    //                    Element e = PlacementAPI.getInstance().handle(p);
    //                    e.setName(StructurePlanXMLConstants.STRUCTURE_PLAN_SUBSTRUCTURE);
    //                    substructuresElement.add(e);
    //                } catch (PlacementException ex) {
    //                    System.err.println(ex.getMessage());
    //                }
    //            }
    //            
    //            int index = 0;
    //            for(StructurePlan p : ssp.getSubStructurePlans()) {
    //                File exportPlan = new File(destinationDirectory, p.getFile().getName() + "-" + index);
    //                
    //                try {
    //                    export(plan, destinationDirectory, exportPlan.getName(), prettyPrint);
    //                } catch (Exception e){
    //                    continue;
    //                }
    //                
    //                Element substructureElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_SUBSTRUCTURE);
    //                
    //                // TODO add position + direction
    //                
    //                Element typeElement = new BaseElement(PlacementXMLConstants.PLACEMENT_TYPE_ELEMENT);
    //                typeElement.setText(PlacementTypes.EMBEDDED);
    //                substructureElement.add(typeElement);
    //                
    //                Element pathElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_RELATIVE_PATH_ELEMENT);
    //                pathElement.setText(exportPlan.getName());
    //                substructureElement.add(pathElement);
    //                
    //                substructuresElement.add(substructureElement);
    //                
    //            }
    //            
    //        }

    OutputFormat format;
    if (prettyPrint) {
        format = OutputFormat.createPrettyPrint();
    } else {
        format = OutputFormat.createCompactFormat();
    }
    XMLWriter writer = new XMLWriter(new FileWriter(new File(destinationDirectory, fileName)), format);
    writer.write(d);
    writer.close();

}

From source file:com.doculibre.constellio.utils.ConnectorManagerRequestUtils.java

License:Open Source License

public static Element sendPost(ConnectorManager connectorManager, String servletPath, Document document) {
    try {//from   w w w.j av a  2s  .  c o m
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);

        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        // Required protocol interceptors
        httpproc.addInterceptor(new RequestContent());
        httpproc.addInterceptor(new RequestTargetHost());
        // Recommended protocol interceptors
        httpproc.addInterceptor(new RequestConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpContext context = new BasicHttpContext(null);

        URL connectorManagerURL = new URL(connectorManager.getUrl());
        HttpHost host = new HttpHost(connectorManagerURL.getHost(), connectorManagerURL.getPort());

        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        try {
            HttpEntity requestBody;
            if (document != null) {
                //                 OutputFormat format = OutputFormat.createPrettyPrint();
                OutputFormat format = OutputFormat.createCompactFormat();
                StringWriter stringWriter = new StringWriter();
                XMLWriter xmlWriter = new XMLWriter(stringWriter, format);
                xmlWriter.write(document);
                String xmlAsString = stringWriter.toString();
                requestBody = new StringEntity(xmlAsString, "UTF-8");
            } else {
                requestBody = null;
            }
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }

            String target = connectorManager.getUrl() + servletPath;

            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", target);
            request.setEntity(requestBody);
            LOGGER.info(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            LOGGER.info("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.info(entityText);
            LOGGER.info("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.info("Connection kept alive...");
            }

            Document xml = DocumentHelper.parseText(entityText);
            return xml.getRootElement();
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.globalsight.everest.workflow.WorkflowTemplateAdapter.java

License:Apache License

/**
 * Saves the workflow template xml to the file storage dir.
 * // w w w.  j a  v a2s .co  m
 * @param p_document
 *            - the xml document of the workflow template.
 * @param p_templateName
 *            - the workflow template name.
 * 
 */
private void saveXmlToFileStore(Document p_document, String p_templateName) {
    OutputFormat format = OutputFormat.createCompactFormat();
    XMLWriter writer = null;
    try {
        String aaa = AmbFileStoragePathUtils.getWorkflowTemplateXmlDir().getAbsolutePath();
        writer = new XMLWriter(
                new FileOutputStream(AmbFileStoragePathUtils.getWorkflowTemplateXmlDir().getAbsolutePath()
                        + File.separator + p_templateName + WorkflowConstants.SUFFIX_XML),
                format);
        writer.write(p_document);
    } catch (Exception e) {
        c_category.info("Exception occurs when saving the template xml to file storage");
    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:com.liferay.portal.ejb.PortletManagerImpl.java

License:Open Source License

private Set _readPortletXML(String servletContextName, String xml, Map portletsPool)
        throws DocumentException, IOException {

    Set portletIds = new HashSet();

    if (xml == null) {
        return portletIds;
    }/*from   w  ww  .j  av  a2  s  .co  m*/

    /*EntityResolver resolver = new EntityResolver() {
       public InputSource resolveEntity(String publicId, String systemId) {
    InputStream is =
       getClass().getClassLoader().getResourceAsStream(
          "com/liferay/portal/resources/portlet-app_1_0.xsd");
            
    return new InputSource(is);
       }
    };*/

    SAXReader reader = new SAXReader();
    //reader.setEntityResolver(resolver);

    Document doc = reader.read(new StringReader(xml));

    Element root = doc.getRootElement();

    Set userAttributes = new HashSet();

    Iterator itr1 = root.elements("user-attribute").iterator();

    while (itr1.hasNext()) {
        Element userAttribute = (Element) itr1.next();

        String name = userAttribute.elementText("name");

        userAttributes.add(name);
    }

    itr1 = root.elements("portlet").iterator();

    while (itr1.hasNext()) {
        Element portlet = (Element) itr1.next();

        String portletId = portlet.elementText("portlet-name");
        if (servletContextName != null) {
            portletId = servletContextName + PortletConfigImpl.WAR_SEPARATOR + portletId;
        }

        portletIds.add(portletId);

        Portlet portletModel = (Portlet) portletsPool.get(portletId);
        if (portletModel == null) {
            portletModel = new Portlet(new PortletPK(portletId, _SHARED_KEY, _SHARED_KEY));

            portletsPool.put(portletId, portletModel);
        }

        if (servletContextName != null) {
            portletModel.setWARFile(true);
        }

        portletModel.setPortletClass(portlet.elementText("portlet-class"));

        Iterator itr2 = portlet.elements("init-param").iterator();

        while (itr2.hasNext()) {
            Element initParam = (Element) itr2.next();

            portletModel.getInitParams().put(initParam.elementText("name"), initParam.elementText("value"));
        }

        Element expirationCache = portlet.element("expiration-cache");
        if (expirationCache != null) {
            portletModel.setExpCache(new Integer(GetterUtil.getInteger(expirationCache.getText())));
        }

        itr2 = portlet.elements("supports").iterator();

        while (itr2.hasNext()) {
            Element supports = (Element) itr2.next();

            String mimeType = supports.elementText("mime-type");

            Iterator itr3 = supports.elements("portlet-mode").iterator();

            while (itr3.hasNext()) {
                Element portletMode = (Element) itr3.next();

                Set mimeTypeModes = (Set) portletModel.getPortletModes().get(mimeType);

                if (mimeTypeModes == null) {
                    mimeTypeModes = new HashSet();

                    portletModel.getPortletModes().put(mimeType, mimeTypeModes);
                }

                mimeTypeModes.add(portletMode.getTextTrim().toLowerCase());
            }
        }

        Set supportedLocales = portletModel.getSupportedLocales();

        supportedLocales.add(Locale.getDefault().getLanguage());

        itr2 = portlet.elements("supported-locale").iterator();

        while (itr2.hasNext()) {
            Element supportedLocaleEl = (Element) itr2.next();

            String supportedLocale = supportedLocaleEl.getText();

            supportedLocales.add(supportedLocale);
        }

        portletModel.setResourceBundle(portlet.elementText("resource-bundle"));

        Element portletInfo = portlet.element("portlet-info");

        String portletInfoTitle = null;
        String portletInfoShortTitle = null;
        String portletInfoKeyWords = null;

        if (portletInfo != null) {
            portletInfoTitle = portletInfo.elementText("title");
            portletInfoShortTitle = portletInfo.elementText("short-title");
            portletInfoKeyWords = portletInfo.elementText("keywords");
        }

        portletModel
                .setPortletInfo(new PortletInfo(portletInfoTitle, portletInfoShortTitle, portletInfoKeyWords));

        Element portletPreferences = portlet.element("portlet-preferences");

        String defaultPreferences = null;
        String prefsValidator = null;

        if (portletPreferences != null) {
            Element prefsValidatorEl = portletPreferences.element("preferences-validator");

            String prefsValidatorName = null;

            if (prefsValidatorEl != null) {
                prefsValidator = prefsValidatorEl.getText();

                portletPreferences.remove(prefsValidatorEl);
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            XMLWriter writer = new XMLWriter(baos, OutputFormat.createCompactFormat());

            writer.write(portletPreferences);

            defaultPreferences = baos.toString();
        }

        portletModel.setDefaultPreferences(defaultPreferences);
        portletModel.setPreferencesValidator(prefsValidator);

        if (!portletModel.isWARFile() && Validator.isNotNull(prefsValidator)
                && GetterUtil.getBoolean(PropsUtil.get(PropsUtil.PREFERENCE_VALIDATE_ON_STARTUP))) {

            try {
                PreferencesValidator prefsValidatorObj = PortalUtil.getPreferencesValidator(portletModel);

                prefsValidatorObj.validate(PortletPreferencesSerializer.fromDefaultXML(defaultPreferences));
            } catch (Exception e) {
                _log.warn("Portlet with the name " + portletId + " does not have valid default preferences");
            }
        }

        List roles = new ArrayList();

        itr2 = portlet.elements("security-role-ref").iterator();

        while (itr2.hasNext()) {
            Element role = (Element) itr2.next();

            roles.add(role.elementText("role-name"));
        }

        portletModel.setRolesArray((String[]) roles.toArray(new String[0]));

        portletModel.getUserAttributes().addAll(userAttributes);
    }

    return portletIds;
}

From source file:com.liferay.portlet.PortletPreferencesSerializer.java

License:Open Source License

public static String toXML(PortletPreferencesImpl prefs) throws SystemException {

    try {/*from   w  ww.  j  av a 2s  . c om*/
        Map preferences = prefs.getPreferences();

        DocumentFactory docFactory = DocumentFactory.getInstance();

        Element portletPreferences = docFactory.createElement("portlet-preferences");

        Iterator itr = preferences.entrySet().iterator();

        while (itr.hasNext()) {
            Map.Entry entry = (Map.Entry) itr.next();

            Preference preference = (Preference) entry.getValue();

            Element prefEl = docFactory.createElement("preference");

            Element nameEl = docFactory.createElement("name");
            nameEl.addText(preference.getName());

            prefEl.add(nameEl);

            String[] values = preference.getValues();

            for (int i = 0; i < values.length; i++) {
                Element valueEl = docFactory.createElement("value");
                valueEl.addText(values[i]);

                prefEl.add(valueEl);
            }

            if (preference.isReadOnly()) {
                Element valueEl = docFactory.createElement("read-only");
                valueEl.addText("true");
            }

            portletPreferences.add(prefEl);
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        XMLWriter writer = new XMLWriter(baos, OutputFormat.createCompactFormat());

        writer.write(portletPreferences);

        return baos.toString();
    } catch (IOException ioe) {
        throw new SystemException(ioe);
    }
}

From source file:com.rockagen.commons.util.XmlUtil.java

License:Apache License

/**
 * Format xml {@link OutputFormat#createCompactFormat()}
 *
 * @param xmlStr                xml String
 * @param enc                   encoding
 * @param isSuppressDeclaration set supperss declaration
 * @return Compact xml String//from w  w  w .java2 s.c om
 */
public static String formatCompact(String xmlStr, String enc, boolean isSuppressDeclaration) {

    if (CommUtil.isBlank(xmlStr))
        return xmlStr;

    if (enc == null)
        enc = ENCODING;

    OutputFormat formater = OutputFormat.createCompactFormat();
    formater.setEncoding(enc);
    formater.setSuppressDeclaration(isSuppressDeclaration);
    return format(xmlStr, formater);
}

From source file:com.stratumsoft.xmlgen.XmlGenOptions.java

License:Open Source License

public OutputFormat getOutputFormat() {
    if (outputFormat == null) {
        outputFormat = OutputFormat.createCompactFormat(); //default to compact format
    }/*w ww  .  j a  v a 2  s. c o  m*/
    return outputFormat;
}