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:com.ephesoft.dcma.ibm.IBMCMExporter.java

private void updateDocumentOffsetValue(final String batchInstanceID, final String filePath)
        throws DCMAApplicationException {
    try {//  w  w  w.ja v a 2 s.  c o m
        org.w3c.dom.Document document = XMLUtil.createDocumentFrom(new File(filePath));
        NodeList documentList = document.getElementsByTagName(IBMCMConstant.DOCUMENT);
        for (int documentIndex = 0; documentIndex < documentList.getLength(); documentIndex++) {
            Element documentTag = (Element) documentList.item(documentIndex);
            Element docTag = (Element) documentTag.getElementsByTagName(IBMCMConstant.DOC_ID).item(0);
            Element offset = (Element) documentTag.getElementsByTagName(IBMCMConstant.OFFSET).item(0);
            String docIdentifier = docTag.getTextContent();
            if (docIdentifier != null & !docIdentifier.isEmpty()) {
                offset.setTextContent(String.valueOf(getOffsetValue(batchInstanceID, docIdentifier)));
            }
        }
        Source source = new DOMSource(document);
        File batchXmlFile = new File(filePath);
        OutputStream outputStream = new FileOutputStream(batchXmlFile);
        Result result = new StreamResult(outputStream);
        Transformer xformer = null;
        try {
            xformer = TransformerFactory.newInstance().newTransformer();
        } catch (TransformerConfigurationException e) {
            String msg = "Exception in transforming configuration file";
            LOGGER.error(msg + e.getMessage(), e);
            throw new DCMAApplicationException(msg + e.getMessage(), e);
        } catch (TransformerFactoryConfigurationError e) {
            String msg = "Exception in transforming factory file";
            LOGGER.error(msg + e.getMessage(), e);
            throw new DCMAApplicationException(msg + e.getMessage(), e);
        }
        try {
            xformer.transform(source, result);
        } catch (TransformerException e) {
            String msg = "Exception in transforming file";
            LOGGER.error(msg + e.getMessage(), e);
            throw new DCMAApplicationException(msg + e.getMessage(), e);
        }
    } catch (Exception e) {
        String msg = "Exception in updating offset into file";
        LOGGER.error(msg + e.getMessage(), e);
        throw new DCMAApplicationException(msg + e.getMessage(), e);
    }
}

From source file:de.betterform.xml.xforms.XFormsProcessorImpl.java

public void writeExternal(ObjectOutput objectOutput) throws IOException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("serializing XFormsFormsProcessorImpl");
    }/*from   w  w  w.  j ava  2s .co m*/
    try {
        if (getXForms().getDocumentElement().hasAttribute("bf:serialized")) {
            objectOutput.writeUTF(DOMUtil.serializeToString(getXForms()));
        } else {
            getXForms().getDocumentElement().setAttributeNS(NamespaceConstants.BETTERFORM_NS, "bf:baseURI",
                    getBaseURI());
            getXForms().getDocumentElement().setAttributeNS(NamespaceConstants.BETTERFORM_NS, "bf:serialized",
                    "true");

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("....::: XForms before writing ::::....");
                DOMUtil.prettyPrintDOM(getXForms());
            }

            DefaultSerializer serializer = new DefaultSerializer(this);
            Document serializedForm = serializer.serialize();

            StringWriter stringWriter = new StringWriter();
            Transformer transformer = null;
            StreamResult result = new StreamResult(stringWriter);
            try {
                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());
        }
    } catch (XFormsException e) {
        throw new IOException("baseURI couldn't be set");
    }

    objectOutput.flush();
    objectOutput.close();

}

From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.knx.KNXDeviceLoaderETSImpl.java

