Example usage for org.dom4j Document getXMLEncoding

List of usage examples for org.dom4j Document getXMLEncoding

Introduction

In this page you can find the example usage for org.dom4j Document getXMLEncoding.

Prototype

String getXMLEncoding();

Source Link

Document

Return the encoding of this document, as part of the XML declaration This is null when unspecified or when it is not known (such as when the Document was created in memory) or when the implementation does not support this operation.

Usage

From source file:org.craftercms.cstudio.alfresco.transform.TaxonomyRendition.java

License:Open Source License

/**
 * Write renditionResult along with the flattened XML file to WCM
 * /*from   w  ww  .ja  v a  2 s  . co  m*/
 * @param articleRef
 */
public InputStream generateOutputFile(NodeRef articleRef) throws ServiceException {

    InputStream retStream = null;

    try {

        Document document = retreiveXml(articleRef);

        String encoding = document.getXMLEncoding();
        if (encoding == null) {
            encoding = "UTF-16";
        }

        Writer stringOutputWriter = new StringWriter();
        OutputFormat opf = OutputFormat.createCompactFormat();
        opf.setSuppressDeclaration(true);
        XMLWriter writer = new XMLWriter(stringOutputWriter, opf);
        writer.write(document);
        writer.close();

        retStream = new ByteArrayInputStream(stringOutputWriter.toString().getBytes(encoding));

    } catch (ServiceException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Cannot create output XML Document: " + e.getMessage(), e);
        }
        throw new ServiceException("Cannot create output XML Document: " + e.getMessage(), e);

    } catch (IOException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Cannot create output XML Document: " + e.getMessage(), e);
        }
        throw new ServiceException("Cannot create output XML Document: " + e.getMessage(), e);
    }

    return retStream;
}

From source file:org.esupportail.lecture.domain.model.Source.java

/**
 * Make Items objects in fonction of itemXPath, xsltURL, xmlStream.
 * @throws ComputeItemsException /*from  w w w .  j  a v a2 s .co m*/
 */
@SuppressWarnings("unchecked")
synchronized private void computeItems() throws ComputeItemsException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("id=" + this.profileId + " - computeItems()");
    }
    if (!itemComputed) {
        try {
            //create dom4j document
            Document document = DocumentHelper.parseText(xmlStream);
            //   get encoding
            String encoding = document.getXMLEncoding();
            //lauch Xpath find
            String x = getItemXPath();
            XPath xpath = document.createXPath(x);
            xpath.setNamespaceURIs(getXPathNameSpaces());
            List<Node> list = xpath.selectNodes(document);
            //List<Node> list = document.selectNodes(getItemXPath());
            Iterator<Node> iter = list.iterator();
            while (iter.hasNext()) {
                Node node = iter.next();
                Item item = new Item(this);
                StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"");
                xml.append(encoding);
                xml.append("\" ?>");
                xml.append(node.asXML());
                String xmlAsString = xml.toString();
                String htmlContent = xml2html(xmlAsString, getXsltURL(), encoding);
                item.setHtmlContent(htmlContent);
                String MobileHtmlContent = xml2html(xmlAsString, getMobileXsltURL(), encoding);
                item.setMobileHtmlContent(MobileHtmlContent);
                //find MD5 of item content for his ID
                byte[] hash = MessageDigest.getInstance("MD5").digest(xmlAsString.getBytes());
                StringBuffer hashString = new StringBuffer();
                for (int i = 0; i < hash.length; ++i) {
                    String hex = Integer.toHexString(hash[i]);
                    if (hex.length() == 1) {
                        hashString.append('0');
                        hashString.append(hex.charAt(hex.length() - 1));
                    } else {
                        hashString.append(hex.substring(hex.length() - 2));
                    }
                }
                item.setId(hashString.toString());
                items.add(item);
            }
        } catch (DocumentException e) {
            String errorMsg = "Error parsing XML content of the source";
            LOG.error(errorMsg, e);
            throw new ComputeItemsException(errorMsg, e);
        } catch (NoSuchAlgorithmException e) {
            String errorMsg = "MD5 algorithm not supported";
            LOG.error(errorMsg, e);
            throw new ComputeItemsException(errorMsg, e);
        } catch (XPathException e) {
            String errorMsg = "Xpath with NameSpace not specified in mappings.xml";
            LOG.error(errorMsg, e);
            throw new ComputeItemsException(errorMsg, e);
        } catch (MappingNotFoundException e) {
            String errorMsg = "Impossible to get itemXPath,XPathNameSpaces and xsltURL";
            LOG.error(errorMsg, e);
            throw new ComputeItemsException(errorMsg, e);
        } catch (Xml2HtmlException e) {
            String errorMsg = "Impossible to make html content";
            LOG.error(errorMsg, e);
            throw new ComputeItemsException(errorMsg, e);
        }
        itemComputed = true;
    }
}

