Example usage for javax.xml.transform OutputKeys DOCTYPE_SYSTEM

List of usage examples for javax.xml.transform OutputKeys DOCTYPE_SYSTEM

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys DOCTYPE_SYSTEM.

Prototype

String DOCTYPE_SYSTEM

To view the source code for javax.xml.transform OutputKeys DOCTYPE_SYSTEM.

Click Source Link

Document

doctype-system = string.

Usage

From source file:com.krawler.portal.tools.ServiceBuilder.java

public void deleteSourceEntryCfgXml(String fileName) {
    try {/*  w w  w  . ja v  a 2 s . co m*/
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(PropsValues.CFG_SOURCE_FILE_PATH);
        Node hibernate_conf = doc.getChildNodes().item(1);
        Node SessionFac = hibernate_conf.getChildNodes().item(1);
        Element sesFac = (Element) SessionFac;
        NodeList mapping_lists = sesFac.getElementsByTagName("mapping");
        Node toDelete = null;
        for (int num = 0; num < mapping_lists.getLength(); num++) {
            Element mapEle = (Element) mapping_lists.item(num);
            if (mapEle.getAttribute("resource").equals(PropsValues.PACKAGE_FILE_PATH + fileName + ".hbm.xml")) {
                toDelete = mapEle;
                break;
            }
        }
        sesFac.removeChild(toDelete);
        DOMSource ds = new DOMSource(doc);
        StreamResult sr = new StreamResult(PropsValues.CFG_SOURCE_FILE_PATH);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
                "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd");
        trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//Hibernate/Hibernate Configuration DTD 3.0//EN");
        trans.transform(ds, sr);
    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (SAXException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
    }
}

From source file:com.krawler.portal.tools.ServiceBuilder.java

public void deleteClassesEntryCfgXml(String fileName) {
    try {//from ww w. j  a v  a  2 s  .c o  m
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(PropsValues.CFG_CLASSES_FILE_PATH);
        Node hibernate_conf = doc.getChildNodes().item(1);
        Node SessionFac = hibernate_conf.getChildNodes().item(1);
        Element sesFac = (Element) SessionFac;
        NodeList mapping_lists = sesFac.getElementsByTagName("mapping");
        Node toDelete = null;
        for (int num = 0; num < mapping_lists.getLength(); num++) {
            Element mapEle = (Element) mapping_lists.item(num);
            if (mapEle.getAttribute("resource").equals(PropsValues.PACKAGE_FILE_PATH + fileName + ".hbm.xml")) {
                toDelete = mapEle;
                break;
            }
        }
        sesFac.removeChild(toDelete);
        DOMSource ds = new DOMSource(doc);
        StreamResult sr = new StreamResult(PropsValues.CFG_CLASSES_FILE_PATH);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
                "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd");
        trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//Hibernate/Hibernate Configuration DTD 3.0//EN");
        trans.transform(ds, sr);
    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (SAXException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
    }
}

From source file:com.krawler.portal.tools.ServiceBuilder.java

public String convertXMLFileToString(File xmlFile) {
    try {//from   ww w.  j ava  2  s  .c  o  m
        //            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        //            InputStream inputStream = new FileInputStream(fileName);
        //            Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
        //            StringWriter stw = new StringWriter();
        //            Transformer serializer = TransformerFactory.newInstance().newTransformer();
        //            serializer.transform(new DOMSource(doc), new StreamResult(stw));
        //            return stw.toString();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlFile);
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
                "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd");
        transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//Hibernate/Hibernate Mapping DTD 3.0//EN");
        transformer.transform(domSource, result);
        return writer.toString();
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
    }
    return null;
}

From source file:org.apache.cocoon.serialization.AbstractTextSerializer.java

/**
 * Set the configurations for this serializer.
 *//*from ww w.  jav a2s . com*/