public ArrayList<Connector> initDevices(ObjectBroker objectBroker) {
    log.info("KNX ETS device loader starting. - connectorsConfig: " + connectorsConfig);
    setConfiguration(connectorsConfig);//  ww  w. j  a  v  a  2 s  .c o  m

    ArrayList<Connector> connectors = new ArrayList<Connector>();

    log.info("connectors config now: " + connectorsConfig);
    Object knxConnectors = connectorsConfig.getProperty("knx-ets.connector.name");

    int connectorsSize = 0;

    if (knxConnectors != null) {
        connectorsSize = 1;
    }

    if (knxConnectors instanceof Collection<?>) {
        connectorsSize = ((Collection<?>) knxConnectors).size();
    }

    // Networks
    List networks = new List();
    networks.setName("networks");
    networks.setOf(new Contract(Network.CONTRACT));
    networks.setHref(new Uri("/networks"));

    boolean networkEnabled = false;

    for (int connector = 0; connector < connectorsSize; connector++) {
        HierarchicalConfiguration subConfig = connectorsConfig
                .configurationAt("knx-ets.connector(" + connector + ")");

        // String connectorName = subConfig.getString("name");
        String routerIP = subConfig.getString("router.ip");
        int routerPort = subConfig.getInteger("router.port", 3671);
        String localIP = subConfig.getString("localIP");
        Boolean enabled = subConfig.getBoolean("enabled", false);
        Boolean forceRefresh = subConfig.getBoolean("forceRefresh", false);
        String knxProj = subConfig.getString("knx-proj");

        Boolean enableGroupComm = subConfig.getBoolean("groupCommEnabled", false);

        Boolean enableHistories = subConfig.getBoolean("historyEnabled", false);

        if (enabled) {
            if (!networkEnabled) {
                objectBroker.addObj(networks, true);
                networkEnabled = true;
            }
            File file = new File(knxProj);

            if (!file.exists() || file.isDirectory() || !file.getName().endsWith(".knxproj")
                    || file.getName().length() < 8) {
                log.warning("KNX project file " + knxProj + " is not a valid KNX project file.");
                continue;
            }

            String projDirName = knxProj.substring(0, knxProj.length() - 8);

            File projDir = new File(projDirName);

            if (!projDir.exists() || forceRefresh) {
                log.info("Expanding " + knxProj + " into directory " + projDirName);
                unZip(knxProj, projDirName);
            }

            String directory = "./" + knxProj.substring(knxProj.indexOf("/") + 1).replaceFirst(".knxproj", "");

            // now the unpacked ETS project should be available in the directory
            String transformFileName = knxProj.replaceFirst(".knxproj", "") + "/"
                    + file.getName().replaceFirst(".knxproj", "") + ".xml";

            File transformFile = new File(transformFileName);

            if (!transformFile.exists() || forceRefresh) {
                log.info("Transforming ETS configuration.");
                //               System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
                // Create a transform factory instance.
                TransformerFactory tfactory = TransformerFactory.newInstance();

                // Create a transformer for the stylesheet.
                Transformer transformer;

                try {
                    transformer = tfactory.newTransformer(new StreamSource("knx-config/stylesheet_knx.xsl"));
                    Collection<File> listFiles = FileUtils.listFiles(projDir,
                            FileFilterUtils.nameFileFilter("0.xml"), new IOFileFilter() {

                                @Override
                                public boolean accept(File file) {
                                    return true;
                                }

                                @Override
                                public boolean accept(File dir, String name) {
                                    return true;
                                }

                            });
                    if (listFiles.size() != 1) {
                        log.severe("Found no or more than one 0.xml file in " + projDirName);
                        continue;
                    }

                    log.info("Transforming with directory parameter set to " + directory);

                    transformer.setParameter("directory", directory);
                    transformer.transform(new StreamSource(listFiles.iterator().next().getAbsoluteFile()),
                            new StreamResult(transformFileName));

                    log.info("Transformation completed and result written to: " + transformFileName);
                } catch (TransformerConfigurationException e) {
                    e.printStackTrace();
                } catch (TransformerException e) {
                    e.printStackTrace();
                }
            }

            try {
                devicesConfig = new XMLConfiguration(transformFileName);
            } catch (Exception e) {
                log.log(Level.SEVERE, e.getMessage(), e);
            }

            KNXConnector knxConnector = new KNXConnector(routerIP, routerPort, localIP);

            connect(knxConnector);

            initNetworks(knxConnector, objectBroker, networks, enableGroupComm, enableHistories);

            connectors.add(knxConnector);
        }
    }

    return connectors;
}

