List of usage examples for javax.xml.transform TransformerConfigurationException getMessage
public String getMessage()
From source file:org.deegree.framework.xml.XMLFragment.java
/** * Writes the <code>XMLFragment</code> instance to the given <code>OutputStream</code> using the specified * <code>OutputKeys</code> which allow complete control of the generated output. * /*from w w w. j ava 2 s . co m*/ * @param os * cannot be null * @param outputProperties * output properties for the <code>Transformer</code> used to serialize the document * * @see javax.xml.transform.OutputKeys */ public void write(OutputStream os, Properties outputProperties) { try { Source source = new DOMSource(rootElement); Transformer transformer = TransformerFactory.newInstance().newTransformer(); if (outputProperties != null) { transformer.setOutputProperties(outputProperties); } transformer.transform(source, new StreamResult(os)); } catch (TransformerConfigurationException e) { LOG.logError(e.getMessage(), e); throw new XMLException(e); } catch (Exception e) { LOG.logError(e.getMessage(), e); throw new XMLException(e); } }
From source file:org.displaytag.export.FopExportView.java
/** * Don't forget to enable debug if you want to see the raw FO. * * @param out output writer/*from w w w . jav a 2 s .c o m*/ * @throws IOException Signals that an I/O exception has occurred. * @throws JspException the jsp exception */ @Override public void doExport(OutputStream out) throws IOException, JspException { String xmlResults = getXml(); FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI()); Source xslt = new StreamSource(getStyleSheet()); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer; try { transformer = factory.newTransformer(xslt); } catch (TransformerConfigurationException e) { throw new JspException("Cannot configure pdf export " + e.getMessage(), e); //$NON-NLS-1$ } boolean outputForDebug = log.isDebugEnabled(); if (outputForDebug) { logXsl(xmlResults, transformer, null); } Fop fop; try { fop = fopFactory.newFop(org.apache.xmlgraphics.util.MimeConstants.MIME_PDF, out); } catch (FOPException e) { throw new JspException("Cannot configure pdf export " + e.getMessage(), e); //$NON-NLS-1$ } StreamSource src = new StreamSource(new StringReader(xmlResults)); Result res; try { res = new SAXResult(fop.getDefaultHandler()); } catch (FOPException e) { throw new JspException("error setting up transform ", e); //$NON-NLS-1$ } try { transformer.transform(src, res); } catch (TransformerException e) { if (e.getCause() instanceof ValidationException) { // recreate the errant fo ValidationException ve = (ValidationException) e.getCause(); logXsl(xmlResults, transformer, ve); } else { throw new JspException("error creating pdf output", e); //$NON-NLS-1$ } } }
From source file:org.displaytag.export.FopExportView.java
/** * If you are authoring a stylesheet locally, this is highly recommended as a way to test your stylesheet against * dummy data.//from w ww. j av a 2 s. c o m * * @param xmlSrc xml as string * @param styleSheetPath the path to the stylesheet * @param f the f * @throws Exception if trouble */ public static void transform(String xmlSrc, String styleSheetPath, File f) throws Exception { FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI()); InputStream styleSheetStream = FopExportView.class.getResourceAsStream(styleSheetPath); Source xslt = new StreamSource(styleSheetStream); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer; try { transformer = factory.newTransformer(xslt); } catch (TransformerConfigurationException e) { throw new JspException("Cannot configure pdf export " + e.getMessage(), e); //$NON-NLS-1$ } Fop fop; try { FileOutputStream fw = new FileOutputStream(f); fop = fopFactory.newFop(org.apache.xmlgraphics.util.MimeConstants.MIME_PDF, fw); } catch (FOPException e) { throw new JspException("Cannot configure pdf export " + e.getMessage(), e); //$NON-NLS-1$ } Source src = new StreamSource(new StringReader(xmlSrc)); Result res; try { res = new SAXResult(fop.getDefaultHandler()); } catch (FOPException e) { throw new JspException("error setting up transform ", e); //$NON-NLS-1$ } try { transformer.transform(src, res); } catch (TransformerException e) { throw new JspException("error creating pdf output " + e.getMessage(), e); //$NON-NLS-1$ } }
From source file:org.dspace.license.CreativeCommonsServiceImpl.java
@Override public void afterPropertiesSet() throws Exception { // if defined, set a proxy server for http requests to Creative // Commons site String proxyHost = configurationService.getProperty("http.proxy.host"); String proxyPort = configurationService.getProperty("http.proxy.port"); if (StringUtils.isNotBlank(proxyHost) && StringUtils.isNotBlank(proxyPort)) { System.setProperty("http.proxyHost", proxyHost); System.setProperty("http.proxyPort", proxyPort); }// w w w. j a v a 2 s.com try { templates = TransformerFactory.newInstance().newTemplates( new StreamSource(CreativeCommonsServiceImpl.class.getResourceAsStream("CreativeCommons.xsl"))); } catch (TransformerConfigurationException e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:org.dspace.xoai.tests.util.XSLPipelineTest.java
protected Transformer identityTransformer() { try {/*from w w w. j a va 2 s . c o m*/ return tFactory.newTransformer(); } catch (TransformerConfigurationException e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:org.eclipse.winery.common.Util.java
public static String getXMLAsString(Element el) { TransformerFactory tf = TransformerFactory.newInstance(); Transformer t;/* w w w. j a va 2 s. co m*/ try { t = tf.newTransformer(); } catch (TransformerConfigurationException e) { throw new IllegalStateException("Could not instantiate Transformer", e); } t.setOutputProperty(OutputKeys.INDENT, "yes"); Source source = new DOMSource(el); ByteArrayOutputStream os = new ByteArrayOutputStream(); Result target = new StreamResult(os); try { t.transform(source, target); } catch (TransformerException e) { Util.logger.debug(e.getMessage(), e); throw new IllegalStateException("Could not transform dom node to string", e); } return os.toString(); }
From source file:org.eclipse.winery.repository.export.CSARExporter.java
/** * Writes a complete CSAR containing all necessary things reachable from the given service * template/*from w w w. j a v a 2 s. co m*/ * * @param id the id of the service template to export * @param out the outputstream to write to * @throws JAXBException */ public void writeCSAR(TOSCAComponentId entryId, OutputStream out) throws ArchiveException, IOException, XMLStreamException, JAXBException { CSARExporter.logger.trace("Starting CSAR export with {}", entryId.toString()); Map<RepositoryFileReference, String> refMap = new HashMap<RepositoryFileReference, String>(); Collection<String> definitionNames = new ArrayList<>(); final ArchiveOutputStream zos = new ArchiveStreamFactory().createArchiveOutputStream("zip", out); TOSCAExportUtil exporter = new TOSCAExportUtil(); Map<String, Object> conf = new HashMap<>(); ExportedState exportedState = new ExportedState(); TOSCAComponentId currentId = entryId; do { String defName = CSARExporter.getDefinitionsPathInsideCSAR(currentId); definitionNames.add(defName); zos.putArchiveEntry(new ZipArchiveEntry(defName)); Collection<TOSCAComponentId> referencedIds; try { referencedIds = exporter.exportTOSCA(currentId, zos, refMap, conf, null); } catch (IllegalStateException e) { // thrown if something went wrong inside the repo out.close(); // we just rethrow as there currently is no error stream. throw e; } zos.closeArchiveEntry(); exportedState.flagAsExported(currentId); exportedState.flagAsExportRequired(referencedIds); currentId = exportedState.pop(); } while (currentId != null); // if we export a ServiceTemplate, data for the self-service portal might exist if (entryId instanceof ServiceTemplateId) { this.addSelfServiceMetaData((ServiceTemplateId) entryId, refMap); } // now, refMap contains all files to be added to the CSAR // write manifest directly after the definitions to have it more at the beginning of the ZIP // rather than having it at the very end this.addManifest(entryId, definitionNames, refMap, zos); // used for generated XSD schemas TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer; try { transformer = tFactory.newTransformer(); } catch (TransformerConfigurationException e1) { CSARExporter.logger.debug(e1.getMessage(), e1); throw new IllegalStateException("Could not instantiate transformer", e1); } // write all referenced files for (RepositoryFileReference ref : refMap.keySet()) { String archivePath = refMap.get(ref); archivePath = replaceBPMN4Tosca2BPELPath(archivePath, ref.getFileName(), entryId); ref = replaceBPMN4Tosca2BPELRef(archivePath, ref); CSARExporter.logger.trace("Creating {}", archivePath); ArchiveEntry archiveEntry = new ZipArchiveEntry(archivePath); zos.putArchiveEntry(archiveEntry); if (ref instanceof DummyRepositoryFileReferenceForGeneratedXSD) { CSARExporter.logger.trace("Special treatment for generated XSDs"); Document document = ((DummyRepositoryFileReferenceForGeneratedXSD) ref).getDocument(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(zos); try { transformer.transform(source, result); } catch (TransformerException e) { CSARExporter.logger.debug("Could not serialize generated xsd", e); } } else { try (InputStream is = Repository.INSTANCE.newInputStream(ref)) { IOUtils.copy(is, zos); } catch (Exception e) { CSARExporter.logger.error("Could not copy file content to ZIP outputstream", e); } } zos.closeArchiveEntry(); } this.addNamespacePrefixes(zos); deleteFiles(tempFiles.toArray(new File[tempFiles.size()])); zos.finish(); zos.close(); }
From source file:org.eclipse.winery.repository.export.ZipExporter.java
/** * Writes a complete CSAR containing all necessary things reachable from the given service * template//from w ww.j a v a 2 s . c o m * * @param id the id of the service template to export * @param out the outputstream to write to * @throws JAXBException */ public void writeZip(TOSCAComponentId entryId, OutputStream out) throws ArchiveException, IOException, XMLStreamException, JAXBException { ZipExporter.logger.trace("Starting CSAR export with {}", entryId.toString()); Map<RepositoryFileReference, String> refMap = new HashMap<RepositoryFileReference, String>(); Collection<String> definitionNames = new ArrayList<>(); final ArchiveOutputStream zos = new ArchiveStreamFactory().createArchiveOutputStream("zip", out); TOSCAExportUtil exporter = new TOSCAExportUtil(); Map<String, Object> conf = new HashMap<>(); ExportedState exportedState = new ExportedState(); TOSCAComponentId currentId = entryId; do { logger.info("begin to scan class:" + System.currentTimeMillis()); Reflections reflections = new Reflections("org.eclipse.winery.repository.ext"); Set<Class<? extends ExportFileGenerator>> implenmetions = reflections .getSubTypesOf(org.eclipse.winery.repository.ext.export.custom.ExportFileGenerator.class); logger.info("end to scan class:" + System.currentTimeMillis()); Iterator<Class<? extends ExportFileGenerator>> it = implenmetions.iterator(); Collection<TOSCAComponentId> referencedIds = null; String defName = ZipExporter.getDefinitionsPathInsideCSAR(currentId); definitionNames.add(defName); zos.putArchiveEntry(new ZipArchiveEntry(defName)); try { referencedIds = exporter.exportTOSCA(currentId, zos, refMap, conf, null); } catch (IllegalStateException e) { // thrown if something went wrong inside the repo out.close(); // we just rethrow as there currently is no error stream. throw e; } zos.closeArchiveEntry(); while (it.hasNext()) { Class<? extends ExportFileGenerator> exportClass = it.next(); logger.trace("the " + exportClass.toString() + "begin to write file"); try { if (!Modifier.isAbstract(exportClass.getModifiers())) { ExportFileGenerator fileGenerator = exportClass.newInstance(); referencedIds = exporter.exportTOSCA(currentId, zos, refMap, conf, fileGenerator); } } catch (InstantiationException e) { logger.error("export error occur while instancing " + exportClass.toString(), e); out.close(); } catch (IllegalAccessException e) { logger.error("export error occur", e); out.close(); } } exportedState.flagAsExported(currentId); exportedState.flagAsExportRequired(referencedIds); currentId = exportedState.pop(); } while (currentId != null); // if we export a ServiceTemplate, data for the self-service portal might exist if (entryId instanceof ServiceTemplateId) { this.addSelfServiceMetaData((ServiceTemplateId) entryId, refMap); addCsarMeta((ServiceTemplateId) entryId, zos); } // write custom file CustomizedFileInfos customizedResult = null; if (entryId instanceof ServiceTemplateId) { customizedResult = this.exportCustomFiles((ServiceTemplateId) entryId, zos); } // write manifest directly after the definitions to have it more at the beginning of the ZIP // rather than having it at the very end this.addManifest(entryId, definitionNames, refMap, zos); this.addManiYamlfest(entryId, exporter.getYamlExportDefResultList(), refMap, zos, exporter); this.addCheckSumFest( getCheckSums(exporter.getYamlExportDefResultList(), customizedResult.getCustomizedFileResults()), zos); // used for generated XSD schemas TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer; try { transformer = tFactory.newTransformer(); } catch (TransformerConfigurationException e1) { ZipExporter.logger.debug(e1.getMessage(), e1); throw new IllegalStateException("Could not instantiate transformer", e1); } // write all referenced files for (RepositoryFileReference ref : refMap.keySet()) { String archivePath = refMap.get(ref); ZipExporter.logger.trace("Creating {}", archivePath); ArchiveEntry archiveEntry = new ZipArchiveEntry("xml/" + archivePath); zos.putArchiveEntry(archiveEntry); if (ref instanceof DummyRepositoryFileReferenceForGeneratedXSD) { ZipExporter.logger.trace("Special treatment for generated XSDs"); Document document = ((DummyRepositoryFileReferenceForGeneratedXSD) ref).getDocument(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(zos); try { transformer.transform(source, result); } catch (TransformerException e) { ZipExporter.logger.debug("Could not serialize generated xsd", e); } } else { try (InputStream is = Repository.INSTANCE.newInputStream(ref)) { IOUtils.copy(is, zos); } catch (Exception e) { ZipExporter.logger.error("Could not copy file content to ZIP outputstream", e); } } // add plan files/artifact templantes to yaml folder updatePlanDef(archivePath, ref, zos, customizedResult.getPlanInfos()); zos.closeArchiveEntry(); } addPlan2Zip(customizedResult.getPlanInfos(), zos); this.addNamespacePrefixes(zos); zos.finish(); zos.close(); }
From source file:org.exist.http.SOAPServer.java
/** * HTTP GET/*from w ww . jav a 2s. com*/ * Processes requests for description documents - WSDL, Human Readable and Human Readable for a specific function * * TODO: I think simple webservices can also be called using GET, so we may need to cater for that as well * but first it would be best to write the doPost() method, split the code out into functions and also use it for this. */ public void doGet(DBBroker broker, HttpServletRequest request, HttpServletResponse response, String path) throws BadRequestException, PermissionDeniedException, NotFoundException, IOException { //set the encoding if (request.getCharacterEncoding() == null) { request.setCharacterEncoding(formEncoding); } /* Process the request */ try { //Get a Description of the XQWS final XQWSDescription description = getXQWSDescription(broker, path, request); //Get the approriate description for the user byte[] result = null; if (request.getParameter("WSDL") != null || request.getParameter("wsdl") != null) { //WSDL document literal result = description.getWSDL(); //set output content type for wsdl response.setContentType(MimeType.XML_TYPE.getName()); } else if (request.getParameter("WSDLRPC") != null || request.getParameter("wsdlrpc") != null) { //WSDL RPC result = description.getWSDL(false); //set output content type for wsdl response.setContentType(MimeType.XML_TYPE.getName()); } else if (request.getParameter("function") != null) { //Specific Function Description result = description.getFunctionDescription(request.getParameter("function")); } else { //Human Readable Description result = description.getHumanDescription(); } //send the description to the http servlet response final ServletOutputStream os = response.getOutputStream(); final BufferedOutputStream bos = new BufferedOutputStream(os); bos.write(result); bos.close(); os.close(); } catch (final XPathException xpe) { LOG.debug(xpe.getMessage()); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, formatXPathException(null, path, xpe), "text/html", ENCODING); } catch (final SAXException saxe) { LOG.debug(saxe.getMessage()); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, formatXPathException(null, path, new XPathException( "SAX exception while transforming node: " + saxe.getMessage(), saxe)), "text/html", ENCODING); } catch (final TransformerConfigurationException tce) { LOG.debug(tce.getMessage()); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, formatXPathException(null, path, new XPathException("SAX exception while transforming node: " + tce.getMessage(), tce)), "text/html", ENCODING); } }
From source file:org.exist.http.SOAPServer.java
public void doPost(DBBroker broker, HttpServletRequest request, HttpServletResponse response, String path) throws BadRequestException, PermissionDeniedException, NotFoundException, IOException { /*/* w w w . j av a 2 s.c o m*/ * Example incoming SOAP Request * <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <SOAP-ENV:Body> <echo xmlns="http://localhost:8080/exist/servlet/db/echo.xqws"> <arg1>adam</arg1> </echo> </SOAP-ENV:Body> </SOAP-ENV:Envelope> */ // 1) Read the incoming SOAP request final InputStream is = request.getInputStream(); final byte[] buf = new byte[request.getContentLength()]; int bytes = 0; int offset = 0; final int max = 4096; while ((bytes = is.read(buf, offset, max)) != -1) { offset += bytes; } // 2) Create an XML Document from the SOAP Request Document soapRequest = null; try { soapRequest = BuildXMLDocument(buf); } catch (final Exception e) { LOG.debug(e.getMessage()); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, formatXPathException(null, path, new XPathException( "Unable to construct an XML document from the SOAP Request, probably an invalid request: " + e.getMessage(), e)), "text/html", ENCODING); return; } try { final StringWriter out = new StringWriter(); broker.getSerializer().serialize((ElementImpl) soapRequest.getDocumentElement(), out); //System.out.println(out.toString()); } catch (final SAXException e) { LOG.error("Error during serialization.", e); } // 3) Validate the SOAP Request //TODO: validate the SOAP Request // 4) Extract the function call from the SOAP Request final NodeList nlBody = soapRequest.getDocumentElement().getElementsByTagNameNS(Namespaces.SOAP_ENVELOPE, "Body"); if (nlBody == null) { LOG.error("Style Parameter wrapped not supported yet"); } final Node nSOAPBody = nlBody.item(0); // DW: can return NULL ! case: style ParameterWrapped final NodeList nlBodyChildren = nSOAPBody.getChildNodes(); Node nSOAPFunction = null; for (int i = 0; i < nlBodyChildren.getLength(); i++) { Node bodyChild = nlBodyChildren.item(i); if (bodyChild.getNodeType() == Node.ELEMENT_NODE) { nSOAPFunction = bodyChild; break; } } // Check the namespace for the function in the SOAP document is the same as the request path? final String funcNamespace = nSOAPFunction.getNamespaceURI(); if (funcNamespace != null) { if (!funcNamespace.equals(request.getRequestURL().toString())) { //function in SOAP request has an invalid namespace response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, "SOAP Function call has invalid namespace, got: " + funcNamespace + " but expected: " + request.getRequestURL().toString(), "text/html", ENCODING); return; } } else { //function in SOAP request has no namespace response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, "SOAP Function call has no namespace, expected: " + request.getRequestURL().toString(), "text/html", ENCODING); return; } // 4.5) Detemine encoding style final String encodingStyle = ((org.w3c.dom.Element) nSOAPFunction).getAttributeNS(Namespaces.SOAP_ENVELOPE, "encodingStyle"); boolean isRpcEncoded = (encodingStyle != null && "http://schemas.xmlsoap.org/soap/encoding/".equals(encodingStyle)); // As this detection is a "quirk" which is not always available, let's use a better one... if (!isRpcEncoded) { final NodeList nlSOAPFunction = nSOAPFunction.getChildNodes(); for (int i = 0; i < nlSOAPFunction.getLength(); i++) { final Node functionChild = nlSOAPFunction.item(i); if (functionChild.getNodeType() == Node.ELEMENT_NODE) { if (((org.w3c.dom.Element) functionChild).hasAttributeNS(Namespaces.SCHEMA_INSTANCE_NS, "type")) { isRpcEncoded = true; break; } } } } // 5) Execute the XQWS function indicated by the SOAP request try { //Get the internal description for the function requested by SOAP (should be in the cache) final XQWSDescription description = getXQWSDescription(broker, path, request); //Create an XQuery to call the XQWS function final CompiledXQuery xqCallXQWS = XQueryExecuteXQWSFunction(broker, nSOAPFunction, description, request, response); //xqCallXQWS final XQuery xqueryService = broker.getXQueryService(); final Sequence xqwsResult = xqueryService.execute(xqCallXQWS, null); // 6) Create a SOAP Response describing the Result String funcName = nSOAPFunction.getLocalName(); if (funcName == null) { funcName = nSOAPFunction.getNodeName(); } final byte[] result = description.getSOAPResponse(funcName, xqwsResult, request, isRpcEncoded); // 7) Send the SOAP Response to the http servlet response response.setContentType(MimeType.XML_LEGACY_TYPE.getName()); final ServletOutputStream os = response.getOutputStream(); final BufferedOutputStream bos = new BufferedOutputStream(os); bos.write(result); bos.close(); os.close(); } catch (final XPathException xpe) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, formatXPathException(null, path, xpe), "text/html", ENCODING); } catch (final SAXException saxe) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, formatXPathException(null, path, new XPathException( "SAX exception while transforming node: " + saxe.getMessage(), saxe)), "text/html", ENCODING); } catch (final TransformerConfigurationException tce) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, formatXPathException(null, path, new XPathException("SAX exception while transforming node: " + tce.getMessage(), tce)), "text/html", ENCODING); } }