From source file:org.esupportail.lecture.domain.model.Source.java

/**
 * transform a xml String in a html String with an XSLT.
 * @param xml to transform/*from  www. ja  va2s.  co m*/
 * @param xsltFileURL URL of XSLT file
 * @param encoding of xml to transform
 * @return html content
 * @throws Xml2HtmlException 
 */
private String xml2html(final String xml, final String xsltFileURL, final String encoding)
        throws Xml2HtmlException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("id=" + this.profileId + " - xml2html(xml,xsltFileURL)");
    }
    LOG.debug("voici le xsltFileUrl : " + xsltFileURL);
    String ret = null;
    try {
        //       1. Instantiate a TransformerFactory.
        TransformerFactory tFactory = TransformerFactory.newInstance();
        //      2. Use the TransformerFactory to process the stylesheet Source and
        //      generate a Transformer.
        Transformer transformer;
        String xsltFileContent = DomainTools.getXsltFile(xsltFileURL);
        //create dom4j document
        Document document = DocumentHelper.parseText(xsltFileContent);
        //   get encoding
        String xslEncoding = document.getXMLEncoding();
        if (xslEncoding == null) {
            xslEncoding = "UTF-8";
        }
        LOG.debug("voici le xsltFileContent : " + xsltFileContent);
        ByteArrayInputStream inputXsltFile = new ByteArrayInputStream(xsltFileContent.getBytes(xslEncoding));
        StreamSource sourceXsltFile = new StreamSource(inputXsltFile);
        transformer = tFactory.newTransformer(sourceXsltFile);
        //      3. Use the Transformer to transform an XML Source and send the
        //      output to a Result object.
        ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes(encoding));
        StreamSource source = new StreamSource(inputStream);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(outputStream);
        transformer.transform(source, result);
        ret = outputStream.toString("UTF-8");
    } catch (TransformerConfigurationException e) {
        String errorMsg = "Error in XSTL Transformation configuration";
        LOG.error(errorMsg);
        throw new Xml2HtmlException(errorMsg, e);
    } catch (TransformerException e) {
        String errorMsg = "Error in XSTL Transformation";
        LOG.error(errorMsg);
        throw new Xml2HtmlException(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "IO Error in xml2html";
        LOG.error(errorMsg);
        throw new Xml2HtmlException(errorMsg, e);
    } catch (DocumentException e) {
        String errorMsg = "Error determining XSLT encoding";
        LOG.error(errorMsg);
        throw new Xml2HtmlException(errorMsg, e);
    }
    return ret;
}

From source file:org.openadaptor.auxil.convertor.xml.OrderedMapToXmlConvertor.java

License:Open Source License

/**
 * Performs the actual conversion. Will recursively add each element of the map as
 * //ww  w.  j a  v a  2 s .  c o m
 * @param map
 *          the map to be converted
 * @param returnAsString
 *          if true then the Dom4j Document is returned
 * 
 * @return the xml (or Dom4j Document) corresponding to the supplied OrderedMap
 * 
 * @throws RecordException
 *           if the conversion fails
 */