From source file:com.krawler.formbuilder.servlet.workflowHandler.java

public String exportBPELFile(HttpServletRequest request, HttpServletResponse response) {
    Writer output = null;//from  w w w  .j ava 2 s . c  om
    try {
        String workflow = request.getParameter("jsonnodeobj");
        String linejson = request.getParameter("linejson");
        String processId = request.getParameter("flowid");
        String containerId = request.getParameter("containerId");
        this.parentSplit = request.getParameter("parentSplit");
        String path = ConfigReader.getinstance().get("workflowpath") + processId;
        path = path + System.getProperty("file.separator") + "Export";
        File fdir = new File(path);
        if (!fdir.exists()) {
            fdir.mkdirs();
        }
        File file = new File(fdir + System.getProperty("file.separator") + "flow.bpel");
        if (file.exists()) {
            file.delete();
        }
        output = new BufferedWriter(new FileWriter(file));
        JSONObject jsonobj = new JSONObject(workflow);
        JSONObject json_line = new JSONObject(linejson);
        createDocument();
        expwritebpel(jsonobj, containerId, processId, json_line);
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans1 = transfac.newTransformer();
        trans1.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans1.setOutputProperty(OutputKeys.INDENT, "yes");

        StringWriter sw = new StringWriter();
        StreamResult kwcresult = new StreamResult(sw);
        DOMSource kwcsource = new DOMSource(dom);
        trans1.transform(kwcsource, kwcresult);
        output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        output.write("\n");
        output.write(sw.toString());

        output.close();
        return "{success:true}";
    } catch (TransformerConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
        return "{success:true}";
    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
        return "{success:true}";
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
        return "{success:true}";
    } catch (JSONException ex) {
        logger.warn(ex.getMessage(), ex);
        return "{success:true}";
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
        return "{success:true}";
    } finally {
        try {
            output.close();
        } catch (IOException ex) {
            logger.warn(ex.getMessage(), ex);
            return "{success:true}";
        }
    }

}

From source file:eu.eidas.auth.engine.core.stork.StorkProtocolProcessor.java

private String extractEDocValue(final XSAnyImpl xmlString) {
    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = null;
    try {/* w  ww. j av  a2 s .co  m*/
        transformer = transFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    } catch (TransformerConfigurationException e) {
        LOG.warn(AbstractProtocolEngine.SAML_EXCHANGE, "Error transformer configuration exception",
                e.getMessage());
        LOG.debug(AbstractProtocolEngine.SAML_EXCHANGE, "Error transformer configuration exception", e);
    }
    StringWriter buffer = new StringWriter();
    try {
        if (transformer != null && xmlString != null && xmlString.getUnknownXMLObjects() != null
                && !xmlString.getUnknownXMLObjects().isEmpty()) {
            transformer.transform(new DOMSource(xmlString.getUnknownXMLObjects().get(0).getDOM()),
                    new StreamResult(buffer));
        }
    } catch (TransformerException e) {
        LOG.info(AbstractProtocolEngine.SAML_EXCHANGE, "BUSINESS EXCEPTION : Error transformer exception",
                e.getMessage());
        LOG.debug(AbstractProtocolEngine.SAML_EXCHANGE, "BUSINESS EXCEPTION : Error transformer exception", e);
    }
    return buffer.toString();
}

From source file:eu.eidas.auth.engine.core.stork.StorkExtensionProcessor.java