public void configure(Configuration conf) throws ConfigurationException {
    // configure buffer size
    //   Configuration bsc = conf.getChild("buffer-size", false);
    //   if(null != bsc)
    //    outputBufferSize = bsc.getValueAsInteger(DEFAULT_BUFFER_SIZE);

    // configure xalan
    String cdataSectionElements = conf.getChild("cdata-section-elements").getValue(null);
    String dtPublic = conf.getChild("doctype-public").getValue(null);
    String dtSystem = conf.getChild("doctype-system").getValue(null);
    String encoding = conf.getChild("encoding").getValue(null);
    String indent = conf.getChild("indent").getValue(null);
    String mediaType = conf.getChild("media-type").getValue(null);
    String method = conf.getChild("method").getValue(null);
    String omitXMLDeclaration = conf.getChild("omit-xml-declaration").getValue(null);
    String standAlone = conf.getChild("standalone").getValue(null);
    String version = conf.getChild("version").getValue(null);

    final StringBuffer buffer = new StringBuffer();

    if (cdataSectionElements != null) {
        format.put(OutputKeys.CDATA_SECTION_ELEMENTS, cdataSectionElements);
        buffer.append(";cdata-section-elements=").append(cdataSectionElements);
    }
    if (dtPublic != null) {
        format.put(OutputKeys.DOCTYPE_PUBLIC, dtPublic);
        buffer.append(";doctype-public=").append(dtPublic);
    }
    if (dtSystem != null) {
        format.put(OutputKeys.DOCTYPE_SYSTEM, dtSystem);
        buffer.append(";doctype-system=").append(dtSystem);
    }
    if (encoding != null) {
        format.put(OutputKeys.ENCODING, encoding);
        buffer.append(";encoding=").append(encoding);
    }
    if (indent != null) {
        format.put(OutputKeys.INDENT, indent);
        buffer.append(";indent=").append(indent);
    }
    if (mediaType != null) {
        format.put(OutputKeys.MEDIA_TYPE, mediaType);
        buffer.append(";media-type=").append(mediaType);
    }
    if (method != null) {
        format.put(OutputKeys.METHOD, method);
        buffer.append(";method=").append(method);
    }
    if (omitXMLDeclaration != null) {
        format.put(OutputKeys.OMIT_XML_DECLARATION, omitXMLDeclaration);
        buffer.append(";omit-xml-declaration=").append(omitXMLDeclaration);
    }
    if (standAlone != null) {
        format.put(OutputKeys.STANDALONE, standAlone);
        buffer.append(";standalone=").append(standAlone);
    }
    if (version != null) {
        format.put(OutputKeys.VERSION, version);
        buffer.append(";version=").append(version);
    }

    if (buffer.length() > 0) {
        this.cachingKey = buffer.toString();
    }

    String tFactoryClass = conf.getChild("transformer-factory").getValue(null);
    if (tFactoryClass != null) {
        try {
            this.tfactory = (SAXTransformerFactory) ClassUtils.newInstance(tFactoryClass);
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("Using transformer factory " + tFactoryClass);
            }
        } catch (Exception e) {
            throw new ConfigurationException("Cannot load transformer factory " + tFactoryClass, e);
        }
    } else {
        // Standard TrAX behaviour
        this.tfactory = (SAXTransformerFactory) TransformerFactory.newInstance();
    }
    tfactory.setErrorListener(new TraxErrorHandler(getLogger()));

    // Check if we need namespace as attributes.
    try {
        if (needsNamespacesAsAttributes()) {
            // Setup a correction pipe
            this.namespacePipe = new NamespaceAsAttributes();
            this.namespacePipe.enableLogging(getLogger());
        }
    } catch (Exception e) {
        getLogger().warn("Cannot know if transformer needs namespaces attributes - assuming NO.", e);
    }
}

From source file:org.apache.stratos.load.balancer.conf.configurator.SynapseConfigurator.java

/**
 * Write xml document to file./*  ww w  .j a  v  a 2  s.c o m*/
 *
 * @param document
 * @param outputFilePath
 * @throws IOException
 */
private static void write(Document document, String outputFilePath) throws IOException {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DocumentType documentType = document.getDoctype();
        if (documentType != null) {
            String publicId = documentType.getPublicId();
            if (publicId != null) {
                transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, publicId);
            }
            transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, documentType.getSystemId());
        }
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        Source source = new DOMSource(document);
        FileOutputStream outputStream = new FileOutputStream(outputFilePath);
        Result result = new StreamResult(outputStream);
        transformer.transform(source, result);
    } catch (Exception e) {
        throw new RuntimeException(String.format("Could not write xml file: s%", outputFilePath), e);
    }
}

From source file:org.dspace.installer_edm.InstallerEDMAskosi.java

/**
 * Modifica el archivo web.xml de Askosi para indicarle el directorio de datos de Askosi
 *
 * @param webXmlFile archivo web.xml de Askosi
 *///from ww w.j  a v  a 2  s  .c om