private Object convertOrderedMapToXml(IOrderedMap map, boolean returnAsString) throws RecordException {
    Object result = null;

    // Create a Document to hold the data.
    Document doc = DocumentHelper.createDocument();
    if (encoding != null) {
        // Doesn't seem to have any effect here, so output formatter also sets it
        doc.setXMLEncoding(encoding);
        log.debug("Document encoding now " + doc.getXMLEncoding());
    }

    String rootTag = rootElementTag;

    if (rootTag != null) {
        log.debug("Using Supplied root tag - unset rootElementTag property to disable");
    } else { // Try and derive it. Must have a single entry, whose value is itself an OM.
        log.debug("rootElementTag property is not set. Deriving root tag from data.");
        if (map.size() == 1) { // Might be able to derive root tag.
            Object rootTagObject = map.keys().get(0);
            rootTag = rootTagObject == null ? null : rootTagObject.toString();
            Object value = map.get(rootTag);
            if (value instanceof IOrderedMap) { // Bingo we're in.
                log.debug(
                        "Deriving rootElementTag property from map (set rootElementTag property explicitly to prevent this");
                map = (IOrderedMap) value; // Move down a level as we're adding it here.
            } else {// No go -be safe and add our own root.
                log.warn("Failed to derive root tag. Using default of "
                        + OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG);
                rootTag = OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG;
            }
        } else {// More than one top level entry. Give up and default.
            log.warn("Top level has more than one entry. Using default of "
                    + OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG);
            rootTag = OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG;
        }
    }
    //Fix for #SC35: OrderedMapToXmlConvertor should, but does not map slashes in the root tag 
    rootTag = generateElementName(rootTag);
    log.debug("Document root tag will be: " + rootTag);

    // Prime the root tag.
    Element root = doc.addElement(rootTag);

    Iterator it = map.keys().iterator();
    while (it.hasNext()) {
        String key = it.next().toString();
        Object value = map.get(key);
        addElement(root, key, value);
    }
    // document done. Phew.
    if (returnAsString) { // Darn, need to output the Document as a String.
        StringWriter sw = new StringWriter();
        OutputFormat outputFormat = OutputFormat.createCompactFormat();
        if (encoding != null) {
            log.debug("Output Format encoding as " + encoding);
            outputFormat.setEncoding(encoding); // This definitely sets it in the header!
        }
        //    outputFormat.setOmitEncoding(true);
        //    outputFormat.setSuppressDeclaration(true);
        XMLWriter writer = new XMLWriter(sw, outputFormat);
        try {
            writer.write(doc);
        } catch (IOException ioe) {
            log.warn("Failed to write the XML as a String");
            throw new RecordFormatException("Failed to write the XML as a String. Reason: " + ioe.toString(),
                    ioe);
        }
        result = sw.toString();
    } else {
        result = doc;
    }
    return result;
}

From source file:org.openadaptor.auxil.convertor.xml.OrderedMapToXmlConvertorTestCase.java

License:Open Source License

public void testProcessRecord() {
    try {/*from  w  ww  .  java2 s. c  om*/
        Object[] resultArray = om2xml.process(om);
        assertTrue(resultArray.length == 1);
        String xml = (String) resultArray[0];

        assertEquals(xmlString, xml);

        om2xml.setReturnXmlAsString(false);
        resultArray = om2xml.process(om);
        assertTrue(resultArray.length == 1);
        Document doc = (Document) resultArray[0];

        String encoding = doc.getXMLEncoding();
        assertEquals(AbstractTestXmlConvertor.docAsString(xmlDocument, encoding),
                AbstractTestXmlConvertor.docAsString(doc, encoding));
    } catch (RecordException re) {
        fail("Unexpected RecordException - " + re);
    }
}

From source file:org.pentaho.actionsequence.dom.actions.MQLAction.java

License:Open Source License

private Document prettyPrint(Document document) {
    try {/*from  www . j  ava2s.c o  m*/
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(document.getXMLEncoding());
        StringWriter stringWriter = new StringWriter();
        XMLWriter writer = new XMLWriter(stringWriter, format);
        // XMLWriter has a bug that is avoided if we reparse the document
        // prior to calling XMLWriter.write()
        writer.write(DocumentHelper.parseText(document.asXML()));
        writer.close();
        document = DocumentHelper.parseText(stringWriter.toString());
    } catch (Exception e) {
        e.printStackTrace();
        return (null);
    }
    return (document);
}

From source file:org.pentaho.actionsequence.dom.ActionSequenceDocument.java

License:Open Source License

public static Document prettyPrint(Document document) {
    try {//from  w ww  .  j  av a2s  . c o m
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(document.getXMLEncoding());
        StringWriter stringWriter = new StringWriter();
        XMLWriter writer = new XMLWriter(stringWriter, format);
        // XMLWriter has a bug that is avoided if we reparse the document
        // prior to calling XMLWriter.write()
        writer.write(DocumentHelper.parseText(document.asXML()));
        writer.close();
        document = DocumentHelper.parseText(stringWriter.toString());
    } catch (Exception e) {
        e.printStackTrace();
        return (null);
    }
    return (document);
}

From source file:org.pentaho.jpivot.AnalysisSaver.java

License:Open Source License