private String extractEDocValue(final XSAnyImpl xmlString) {
    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = null;
    try {//from w  ww. j  a  v  a2  s. c o  m
        transformer = transFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    } catch (TransformerConfigurationException e) {
        LOG.warn(AbstractProtocolEngine.SAML_EXCHANGE, "Error transformer configuration exception",
                e.getMessage());
        LOG.debug(AbstractProtocolEngine.SAML_EXCHANGE, "Error transformer configuration exception", e);
    }
    StringWriter buffer = new StringWriter();
    try {
        if (transformer != null && xmlString != null && xmlString.getUnknownXMLObjects() != null
                && !xmlString.getUnknownXMLObjects().isEmpty()) {
            transformer.transform(new DOMSource(xmlString.getUnknownXMLObjects().get(0).getDOM()),
                    new StreamResult(buffer));
        }
    } catch (TransformerException e) {
        LOG.info(AbstractProtocolEngine.SAML_EXCHANGE, "BUSINESS EXCEPTION : Error transformer exception",
                e.getMessage());
        LOG.debug(AbstractProtocolEngine.SAML_EXCHANGE, "BUSINESS EXCEPTION : Error transformer exception", e);
    }
    return buffer.toString();

}

From source file:it.imtech.metadata.MetaUtility.java

/**
 * Metodo adibito all'esportazione dei metadati su oggetto Document a
 * partire dai valori dell'interfaccia/*from   ww  w.j ava 2  s.  co m*/
 *
 * @param pid PID del libro durante upload
 * @param pagenum Numero pagina corrente di esportazione
 * @param objectDefaultValues Valori di default durante upload
 * @return Oggetto xml contenente i metadati inseriti nei campi
 * dell'interfaccia
 * @throws Exception
 */
public Document create_uwmetadata(String pid, int pagenum, HashMap<String, String> objectDefaultValues,
        String collTitle, String panelname) throws Exception {
    String xmlFile = "";

    if (objectDefaultValues != null) {
        this.objectDefaultValues = objectDefaultValues;
    }

    StreamResult result = new StreamResult(new StringWriter());

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // set the factory to be namespace aware
    factory.setNamespaceAware(true);

    // create the xml document builder object and get the DOMImplementation object
    DocumentBuilder builder = factory.newDocumentBuilder();
    DOMImplementation domImpl = builder.getDOMImplementation();
    Document xmlDoc = domImpl.createDocument("http://phaidra.univie.ac.at/XML/metadata/V1.0", "ns0:uwmetadata",
            null);

    try {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        t.setOutputProperty(OutputKeys.STANDALONE, "");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        // get the root element
        Element rootElement = xmlDoc.getDocumentElement();

        //Add namespaces in XML Root
        for (Map.Entry<String, String> field : metadata_namespaces.entrySet()) {
            rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + field.getKey().toString(),
                    field.getValue().toString());
        }
        create_uwmetadata_recursive(xmlDoc, rootElement, BookImporter.getInstance().getMetadata(),
                this.objectDefaultValues, pagenum, collTitle, panelname);
    } catch (TransformerConfigurationException e) {
    } catch (Exception e) {
        throw new Exception(e.getMessage());
    }

    return xmlDoc;
}

From source file:com.ephesoft.gxt.systemconfig.server.SystemConfigServiceImpl.java

