Example usage for javax.xml.transform TransformerConfigurationException getMessage

List of usage examples for javax.xml.transform TransformerConfigurationException getMessage

Introduction

In this page you can find the example usage for javax.xml.transform TransformerConfigurationException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.apache.axiom.om.AbstractOMSerializationTest.java

public String writeXmlFile(Document doc) {
    try {//from w ww  .  ja  v  a 2  s.  co m
        // Prepare the DOM document for writing
        Source source = new DOMSource(doc);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Result result = new StreamResult(baos);

        // Write the DOM document to the file
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.transform(source, result);
        return new String(baos.toByteArray());
    } catch (TransformerConfigurationException e) {
        log.error(e.getMessage(), e);
    } catch (TransformerException e) {
        log.error(e.getMessage(), e);
    }
    return null;

}

From source file:org.apache.fop.events.model.EventModel.java

private void writeXMLizable(XMLizable object, File outputFile) throws IOException {
    //These two approaches do not seem to work in all environments:
    //Result res = new StreamResult(outputFile);
    //Result res = new StreamResult(outputFile.toURI().toURL().toExternalForm());
    //With an old Xalan version: file:/C:/.... --> file:\C:\.....
    OutputStream out = new java.io.FileOutputStream(outputFile);
    out = new java.io.BufferedOutputStream(out);
    Result res = new StreamResult(out);

    try {/*from ww w.  j a  va  2  s .co m*/
        SAXTransformerFactory tFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        TransformerHandler handler = tFactory.newTransformerHandler();
        Transformer transformer = handler.getTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        handler.setResult(res);
        handler.startDocument();
        object.toSAX(handler);
        handler.endDocument();
    } catch (TransformerConfigurationException e) {
        throw new IOException(e.getMessage());
    } catch (TransformerFactoryConfigurationError e) {
        throw new IOException(e.getMessage());
    } catch (SAXException e) {
        throw new IOException(e.getMessage());
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:org.apache.fop.layoutengine.LayoutEngineTestSuite.java

public static String[] readDisabledTestcases(File f) throws IOException {
    List lines = new java.util.ArrayList();
    Source stylesheet = new StreamSource(new File("test/layoutengine/disabled-testcase2filename.xsl"));
    Source source = new StreamSource(f);
    Result result = new SAXResult(new FilenameHandler(lines));
    try {/*w  w  w. j a  v a2  s .  c  om*/
        Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesheet);
        transformer.transform(source, result);
    } catch (TransformerConfigurationException tce) {
        throw new RuntimeException(tce.getMessage());
    } catch (TransformerException te) {
        throw new RuntimeException(te.getMessage());
    }
    return (String[]) lines.toArray(new String[lines.size()]);
}

From source file:org.apache.fop.visual.BatchDiffer.java

/**
 * Runs the batch/*from w w  w.  j  av  a 2 s  .  c om*/
 * @param cfg Configuration for the batch
 * @throws TransformerConfigurationException
 */
public void runBatch(Configuration cfg) {
    try {
        ProducerContext context = new ProducerContext();
        context.setTargetResolution(cfg.getChild("resolution").getValueAsInteger(72));
        String xslt = cfg.getChild("stylesheet").getValue(null);
        if (xslt != null) {
            try {
                context.setTemplates(context.getTransformerFactory().newTemplates(new StreamSource(xslt)));
            } catch (TransformerConfigurationException e) {
                log.error("Error setting up stylesheet", e);
                throw new RuntimeException("Error setting up stylesheet");
            }
        }
        BitmapProducer[] producers = getProducers(cfg.getChild("producers"));

        //Set up directories
        File srcDir = new File(cfg.getChild("source-directory").getValue());
        if (!srcDir.exists()) {
            throw new RuntimeException("source-directory does not exist: " + srcDir);
        }
        final File targetDir = new File(cfg.getChild("target-directory").getValue());
        if (!targetDir.mkdirs() && !targetDir.exists()) {
            throw new RuntimeException("target-directory is invalid: " + targetDir);
        }
        context.setTargetDir(targetDir);

        boolean stopOnException = cfg.getChild("stop-on-exception").getValueAsBoolean(true);
        final boolean createDiffs = cfg.getChild("create-diffs").getValueAsBoolean(true);

        //RUN!

        IOFileFilter filter = new SuffixFileFilter(new String[] { ".xml", ".fo" });
        //Same filtering as in layout engine tests
        if (cfg.getChild("filter-disabled").getValueAsBoolean(true)) {
            String disabled = System.getProperty("fop.layoutengine.disabled");
            filter = LayoutEngineTestUtils.decorateWithDisabledList(filter, disabled);
        }
        String manualFilter = cfg.getChild("manual-filter").getValue(null);
        if (manualFilter != null) {
            if (manualFilter.indexOf('*') < 0) {
                manualFilter = manualFilter + '*';
            }
            filter = new AndFileFilter(new WildcardFileFilter(manualFilter), filter);
        }

        int maxfiles = cfg.getChild("max-files").getValueAsInteger(-1);
        Collection<File> files = FileUtils.listFiles(srcDir, filter, null);
        for (final File f : files) {
            try {
                log.info("---=== " + f + " ===---");
                long[] times = new long[producers.length];
                final BufferedImage[] bitmaps = new BufferedImage[producers.length];
                for (int j = 0; j < producers.length; j++) {
                    times[j] = System.currentTimeMillis();
                    bitmaps[j] = producers[j].produce(f, j, context);
                    times[j] = System.currentTimeMillis() - times[j];
                }
                if (log.isDebugEnabled()) {
                    StringBuffer sb = new StringBuffer("Bitmap production times: ");
                    for (int j = 0; j < producers.length; j++) {
                        if (j > 0) {
                            sb.append(", ");
                        }
                        sb.append(times[j]).append("ms");
                    }
                    log.debug(sb.toString());
                }
                //Create combined image
                if (bitmaps[0] == null) {
                    throw new RuntimeException(
                            "First producer didn't return a bitmap for " + f + ". Cannot continue.");
                }

                Runnable runnable = new Runnable() {
                    public void run() {
                        try {
                            saveBitmaps(targetDir, f, createDiffs, bitmaps);
                        } catch (IOException e) {
                            log.error("IO error while saving bitmaps: " + e.getMessage());
                        }
                    }
                };
                //This speeds it up a little on multi-core CPUs (very cheap, I know)
                new Thread(runnable).start();
            } catch (RuntimeException e) {
                log.error("Catching RE on file " + f + ": " + e.getMessage());
                if (stopOnException) {
                    log.error("rethrowing...");
                    throw e;
                }
            }
            maxfiles = (maxfiles < 0 ? maxfiles : maxfiles - 1);
            if (maxfiles == 0) {
                break;
            }
        }
    } catch (ConfigurationException e) {
        log.error("Error while configuring BatchDiffer", e);
        throw new RuntimeException("Error while configuring BatchDiffer: " + e.getMessage());
    }
}

From source file:org.apache.solr.handler.dataimport.TikaEntityProcessor.java

@Override
public Map<String, Object> nextRow() {
    if (done)// w  ww  . j  av  a 2s. co m
        return null;
    Map<String, Object> row = new HashMap<>();
    DataSource<InputStream> dataSource = context.getDataSource();
    InputStream is = dataSource.getData(context.getResolvedEntityAttribute(URL));
    ContentHandler contentHandler = null;
    Metadata metadata = new Metadata();
    StringWriter sw = new StringWriter();
    try {
        if ("html".equals(format)) {
            contentHandler = getHtmlHandler(sw);
        } else if ("xml".equals(format)) {
            contentHandler = getXmlContentHandler(sw);
        } else if ("text".equals(format)) {
            contentHandler = getTextContentHandler(sw);
        } else if ("none".equals(format)) {
            contentHandler = new DefaultHandler();
        }
    } catch (TransformerConfigurationException e) {
        wrapAndThrow(SEVERE, e, "Unable to create content handler");
    }
    Parser tikaParser = null;
    if (parser.equals(AUTO_PARSER)) {
        tikaParser = new AutoDetectParser(tikaConfig);
    } else {
        tikaParser = context.getSolrCore().getResourceLoader().newInstance(parser, Parser.class);
    }
    try {
        ParseContext context = new ParseContext();
        if ("identity".equals(htmlMapper)) {
            context.set(HtmlMapper.class, IdentityHtmlMapper.INSTANCE);
        }
        if (extractEmbedded) {
            context.set(Parser.class, tikaParser);
        }
        tikaParser.parse(is, contentHandler, metadata, context);
    } catch (Exception e) {
        if (SKIP.equals(onError)) {
            throw new DataImportHandlerException(DataImportHandlerException.SKIP_ROW,
                    "Document skipped :" + e.getMessage());
        }
        wrapAndThrow(SEVERE, e, "Unable to read content");
    }
    IOUtils.closeQuietly(is);
    for (Map<String, String> field : context.getAllEntityFields()) {
        if (!"true".equals(field.get("meta")))
            continue;
        String col = field.get(COLUMN);
        String s = metadata.get(col);
        if (s != null)
            row.put(col, s);
    }
    if (!"none".equals(format))
        row.put("text", sw.toString());
    tryToAddLatLon(metadata, row);
    done = true;
    return row;
}

From source file:org.apereo.portal.portlets.sitemap.SitemapTest.java

@Test
public void testStylesheetCompilation() throws IOException {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    Resource resource = new ClassPathResource(STYLESHEET_LOCATION);
    Source source = new StreamSource(resource.getInputStream(), resource.getURI().toASCIIString());
    try {//from   w ww. j  ava2s  .  c  om
        Transformer transformer = TransformerFactory.newInstance().newTransformer(source);
        transformer.setParameter(SitemapPortletController.USE_TAB_GROUPS, useTabGroups);
        transformer.setParameter(SitemapPortletController.USER_LANG, "en_US");
        transformer.setParameter(XsltPortalUrlProvider.CURRENT_REQUEST, request);
        transformer.setParameter(XsltPortalUrlProvider.XSLT_PORTAL_URL_PROVIDER, this.xsltPortalUrlProvider);

        Source xmlSource = new StreamSource(new ClassPathResource(XML_LOCATION).getFile());
        CharArrayWriter buffer = new CharArrayWriter();
        TransformerUtils.enableIndenting(transformer);
        transformer.transform(xmlSource, new StreamResult(buffer));
        if (logger.isTraceEnabled()) {
            logger.trace("XML: " + new String(buffer.toCharArray()));
        }
    } catch (TransformerConfigurationException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.asimba.utility.xml.XMLUtils.java

/**
 * Create a String representation of the XML-document in the provided DOM Document  
 * @param eDocument DOM representation of the XML document
 * @return String representation of the provided XML document, or null when document 
 *    could not be transformed/*from   w w w . java  2  s .  co  m*/
 * @throws OAException when transformation could not be started
 */
public static String getStringFromDocument(Document eDocument) throws OAException {
    String sResult = null;

    try {
        // Build serializable metadata
        TransformerFactory oTransformerFactory = TransformerFactory.newInstance();
        Transformer oSerializer;
        oSerializer = oTransformerFactory.newTransformer();

        StringWriter oStringWriter = new StringWriter();

        oSerializer.transform(new DOMSource(eDocument), new StreamResult(oStringWriter));

        sResult = oStringWriter.toString();

        return sResult;

    } catch (TransformerConfigurationException e) {
        _oLogger.error("Exception when getting transformer for document transformation: " + e.getMessage());
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } catch (TransformerException e) {
        _oLogger.error("Exception when transforming document to DOM: " + e.getMessage());
        return null;
    }

}

From source file:org.chiba.xml.xforms.ChibaBean.java

public void writeExternal(ObjectOutput objectOutput) throws IOException {
    DefaultSerializer serializer = new DefaultSerializer(this);
    Document serializedForm = serializer.serialize();

    StringWriter stringWriter = new StringWriter();
    Transformer transformer = null;
    StreamResult result = new StreamResult(stringWriter);
    try {/*from  ww w  .  j a  v a2s . co  m*/
        transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.transform(new DOMSource(serializedForm), result);
    } catch (TransformerConfigurationException e) {
        throw new IOException("TransformerConfiguration invalid: " + e.getMessage());
    } catch (TransformerException e) {
        throw new IOException("Error during serialization transform: " + e.getMessage());
    }
    objectOutput.writeUTF(stringWriter.getBuffer().toString());
    objectOutput.flush();
    objectOutput.close();

}

From source file:org.commonjava.maven.galley.maven.parse.XMLInfrastructure.java

public Transformer newTransformer() throws GalleyMavenXMLException {
    try {//from  w  w w  .  ja v a  2  s  . co m

        return transformerFactory.newTransformer();
    } catch (final TransformerConfigurationException e) {
        throw new GalleyMavenXMLException("Failed to create Transformer: %s", e, e.getMessage());
    }
}

From source file:org.deegree.framework.xml.XMLFragment.java

/**
 * Writes the <code>XMLFragment</code> instance to the given <code>Writer</code> using the specified
 * <code>OutputKeys</code>./*from w w  w.ja v a 2  s .co m*/
 * 
 * @param writer
 *            cannot be null
 * @param outputProperties
 *            output properties for the <code>Transformer</code> that is used to serialize the document
 * 
 *            see javax.xml.OutputKeys
 */
public void write(Writer writer, Properties outputProperties) {
    try {
        Source source = new DOMSource(rootElement);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        if (outputProperties != null) {
            transformer.setOutputProperties(outputProperties);
        }
        transformer.transform(source, new StreamResult(writer));
    } catch (TransformerConfigurationException e) {
        LOG.logError(e.getMessage(), e);
        throw new XMLException(e);
    } catch (Exception e) {
        LOG.logError(e.getMessage(), e);
        throw new XMLException(e);
    }
}