List of usage examples for javax.xml.transform ErrorListener ErrorListener
ErrorListener
From source file:org.ambraproject.article.service.XslIngestArchiveProcessor.java
public XslIngestArchiveProcessor() { transformerFactory = new TransformerFactoryImpl(); transformerFactory.setURIResolver(new URLResolver()); transformerFactory.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE); transformerFactory.setAttribute("http://saxon.sf.net/feature/strip-whitespace", "none"); transformerFactory.setErrorListener(new ErrorListener() { public void warning(TransformerException te) { log.warn("Warning received while processing a stylesheet", te); }//from ww w . ja va 2 s .c o m public void error(TransformerException te) { log.warn("Error received while processing a stylesheet", te); } public void fatalError(TransformerException te) { log.warn("Fatal error received while processing a stylesheet", te); } }); xPathUtil = new XPathUtil(); }
From source file:dk.statsbiblioteket.util.xml.XSLT.java
private static ErrorListener getErrorListener() { if (ERRORLISTENER == null) { ERRORLISTENER = new ErrorListener() { @Override/*from www . java 2s . c om*/ public void warning(TransformerException exception) throws TransformerException { warnlog.debug("A transformer warning occured", exception); } @Override public void error(TransformerException exception) throws TransformerException { throw new TransformerException("A Transformer error occured", exception); } @Override public void fatalError(TransformerException exception) throws TransformerException { throw new TransformerException("A Transformer exception occurred", exception); } }; } return ERRORLISTENER; }
From source file:it.cnr.icar.eric.service.catalogingTest.cppaCataloging.CPPACataloging.java
public SOAPElement catalogContent(SOAPElement partCatalogContentRequest) throws RemoteException { try {//from w w w .j a va 2s. c om if (log.isDebugEnabled()) { printNodeToConsole(partCatalogContentRequest); } final HashMap<String, DataHandler> repositoryItemDHMap = getRepositoryItemDHMap(); if (log.isDebugEnabled()) { log.debug("Attachments: " + repositoryItemDHMap.size()); } Object requestObj = getBindingObjectFromNode(partCatalogContentRequest); if (!(requestObj instanceof CatalogContentRequest)) { throw new Exception( "Wrong response received from validation service. Expected CatalogContentRequest, got: " + partCatalogContentRequest.getElementName().getQualifiedName()); } ccReq = (CatalogContentRequest) requestObj; IdentifiableType originalContentIT = ccReq.getOriginalContent().getIdentifiable().get(0).getValue(); IdentifiableType invocationControlIT = ccReq.getInvocationControlFile().get(0); DataHandler invocationControlDH = repositoryItemDHMap.get(invocationControlIT.getId()); if (log.isDebugEnabled()) { log.debug("originalContentIT id: " + originalContentIT.getId()); log.debug("invocationControlIT id: " + invocationControlIT.getId()); } StreamSource invocationControlSrc = new StreamSource(invocationControlDH.getInputStream()); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(invocationControlSrc); transformer.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { Source source = null; try { // Should this check that href is UUID URN first? source = new StreamSource((repositoryItemDHMap.get(href)).getInputStream()); } catch (Exception e) { source = null; } return source; } }); transformer.setErrorListener(new ErrorListener() { public void error(TransformerException exception) throws TransformerException { log.info(exception); } public void fatalError(TransformerException exception) throws TransformerException { log.error(exception); throw exception; } public void warning(TransformerException exception) throws TransformerException { log.info(exception); } }); //Set respository item as parameter transformer.setParameter("repositoryItem", originalContentIT.getId()); StringWriter sw = new StringWriter(); transformer.transform(new JAXBSource(jaxbContext, originalContentIT), new StreamResult(sw)); ccResp = cmsFac.createCatalogContentResponse(); RegistryObjectListType catalogedMetadata = (RegistryObjectListType) getUnmarshaller() .unmarshal(new StreamSource(new StringReader(sw.toString()))); RegistryObjectListType roList = rimFac.createRegistryObjectListType(); ccResp.setCatalogedContent(roList); // FIXME: Setting catalogedMetadata as CatalogedContent results in incorrect serialization. roList.getIdentifiable().addAll(catalogedMetadata.getIdentifiable()); ccResp.setStatus(CANONICAL_RESPONSE_STATUS_TYPE_ID_Success); ccRespElement = getSOAPElementFromBindingObject(ccResp); // Copy request's attachments to response to exercise attachment-processing code on client. MessageContext mc = servletEndpointContext.getMessageContext(); mc.setProperty(com.sun.xml.rpc.server.ServerPropertyConstants.SET_ATTACHMENT_PROPERTY, (Collection<?>) mc .getProperty(com.sun.xml.rpc.server.ServerPropertyConstants.GET_ATTACHMENT_PROPERTY)); } catch (Exception e) { throw new RemoteException("Could not create response.", e); } return ccRespElement; }
From source file:it.cnr.icar.eric.server.cms.CanonicalXMLCatalogingService.java
private Transformer initTransformer(TransformerFactory tFactory, StreamSource invocationControlFileSrc) throws TransformerConfigurationException { Transformer transformer = tFactory.newTransformer(invocationControlFileSrc); transformer.setErrorListener(new ErrorListener() { public void error(TransformerException exception) throws TransformerException { log.info(exception);//from w ww. j a va 2 s . c o m } public void fatalError(TransformerException exception) throws TransformerException { log.error(exception); throw exception; } public void warning(TransformerException exception) throws TransformerException { log.info(exception); } }); return transformer; }
From source file:it.cnr.icar.eric.server.cms.CanonicalXMLFilteringService.java
private static Transformer initTransformer(TransformerFactory tFactory, StreamSource xslt) throws TransformerConfigurationException { Transformer transformer = tFactory.newTransformer(xslt); transformer.setErrorListener(new ErrorListener() { public void error(TransformerException exception) throws TransformerException { log.info(exception);//from w w w .j ava 2 s . c om } public void fatalError(TransformerException exception) throws TransformerException { log.error(exception); throw exception; } public void warning(TransformerException exception) throws TransformerException { log.info(exception); } }); return transformer; }
From source file:it.cnr.icar.eric.server.event.EmailNotifier.java
private String transformContent(ServerRequestContext context, String xsltId, String xmlNotif, String action, String user) throws RegistryException { try {/*from ww w . j av a 2 s . c om*/ RepositoryItem repositoryItem = RepositoryManagerFactory.getInstance().getRepositoryManager() .getRepositoryItem(xsltId); StreamSource xsltIn = new StreamSource(repositoryItem.getDataHandler().getInputStream()); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(xsltIn); //transformer.setURIResolver(rm.getURIResolver()); transformer.setErrorListener(new ErrorListener() { public void error(TransformerException exception) throws TransformerException { log.info(ServerResourceBundle.getInstance().getString("xsltError"), exception); } public void fatalError(TransformerException exception) throws TransformerException { log.error(ServerResourceBundle.getInstance().getString("xsltFatalError"), exception); throw exception; } public void warning(TransformerException exception) throws TransformerException { log.info(ServerResourceBundle.getInstance().getString("xsltWarning"), exception); } }); //Set parameters transformer.setParameter("action", action); transformer.setParameter("user", user); transformer.setParameter("registryBaseURL", RegistryProperties.getInstance().getProperty("eric.registry.baseurl")); ByteArrayInputStream bais = new ByteArrayInputStream(xmlNotif.getBytes("utf-8")); StreamSource inputSrc = new StreamSource(bais); //TODO: use file in case we have a large amount of data to transform? ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamResult streamResult = new StreamResult(baos); transformer.transform(inputSrc, streamResult); return baos.toString("utf-8"); } catch (Exception e) { log.error(ServerResourceBundle.getInstance().getString("message.prettyPrintNotificationFailure"), e); throw new RegistryException(e); } }
From source file:it.cnr.icar.eric.server.cms.CanonicalXMLValidationService.java
private void configureTransformer(Transformer transformer) { transformer.setURIResolver(rm.getURIResolver()); transformer.setErrorListener(new ErrorListener() { public void error(TransformerException exception) throws TransformerException { log.info(exception);/* w w w . j av a 2 s.com*/ } public void fatalError(TransformerException exception) throws TransformerException { log.error(exception); throw exception; } public void warning(TransformerException exception) throws TransformerException { log.info(exception); } }); }
From source file:com.amalto.core.plugin.base.xslt.XSLTTransformerPluginBean.java
/** * @throws XtentisException/*w w w. j av a 2 s .com*/ * * @ejb.interface-method view-type = "local" * @ejb.facade-method */ public void init(TransformerPluginContext context, String compiledParameters) throws XtentisException { try { if (!configurationLoaded) { loadConfiguration(); } // fetech the parameters CompiledParameters parameters = CompiledParameters.deserialize(compiledParameters); // get the xslt compiled style sheet and the Transformer /** * Unfortunately this does not work for the moment PreparedStylesheet preparedStyleSheet * =parameters.getPreparedStyleSheet(); Transformer transformer = preparedStyleSheet.newTransformer(); **/ // As a replacement in the meantime setCompilationErrors(""); //$NON-NLS-1$ // USE SAXON for XSLT 2.0 Support TransformerFactory transFactory = new net.sf.saxon.TransformerFactoryImpl(); transFactory.setErrorListener(new ErrorListener() { public void error(TransformerException exception) throws TransformerException { add2CompilationErrors(exception.getLocalizedMessage()); } public void fatalError(TransformerException exception) throws TransformerException { add2CompilationErrors(exception.getLocalizedMessage()); } public void warning(TransformerException exception) throws TransformerException { String err = "XSLT Plugin: Warning during the compilation of the XSLT"; //$NON-NLS-1$ LOG.warn(err, exception); } }); transFactory.setAttribute(FeatureKeys.VERSION_WARNING, Boolean.valueOf(false)); if (!"".equals(getCompilationErrors())) { //$NON-NLS-1$ String err = "XSLT Plugin: Errors occurred during the compilation of the XSLT:" //$NON-NLS-1$ + getCompilationErrors(); LOG.error(err); throw new XtentisException(err); } Transformer transformer = transFactory .newTransformer(new StreamSource(new StringReader(parameters.getXslt()))); // Pass Parameters to the XSLT processor String username = LocalUser.getLocalUser().getUsername(); transformer.setParameter("USERNAME", username); //$NON-NLS-1$ transformer.setErrorListener(new ErrorListener() { public void error(TransformerException exception) throws TransformerException { String err = "XSLT Plugin: An error occured during the XSLT transformation"; //$NON-NLS-1$ LOG.error(err, exception); throw new TransformerException(err); } public void fatalError(TransformerException exception) throws TransformerException { String err = "XSLT Plugin: A fatal error occured during the XSLT transformation"; //$NON-NLS-1$ LOG.error(err, exception); throw new TransformerException(err); } public void warning(TransformerException exception) throws TransformerException { String err = "XSLT Plugin: Warning during the XSLT transformation"; //$NON-NLS-1$ LOG.warn(err, exception); } }); // Insert all this in the context context.put(TRANSFORMER, transformer); context.put(OUTPUT_METHOD, parameters.getOutputMethod()); } catch (Exception e) { String err = compilationErrors; if (err == null || err.length() == 0) { err = "Could not init the XSLT Plugin"; //$NON-NLS-1$ } LOG.error(err, e); throw new XtentisException(err); } }
From source file:com.amalto.core.plugin.base.xslt.XSLTTransformerPluginBean.java
/** * @throws XtentisException/* w ww . j a va 2s . c o m*/ * * @ejb.interface-method view-type = "local" * @ejb.facade-method */ public void execute(TransformerPluginContext context) throws XtentisException { try { // fetch data from context Transformer transformer = (Transformer) context.get(TRANSFORMER); String outputMethod = (String) context.get(OUTPUT_METHOD); TypedContent xmlTC = (TypedContent) context.get(INPUT_XML); // get the charset String charset = Util.extractCharset(xmlTC.getContentType()); // get the xml String String xml = new String(xmlTC.getContentBytes(), charset); // get the xml parameters TypedContent parametersTC = (TypedContent) context.get(INPUT_PARAMETERS); if (parametersTC != null) { String parametersCharset = Util.extractCharset(parametersTC.getContentType()); byte[] parametersBytes = parametersTC.getContentBytes(); if (parametersBytes != null) { String parameters = new String(parametersBytes, parametersCharset); Document parametersDoc = Util.parse(parameters); NodeList paramList = Util.getNodeList(parametersDoc.getDocumentElement(), "//Parameter"); //$NON-NLS-1$ for (int i = 0; i < paramList.getLength(); i++) { String paramName = Util.getFirstTextNode(paramList.item(i), "Name"); //$NON-NLS-1$ String paramValue = Util.getFirstTextNode(paramList.item(i), "Value"); //$NON-NLS-1$ if (paramValue == null) paramValue = ""; //$NON-NLS-1$ if (paramName != null) { transformer.setParameter(paramName, paramValue); } } } } // FIXME: ARRRRGHHHHHH - How do you prevent the Transformer to process doctype instructions? // Sets the current time transformer.setParameter("TIMESTAMP", getTimestamp()); //$NON-NLS-1$ transformer.setErrorListener(new ErrorListener() { public void error(TransformerException exception) throws TransformerException { transformatioError = exception.getMessage(); } public void fatalError(TransformerException exception) throws TransformerException { transformatioError = exception.getMessage(); } public void warning(TransformerException exception) throws TransformerException { transformationeWarning = exception.getMessage(); } }); transformatioError = null; transformationeWarning = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); if ("xml".equals(outputMethod) || "xhtml".equals(outputMethod)) { //$NON-NLS-1$ //$NON-NLS-2$ DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.newDocument(); DOMResult domResult = new DOMResult(document); transformer.transform(new StreamSource(new StringReader(xml)), domResult); if (transformationeWarning != null) { String err = "Warning processing the XSLT: " + transformationeWarning; //$NON-NLS-1$ LOG.warn(err); } if (transformatioError != null) { String err = "Error processing the XSLT: " + transformatioError; //$NON-NLS-1$ LOG.error(err); throw new XtentisException(err); } Node rootNode = document.getDocumentElement(); // process the cross-referencings NodeList xrefl = Util.getNodeList(rootNode.getOwnerDocument(), "//*[@xrefCluster]"); //$NON-NLS-1$ int len = xrefl.getLength(); for (int i = 0; i < len; i++) { Element xrefe = (Element) xrefl.item(i); xrefe = processMappings(xrefe); } TransformerFactory transFactory = new net.sf.saxon.TransformerFactoryImpl(); Transformer serializer = transFactory.newTransformer(); serializer.setOutputProperty(OutputKeys.METHOD, outputMethod); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$ serializer.transform(new DOMSource(rootNode), new StreamResult(baos)); } else { if (transformationeWarning != null) { String err = "Warning processing the XSLT: " + transformationeWarning; //$NON-NLS-1$ LOG.warn(err); } if (transformatioError != null) { String err = "Error processing the XSLT: " + transformatioError; //$NON-NLS-1$ LOG.error(err); throw new XtentisException(err); } // transform the item transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(baos)); } // Call Back byte[] bytes = baos.toByteArray(); if (LOG.isDebugEnabled()) { LOG.debug("execute() Inserting XSL Result in '" + OUTPUT_TEXT + "'\n" + new String(bytes, "utf-8")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } context.put(OUTPUT_TEXT, new TypedContent(bytes, ("xhtml".equals(outputMethod) ? "application/xhtml+xml" //$NON-NLS-1$//$NON-NLS-2$ : "text/" //$NON-NLS-1$ + outputMethod) + "; charset=utf-8")); //$NON-NLS-1$ context.getPluginCallBack().contentIsReady(context); } catch (Exception e) { String err = "Could not start the XSLT plugin"; //$NON-NLS-1$ LOG.error(err, e); throw new XtentisException(err); } }
From source file:org.ambraproject.article.service.XslIngestArchiveProcessor.java
/** * Run the zip file through the xsl stylesheet * * @param zip the zip archive containing the items to ingest * @param zipInfo the document describing the zip archive (adheres to zip.dtd) * @param articleXml the stylesheet to run on <var>zipInfo</var>; this is the main script * @param doiUrlPrefix DOI URL prefix// ww w. j av a2 s.com * @return a document describing the fedora objects to create (must adhere to fedora.dtd) * @throws javax.xml.transform.TransformerException * if an error occurs during the processing */ private Document transformZip(ZipFile zip, String zipInfo, Document articleXml, String doiUrlPrefix) throws TransformerException, URISyntaxException { Transformer t = getTranslet(articleXml); t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); t.setURIResolver(new ZipURIResolver(zip)); // override the doi url prefix if one is specified in the config if (doiUrlPrefix != null) t.setParameter("doi-url-prefix", doiUrlPrefix); /* * Note: it would be preferable (and correct according to latest JAXP specs) to use * t.setErrorListener(), but Saxon does not forward <xls:message>'s to the error listener. * Hence we need to use Saxon's API's in order to get at those messages. */ final StringWriter msgs = new StringWriter(); MessageWarner em = new MessageWarner(); ((Controller) t).setMessageEmitter(em); t.setErrorListener(new ErrorListener() { public void warning(TransformerException te) { log.warn("Warning received while processing zip", te); } public void error(TransformerException te) { log.warn("Error received while processing zip", te); msgs.write(te.getMessageAndLocation() + '\n'); } public void fatalError(TransformerException te) { log.warn("Fatal error received while processing zip", te); msgs.write(te.getMessageAndLocation() + '\n'); } }); Source inp = new StreamSource(new StringReader(zipInfo), "zip:/"); DOMResult res = new DOMResult(); try { t.transform(inp, res); } catch (TransformerException te) { if (msgs.getBuffer().length() > 0) { log.error(msgs.getBuffer().toString()); throw new TransformerException(msgs.toString(), te); } else throw te; } if (msgs.getBuffer().length() > 0) throw new TransformerException(msgs.toString()); return (Document) res.getNode(); }