public static boolean saveAnalysis(final IPentahoSession session, final HashMap props, String path,
        String fileName, final boolean overwrite) {

    if ("true".equals(PentahoSystem.getSystemSetting("kiosk-mode", "false"))) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        throw new RuntimeException(
                Messages.getInstance().getErrorString("ANALYSISSAVER.ERROR_0006_SAVE_IS_DISABLED")); //$NON-NLS-1$
    }//  w w  w.j  a v  a 2 s. c o  m

    try {
        AnalysisSaver.logger = LogFactory.getLog(AnalysisSaver.class);

        // TODO: if this is a new JPivot report, get doc from generateXAction

        // We will (at this point in time) always have an original action sequence to start from...
        String originalActionReference = (String) props.get("actionreference"); //$NON-NLS-1$

        if (originalActionReference == null) {
            throw new MissingParameterException(
                    Messages.getInstance().getErrorString("ANALYSISSAVER.ERROR_0001_MISSING_ACTION_REFERENCE")); //$NON-NLS-1$
        }
        Document document = null;
        if (NEW_ACTION.equals(originalActionReference)) {
            String model = (String) props.get(PivotViewComponent.MODEL);
            String jndi = (String) props.get(PivotViewComponent.CONNECTION);
            String jdbc = null; // NOT SUPPORTED AT THIS TIME
            String cube = null; // No need, MDX statement already exists 

            String xaction = new AnalysisViewService().generateXAction(PentahoSessionHolder.getSession(),
                    Messages.getInstance().getString("BaseTest.DEFAULT_TITLE"),
                    Messages.getInstance().getString("BaseTest.DEFAULT_DESCRIPTION"), model, jndi, jdbc, cube);
            org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
            reader.setEntityResolver(new SolutionURIResolver());
            final String encoding = XmlHelper.getEncoding(xaction, null);
            document = reader.read(new ByteArrayInputStream(xaction.getBytes(encoding)));
        } else {
            try {
                org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
                reader.setEntityResolver(new SolutionURIResolver());
                document = reader.read(ActionSequenceResource.getInputStream(originalActionReference,
                        LocaleHelper.getLocale()));
            } catch (Throwable t) {
                // XML document can't be read. We'll just return a null document.
            }
        }
        // Update the document with the stuff we passed in on the props
        document = AnalysisSaver.updateDocument(document, props);
        fileName = fileName.endsWith(AnalysisSaver.SUFFIX) ? fileName : fileName + AnalysisSaver.SUFFIX;

        path = cleansePath(path, fileName);

        // Write contents to Unified Repository

        RepositoryFile jpivotRepoFile = null;
        IUnifiedRepository repository = PentahoSystem.get(IUnifiedRepository.class);
        try {
            jpivotRepoFile = repository.getFile(path + '/' + fileName);
        } catch (UnifiedRepositoryException e) {
            // file does not exist, ignore exception
        }
        if (jpivotRepoFile != null) {
            jpivotRepoFile = repository.updateFile(jpivotRepoFile,
                    new SimpleRepositoryFileData(
                            new ByteArrayInputStream(document.asXML().getBytes(document.getXMLEncoding())),
                            LocaleHelper.getSystemEncoding(), "application/xml"),
                    "Update to existing file");
        } else {
            RepositoryFile parentFile = repository.getFile(path);
            jpivotRepoFile = new RepositoryFile.Builder(fileName).title(RepositoryFile.ROOT_LOCALE, fileName)
                    .description(RepositoryFile.ROOT_LOCALE, fileName).build();
            jpivotRepoFile = repository.createFile(parentFile.getId(), jpivotRepoFile,
                    new SimpleRepositoryFileData(
                            new ByteArrayInputStream(document.asXML().getBytes(document.getXMLEncoding())),
                            LocaleHelper.getSystemEncoding(), "application/xml"),
                    "Initial JPivot View Check-in");
        }
    } catch (Exception e) {
        AnalysisSaver.logger.error(Messages.getInstance().getErrorString("ANALYSISSAVER.ERROR_0000_UNKNOWN"), //$NON-NLS-1$
                e);
        return false;
    }

    return true;
}

From source file:org.pentaho.platform.plugin.action.mondrian.AnalysisSaver.java

License:Open Source License