private void addPathToApplicationContext(String pluginApplicationContextPath) throws UIException {
    StringBuffer applicationContextFilePathBuffer = new StringBuffer(
            System.getenv(SystemConfigSharedConstants.DCMA_HOME));
    applicationContextFilePathBuffer.append(File.separator);
    applicationContextFilePathBuffer.append(SystemConfigSharedConstants.APPLICATION_CONTEXT_PATH_XML);
    String applicationContextFilePath = applicationContextFilePathBuffer.toString();
    File applicationContextFile = new File(applicationContextFilePath);
    LOGGER.info("Making entry for " + pluginApplicationContextPath + " in the application context file at: "
            + applicationContextFilePath);
    try {/* w  w  w . j a  v  a 2s.com*/
        Document xmlDocument = XMLUtil.createDocumentFrom(applicationContextFile);

        NodeList beanTags = xmlDocument.getElementsByTagName(SystemConfigSharedConstants.BEANS_TAG);
        if (beanTags != null) {
            String searchTag = SystemConfigSharedConstants.BEANS_TAG;
            // Get the 1st bean node from
            Node beanNode = getFirstNodeOfType(beanTags, searchTag);

            Node importNodesClone = null;

            NodeList beanChildNodes = beanNode.getChildNodes();
            searchTag = SystemConfigSharedConstants.IMPORT_TAG;
            importNodesClone = getFirstNodeOfType(beanChildNodes, searchTag);
            Node cloneNode = importNodesClone.cloneNode(true);
            cloneNode.getAttributes().getNamedItem(SystemConfigSharedConstants.RESOURCE).setTextContent(
                    SystemConfigSharedConstants.CLASSPATH_META_INF + pluginApplicationContextPath);
            beanNode.insertBefore(cloneNode, importNodesClone);

            Source source = new DOMSource(xmlDocument);

            File batchXmlFile = new File(applicationContextFilePath);

            Result result = new StreamResult(batchXmlFile);

            Transformer xformer = null;
            try {
                xformer = TransformerFactory.newInstance().newTransformer();
                xformer.setOutputProperty(OutputKeys.INDENT, SystemConfigSharedConstants.YES);
                xformer.setOutputProperty(SystemConfigSharedConstants.XML_INDENT_AMOUNT, String.valueOf(2));

            } catch (TransformerConfigurationException e) {
                String errorMsg = SystemConfigSharedConstants.APPLICATION_CONTEXT_ENTRY_ERROR_MESSAGE;
                LOGGER.error(errorMsg + e.getMessage(), e);
                throw new UIException(errorMsg);
            } catch (TransformerFactoryConfigurationError e) {
                String errorMsg = SystemConfigSharedConstants.APPLICATION_CONTEXT_ENTRY_ERROR_MESSAGE;
                LOGGER.error(errorMsg + e.getMessage(), e);
                throw new UIException(errorMsg);
            }
            try {
                xformer.transform(source, result);
            } catch (TransformerException e) {
                String errorMsg = SystemConfigSharedConstants.APPLICATION_CONTEXT_ENTRY_ERROR_MESSAGE;
                LOGGER.error(errorMsg + e.getMessage(), e);
                throw new UIException(errorMsg);
            }
            LOGGER.info("Application Context Entry made successfully.");
        }
    } catch (Exception e) {
        String errorMsg = SystemConfigSharedConstants.APPLICATION_CONTEXT_ENTRY_ERROR_MESSAGE;
        LOGGER.error(errorMsg + e.getMessage());
        throw new UIException(errorMsg);
    }
}

From source file:org.alfresco.repo.template.XSLTProcessor.java

/**
 * @param templateSource/* w  ww  .  ja v a2s  .  c  o  m*/
 * @param model
 * @param out
 */