private void changeWebXml(File webXmlFile, String webXmlFileName) {
    try {
        // se abre con DOM el archivo web.xml
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(webXmlFile);
        XPath xpathInputForms = XPathFactory.newInstance().newXPath();

        // se busca el elemento SKOSdirectory
        NodeList results = (NodeList) xpathInputForms.evaluate("//*[contains(*,\"SKOSdirectory\")]", doc,
                XPathConstants.NODESET);
        if (results.getLength() > 0) {
            Element contextParam = (Element) results.item(0);

            // se busca el elemento context-param como hijo del anterior
            if (contextParam.getTagName().equals("context-param")) {

                // se busca el elemento param-value como hijo del anterior
                NodeList resultsParamValue = contextParam.getElementsByTagName("param-value");
                if (resultsParamValue.getLength() > 0) {

                    // se modifica con la ruta del directorio de datos de Askosi
                    Element valueParam = (Element) resultsParamValue.item(0);
                    Text text = doc.createTextNode(finalAskosiDataDestDirFile.getAbsolutePath());
                    valueParam.replaceChild(text, valueParam.getFirstChild());

                    // se guarda
                    TransformerFactory transformerFactory = TransformerFactory.newInstance();
                    Transformer transformer = transformerFactory.newTransformer();
                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
                    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                    //transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
                    DocumentType docType = doc.getDoctype();
                    if (docType != null) {
                        if (docType.getPublicId() != null)
                            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId());
                        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId());
                    }
                    DOMSource source = new DOMSource(doc);
                    StreamResult result = (fileSeparator.equals("\\")) ? new StreamResult(webXmlFileName)
                            : new StreamResult(webXmlFile);
                    transformer.transform(source, result);
                }
            }
        } else
            installerEDMDisplay.showQuestion(currentStepGlobal, "changeWebXml.noSKOSdirectory",
                    new String[] { webXmlFile.getAbsolutePath() });
    } catch (ParserConfigurationException e) {
        showException(e);
    } catch (SAXException e) {
        showException(e);
    } catch (IOException e) {
        showException(e);
    } catch (XPathExpressionException e) {
        showException(e);
    } catch (TransformerConfigurationException e) {
        showException(e);
    } catch (TransformerException e) {
        showException(e);
    }

}

From source file:org.dspace.installer_edm.InstallerEDMConfEDMExport.java

/**
 * Aadimos el contenido del documento jdom como archivo web.xml al flujo de escritura del war
 *
 * @param jarOutputStream flujo de escritura del war
 * @throws TransformerException//from   w w w .  j a  va 2  s.  co m
 * @throws IOException
 */
private void addNewWebXml(JarOutputStream jarOutputStream) throws TransformerException, IOException {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    //transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    DocumentType docType = eDMExportDocument.getDoctype();
    if (docType != null) {
        if (docType.getPublicId() != null)
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId());
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId());
    }
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(eDMExportDocument);
    transformer.transform(source, result);
    String xmlString = sw.toString();
    jarOutputStream.putNextEntry(new JarEntry("WEB-INF/web.xml"));
    jarOutputStream.write(xmlString.getBytes());
    jarOutputStream.closeEntry();
}

From source file:org.eclipse.buckminster.jnlp.componentinfo.cloudsmith.ComponentInfoProvider.java