public static int saveAnalysis(final IPentahoSession session, final HashMap props, final String path,
        String fileName, final boolean overwrite) {

    if ("true".equals(PentahoSystem.getSystemSetting("kiosk-mode", "false"))) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        throw new RuntimeException(Messages.getErrorString("ANALYSISSAVER.ERROR_0006_SAVE_IS_DISABLED")); //$NON-NLS-1$
    }//from   w w w.  j  a  va  2  s.c  o  m

    int result = 0;
    try {
        AnalysisSaver.logger = LogFactory.getLog(AnalysisSaver.class);
        String baseUrl = PentahoSystem.getApplicationContext().getSolutionPath(""); //$NON-NLS-1$
        ISolutionRepository solutionRepository = PentahoSystem.get(ISolutionRepository.class, session);

        // We will (at this point in time) always have an original action sequence to start from...
        String originalActionReference = (String) props.get("actionreference"); //$NON-NLS-1$

        if (originalActionReference == null) {
            throw new MissingParameterException(
                    Messages.getErrorString("ANALYSISSAVER.ERROR_0001_MISSING_ACTION_REFERENCE")); //$NON-NLS-1$
        }

        org.dom4j.Document document = solutionRepository.getResourceAsDocument(originalActionReference,
                ISolutionRepository.ACTION_UPDATE);

        // Update the document with the stuff we passed in on the props
        document = AnalysisSaver.updateDocument(document, props);
        fileName = fileName.endsWith(AnalysisSaver.SUFFIX) ? fileName : fileName + AnalysisSaver.SUFFIX;
        result = solutionRepository.publish(baseUrl, path, fileName,
                document.asXML().getBytes(document.getXMLEncoding()), overwrite);

        // Now save the resource files
        ActionInfo actionInfo = ActionInfo.parseActionString(originalActionReference);
        String originalPath = actionInfo.getSolutionName() + "/" + actionInfo.getPath(); //$NON-NLS-1$
        String originalFileName = actionInfo.getActionName();
        originalFileName = originalFileName.substring(0, originalFileName.lastIndexOf(AnalysisSaver.SUFFIX));
        ISolutionFile[] parentFiles = solutionRepository
                .getSolutionFile(originalPath, ISolutionRepository.ACTION_EXECUTE).listFiles();
        String baseFileName = fileName.substring(0, fileName.lastIndexOf(AnalysisSaver.SUFFIX));
        for (ISolutionFile aSolutionFile : parentFiles) {
            if (!aSolutionFile.isDirectory() && aSolutionFile.getFileName().startsWith(originalFileName)
                    && aSolutionFile.getFileName().toLowerCase().endsWith(AnalysisSaver.PROPERTIES_SUFFIX)) {
                String newFileName = aSolutionFile.getFileName().replaceFirst(originalFileName, baseFileName);
                result = result & solutionRepository.publish(baseUrl, path, newFileName,
                        aSolutionFile.getData(), overwrite);
            }
        }

        solutionRepository.resetRepository();
    } catch (Exception e) {
        AnalysisSaver.logger.error(Messages.getErrorString("ANALYSISSAVER.ERROR_0000_UNKNOWN"), e); //$NON-NLS-1$
        result = ISolutionRepository.FILE_ADD_FAILED;
    }

    return result;
}

From source file:org.pentaho.platform.plugin.action.mondrian.catalog.MondrianCatalogHelper.java

License:Open Source License

@Deprecated
protected synchronized void writeDataSources(DataSources dataSources) {

    File dataSourcesFile;//from w  ww .j a v a2s. co  m
    try {
        dataSourcesFile = new File(new URL(dataSourcesConfig).getFile()); // dataSourcesConfigResource.getFile();
    } catch (IOException e) {
        throw new MondrianCatalogServiceException(Messages.getInstance()
                .getErrorString("MondrianCatalogHelper.ERROR_0005_RESOURCE_NOT_AVAILABLE"), e, Reason.GENERAL); //$NON-NLS-1$
    }

    Writer sxml;
    try {
        sxml = new FileWriter(dataSourcesFile);
    } catch (IOException e) {
        throw new MondrianCatalogServiceException(e);
    }
    StringWriter sw = new StringWriter();
    XMLOutput pxml = new XMLOutput(sw);
    pxml.print("<?xml version=\"1.0\"?>\n"); //$NON-NLS-1$
    dataSources.displayXML(pxml, 0);
    Document doc = null;
    try {
        doc = XmlDom4JHelper.getDocFromString(sw.toString(), new PentahoEntityResolver());
    } catch (XmlParseException e) {
        throw new MondrianCatalogServiceException(e);
    }

    // pretty print
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(doc.getXMLEncoding());
        XMLWriter writer = new XMLWriter(sxml, format);
        writer.write(doc);
        writer.close();
        // CleanXmlHelper.saveDomToWriter(doc, sxml);
    } catch (IOException e) {
        throw new MondrianCatalogServiceException(e);
    }

    IOUtils.closeQuietly(sxml);
}