private void process(TemplateSource templateSource, Object model, Writer out) {
    if ((model == null) || !XSLTemplateModel.class.isAssignableFrom(model.getClass())) {
        throw new IllegalArgumentException("\"model\" must be an XSLTemplateModel object: " + model);
    }

    XSLTemplateModel xsltModel = (XSLTemplateModel) model;
    System.setProperty("org.apache.xalan.extensions.bsf.BSFManager", BSFManager.class.getName());

    Document xslTemplate;
    try {
        xslTemplate = XMLUtil.parse(templateSource.getReader(defaultEncoding));
    } catch (IOException ex) {
        throw new TemplateException(MSG_UNABLE_TO_READ_TEMPLATE, new Object[] { ex.getMessage() }, ex);
    } catch (SAXException sax) {
        throw new TemplateException(MSG_UNABLE_TO_PARSE_TEMPLATE, new Object[] { sax.getMessage() }, sax);
    } finally {
        try {
            templateSource.close();
        } catch (IOException ex) {
            // There's little to be done here. Log it and carry on
            log.warn("Error while trying to close template stream", ex);
        }
    }

    List<String> scriptIds = addScripts(xsltModel, xslTemplate);
    addParameters(xsltModel, xslTemplate);

    final LinkedList<TransformerException> errors = new LinkedList<TransformerException>();
    final ErrorListener errorListener = new ErrorListener() {
        public void error(final TransformerException te) throws TransformerException {
            log.debug("error " + te.getMessageAndLocation());
            errors.add(te);
        }

        public void fatalError(final TransformerException te) throws TransformerException {
            log.debug("fatalError " + te.getMessageAndLocation());
            throw te;
        }

        public void warning(final TransformerException te) throws TransformerException {
            log.debug("warning " + te.getMessageAndLocation());
            errors.add(te);
        }
    };

    final TemplateSource resourceSource = templateSource;
    final URIResolver uriResolver = new URIResolver() {
        public Source resolve(final String href, String base) throws TransformerException {
            if (log.isDebugEnabled()) {
                log.debug("request to resolve href " + href + " using base " + base);
            }
            InputStream in = null;
            try {
                in = resourceSource.getResource(href);
                if (in == null) {
                    throw new TransformerException("unable to resolve href " + href);
                }

                Document d = XMLUtil.parse(in);
                if (log.isDebugEnabled()) {
                    log.debug("loaded " + XMLUtil.toString(d));
                }
                return new DOMSource(d);
            } catch (TransformerException ex) {
                throw ex;
            } catch (Exception e) {
                throw new TransformerException("unable to load " + href, e);
            }
        }
    };

    Source xmlSource = this.getXMLSource(xsltModel);

    Transformer t = null;
    try {
        final TransformerFactory tf = TransformerFactory.newInstance();
        tf.setErrorListener(errorListener);
        tf.setURIResolver(uriResolver);

        if (log.isDebugEnabled()) {
            log.debug("xslTemplate: \n" + XMLUtil.toString(xslTemplate));
        }

        t = tf.newTransformer(new DOMSource(xslTemplate));

        if (errors.size() != 0) {
            final StringBuilder msg = new StringBuilder("errors encountered creating tranformer ... \n");
            for (TransformerException te : errors) {
                msg.append(te.getMessageAndLocation()).append("\n");
            }
            throw new TemplateException(msg.toString());
        }

        t.setErrorListener(errorListener);
        t.setURIResolver(uriResolver);
        t.setParameter("versionParam", "2.0");
    } catch (TransformerConfigurationException tce) {
        log.error(tce);
        throw new TemplateException(tce.getMessage(), tce);
    }

    try {
        t.transform(xmlSource, new StreamResult(out));
    } catch (TransformerException te) {
        log.error(te.getMessageAndLocation());
        throw new TemplateException(te.getMessageAndLocation(), te);
    } catch (Exception e) {
        log.error("unexpected error " + e);
        throw new TemplateException(e.getMessage(), e);
    } finally {
        //Clear out any scripts that were created for this transform
        if (!scriptIds.isEmpty()) {
            XSLTProcessorMethodInvoker.removeMethods(scriptIds);
        }
    }

    if (errors.size() != 0) {
        final StringBuilder msg = new StringBuilder("errors encountered during transformation ... \n");
        for (TransformerException te : errors) {
            msg.append(te.getMessageAndLocation()).append("\n");
        }
        throw new TemplateException(msg.toString());
    }
}

From source file:org.ambraproject.service.xml.XMLServiceImpl.java

/**
 * Initialization method called by Spring.
 *
 * @throws org.ambraproject.ApplicationException On Template creation Exceptions.
 *//*w w w.  ja v  a2 s  .c  o m*/
public void init() throws ApplicationException {
    // set JAXP properties
    System.getProperties().putAll(xmlFactoryProperty);

    // Create a document builder factory and set the defaults
    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);

    // set the Templates
    final TransformerFactory tFactory = TransformerFactory.newInstance();

    //Because we have XSL sheets with import statements.  I override the URI resolver
    //here so the factory knows to look inside the jar files for these files
    tFactory.setURIResolver(new XMLServiceURIResolver());

    try {
        log.debug("Loading XSL: {}", xslDefaultTemplate);
        translet = tFactory.newTemplates(getResourceAsStreamSource(xslDefaultTemplate));
    } catch (TransformerConfigurationException ex) {
        throw new ApplicationException(ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new ApplicationException(ex.getMessage(), ex);
    }
}