public String prepareHTML(Map<String, String> properties, IOPML opml, String destination) throws Exception {
    if (opml == null)
        return null;
    if (properties == null)
        throw new IllegalArgumentException("Properties are not set");
    if (destination == null)
        throw new IllegalArgumentException("Target destination is not set");

    m_properties = properties;//from   ww  w.  j  a v a2s. c  om
    m_opml = opml;

    String htmlURL = null;

    InputStream is = getResource(IPath.SEPARATOR + SRC_HTML_FOLDER + IPath.SEPARATOR + HTML_TEMPLATE);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    FileUtils.copyFile(is, bos, m_nullMonitor);
    String string = bos.toString(HTML_ENCODING);

    String basePath = m_properties.get(PROP_BASE_PATH_URL);
    if (basePath == null)
        throw new Exception("Missing required property '" + PROP_BASE_PATH_URL + '\'');

    string = string.replaceAll(Pattern.quote(HTML_BASEPATH_PLACEHOLDER), basePath);

    m_xml = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new ByteArrayInputStream(string.getBytes(HTML_ENCODING)));

    fillTemplate();

    File htmlDestDir = new File(destination);

    if (!(htmlDestDir.exists() && htmlDestDir.isDirectory()))
        FileUtils.createDirectory(htmlDestDir, m_nullMonitor);

    File imgDestDir = new File(htmlDestDir, "img");

    if (!(imgDestDir.exists() && imgDestDir.isDirectory()))
        FileUtils.createDirectory(imgDestDir, m_nullMonitor);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(stream);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, HTML_ENCODING);
    transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, HTML_DOCTYPE_PUBLIC);
    transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, HTML_DOCTYPE_SYSTEM);
    transformer.transform(new DOMSource(m_xml), result);

    String htmlFileName = "distro." + m_properties.get(PROP_CSPEC_NAME) + "."
            + m_properties.get(PROP_CSPEC_VERSION_STRING) + ".html";
    htmlFileName = htmlFileName.replaceAll("(?:/|\\\\|:|\\*|\\?|\"|<|>|\\|)", "_");

    htmlURL = destination + File.separator + htmlFileName;

    FileUtils.copyFile(new ByteArrayInputStream(stream.toByteArray()), htmlDestDir, htmlFileName,
            m_nullMonitor);

    if (!new File(imgDestDir, IMG_FOOTER).exists())
        FileUtils.copyFile(getResource(IPath.SEPARATOR + SRC_HTML_IMG_FOLDER + IPath.SEPARATOR + IMG_FOOTER),
                imgDestDir, IMG_FOOTER, m_nullMonitor);
    if (!new File(imgDestDir, IMG_FAVICON).exists())
        FileUtils.copyFile(getResource(IPath.SEPARATOR + SRC_HTML_IMG_FOLDER + IPath.SEPARATOR + IMG_FAVICON),
                imgDestDir, IMG_FAVICON, m_nullMonitor);
    if (!new File(imgDestDir, IMG_RSS).exists())
        FileUtils.copyFile(getResource(IPath.SEPARATOR + SRC_HTML_IMG_FOLDER + IPath.SEPARATOR + IMG_RSS),
                imgDestDir, IMG_RSS, m_nullMonitor);
    if (!new File(imgDestDir, IMG_LOGO).exists())
        FileUtils.copyFile(new URL(m_properties.get(PROP_PROVIDER_LOGO_URL)).openStream(), imgDestDir, IMG_LOGO,
                m_nullMonitor);

    return htmlURL;
}

From source file:org.expath.tools.model.exist.EXistSequence.java

/**
 * Borrowed from {@link org.expath.tools.saxon.model.SaxonSequence}
 *///from www . j  a v a2s. c  o  m
private Properties makeOutputProperties(final SerialParameters params) throws ToolsException {
    final Properties props = new Properties();

    setOutputKey(props, OutputKeys.METHOD, params.getMethod());
    setOutputKey(props, OutputKeys.MEDIA_TYPE, params.getMediaType());
    setOutputKey(props, OutputKeys.ENCODING, params.getEncoding());
    setOutputKey(props, OutputKeys.CDATA_SECTION_ELEMENTS, params.getCdataSectionElements());
    setOutputKey(props, OutputKeys.DOCTYPE_PUBLIC, params.getDoctypePublic());
    setOutputKey(props, OutputKeys.DOCTYPE_SYSTEM, params.getDoctypeSystem());
    setOutputKey(props, OutputKeys.INDENT, params.getIndent());
    setOutputKey(props, OutputKeys.OMIT_XML_DECLARATION, params.getOmitXmlDeclaration());
    setOutputKey(props, OutputKeys.STANDALONE, params.getStandalone());
    setOutputKey(props, OutputKeys.VERSION, params.getVersion());

    return props;
}

From source file:org.geoserver.wms.capabilities.GetCapabilitiesTransformer.java

/**
 * Gets the <code>Transformer</code> created by the overriden method in the superclass and adds
 * it the system DOCTYPE token pointing to the Capabilities DTD on this server instance.
 * //from   ww  w  .ja  v a  2  s.  c  o m
 * <p>
 * The DTD is set at the fixed location given by the <code>schemaBaseUrl</code> passed to the
 * constructor <code>+
 * "wms/1.1.1/WMS_MS_Capabilities.dtd</code>.
 * </p>
 * 
 * @return a Transformer propoerly configured to produce DescribeLayer responses.h
 * 
 * @throws TransformerException
 *             if it is thrown by <code>super.createTransformer()</code>
 */
@Override
public Transformer createTransformer() throws TransformerException {
    Transformer transformer = super.createTransformer();
    String dtdUrl = buildSchemaURL(baseURL, "wms/1.1.1/WMS_MS_Capabilities.dtd");
    transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dtdUrl);

    return transformer;
}