javax.xml.transform.TransformerException Java Examples
The following examples show how to use
javax.xml.transform.TransformerException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DocExporter.java From TranskribusCore with GNU General Public License v3.0 | 6 votes |
@Override public Source resolve(String href, String base) throws TransformerException { Document xslDoc; try (InputStream in = this.getClass().getClassLoader().getResourceAsStream(href)) { InputSource xslInputSource = new InputSource(in); if (dBuilder != null && href.startsWith("xslt")) { xslDoc = dBuilder.parse(xslInputSource); DOMSource xslDomSource = new DOMSource(xslDoc); xslDomSource.setSystemId(href); return xslDomSource; } } catch (SAXException | IOException e) { logger.error("Failed to load XSLT!", e); } return null; }
Example #2
Source File: XmlUtils.java From alipay-sdk with Apache License 2.0 | 6 votes |
/** * Converts the Node/Document/Element instance to XML payload. * * @param node the node/document/element instance to convert * @return the XML payload representing the node/document/element * @throws ApiException problem converting XML to string */ public static String nodeToString(Node node) throws AlipayApiException { String payload = null; try { Transformer tf = TransformerFactory.newInstance().newTransformer(); Properties props = tf.getOutputProperties(); props.setProperty(OutputKeys.INDENT, LOGIC_YES); props.setProperty(OutputKeys.ENCODING, DEFAULT_ENCODE); tf.setOutputProperties(props); StringWriter writer = new StringWriter(); tf.transform(new DOMSource(node), new StreamResult(writer)); payload = writer.toString(); payload = payload.replaceAll(REG_INVALID_CHARS, " "); } catch (TransformerException e) { throw new AlipayApiException("XML_TRANSFORM_ERROR", e); } return payload; }
Example #3
Source File: TransformerImpl.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** * Receive notification of a recoverable error. * The transformer must continue to provide normal parsing events after * invoking this method. It should still be possible for the application * to process the document through to the end. * * @param e The warning information encapsulated in a transformer * exception. * @throws TransformerException if the application chooses to discontinue * the transformation (always does in our case). */ @Override public void error(TransformerException e) throws TransformerException { Throwable wrapped = e.getException(); if (wrapped != null) { System.err.println(new ErrorMsg(ErrorMsg.ERROR_PLUS_WRAPPED_MSG, e.getMessageAndLocation(), wrapped.getMessage())); } else { System.err.println(new ErrorMsg(ErrorMsg.ERROR_MSG, e.getMessageAndLocation())); } throw e; }
Example #4
Source File: DesignSupport.java From netbeans with Apache License 2.0 | 6 votes |
public static String readMode(FileObject fo) throws IOException { final InputStream is = fo.getInputStream(); try { StringWriter w = new StringWriter(); Source t = new StreamSource(DesignSupport.class.getResourceAsStream("polishing.xsl")); // NOI18N Transformer tr = TransformerFactory.newInstance().newTransformer(t); Source s = new StreamSource(is); Result r = new StreamResult(w); tr.transform(s, r); return w.toString(); } catch (TransformerException ex) { throw new IOException(ex); } finally { is.close(); } }
Example #5
Source File: Main.java From hkxpack with MIT License | 6 votes |
/** * Convert a HKXFile to a XML file. * @param inputFileName * @param outputFileName */ public void read(final String inputFileName, final String outputFileName) { try { // Read file File inFile = new File(inputFileName); HKXEnumResolver enumResolver = new HKXEnumResolver(); HKXDescriptorFactory descriptorFactory = new HKXDescriptorFactory(enumResolver); HKXReader reader = new HKXReader(inFile, descriptorFactory, enumResolver); HKXFile hkxFile = reader.read(); // Write file File outFile = new File(outputFileName); TagXMLWriter writer = new TagXMLWriter(outFile); writer.write(hkxFile); } catch (IOException | TransformerException | ParserConfigurationException | InvalidPositionException e) { LoggerUtil.add(e); } }
Example #6
Source File: RaftProperties.java From ratis with Apache License 2.0 | 6 votes |
/** * Write out the non-default properties in this configuration to the given * {@link Writer}. * * @param out the writer to write to. */ public void writeXml(Writer out) throws IOException { Document doc = asXmlDocument(); try { DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(out); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); // Important to not hold Configuration log while writing result, since // 'out' may be an HDFS stream which needs to lock this configuration // from another thread. transformer.transform(source, result); } catch (TransformerException te) { throw new IOException(te); } }
Example #7
Source File: ConfigTests.java From utah-parser with Apache License 2.0 | 6 votes |
@Test public void testDelimAtStart() throws TransformerException, IOException { createEmptyDocument(); Element delimiterNode = addDelimiter("a line"); delimiterNode.setAttribute("at-start", "true"); Config config = new ConfigLoader().loadConfig(buildDocReader()); Delimiter delimiter = config.delimiters.get(0); Assert.assertNotNull(delimiter); assertTrue(delimiter.isDelimAtStartOfRecord()); // here we check if the retain delim field is false // but the start of record is true, that the retain delim // operation will still return true assertTrue(delimiter.isRetainDelim()); assertFalse(delimiter.isRetainDelim); }
Example #8
Source File: SLDWriterImpl.java From sldeditor with GNU General Public License v3.0 | 6 votes |
/** * Encode sld to a string. * * @param resourceLocator the resource locator * @param sld the sld * @return the string */ @Override public String encodeSLD(URL resourceLocator, StyledLayerDescriptor sld) { String xml = ""; if (sld != null) { InlineDatastoreVisitor duplicator = new InlineDatastoreVisitor(); sld.accept(duplicator); StyledLayerDescriptor sldCopy = (StyledLayerDescriptor) duplicator.getCopy(); if (resourceLocator != null) { SLDExternalImages.updateOnlineResources(resourceLocator, sldCopy); } SLDTransformer transformer = new SLDTransformer(); transformer.setIndentation(2); try { xml = transformer.transform(sldCopy); } catch (TransformerException e) { ConsoleManager.getInstance().exception(this, e); } } return xml; }
Example #9
Source File: XPathParser.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 6 votes |
private XPathContext parseDocument(Document doc) throws TransformerException, XPathException, DOMException, ComponentNotReadyException { // get just one context element ports = new LinkedList<Integer>(); NodeList list = doc.getChildNodes(); Node node = null; boolean found = false; for (int i=0; i<list.getLength(); i++) { if (list.item(i).getNodeName().equalsIgnoreCase(ELEMENT_CONTEXT)) { if (found) { found = false; break; } else { node = list.item(i); found = true; } } } if (!found) throw new TransformerException("Every xpath must contain just one " + ELEMENT_CONTEXT + " element!"); return parseXpathContext(node, new HashMap<String, String>(), null); }
Example #10
Source File: SolrOperationsService.java From Decision with Apache License 2.0 | 6 votes |
public void createSolrSchema(List<ColumnNameTypeValue> columns, String confpath) throws ParserConfigurationException, URISyntaxException, IOException, SAXException, TransformerException { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setIgnoringComments(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(new File(ClassLoader.getSystemResource("./solr-config/schema.xml").toURI())); NodeList nodes = doc.getElementsByTagName("schema"); for (ColumnNameTypeValue column: columns) { Element field = doc.createElement("field"); field.setAttribute("name", column.getColumn()); field.setAttribute("type", streamingToSolr(column.getType())); field.setAttribute("indexed", "true"); field.setAttribute("stored", "true"); nodes.item(0).appendChild(field); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult streamResult = new StreamResult(new File(confpath+"/schema.xml")); transformer.transform(source, streamResult); }
Example #11
Source File: XPathParser.java From hottub with GNU General Public License v2.0 | 6 votes |
/** * * RelativeLocationPath ::= Step * | RelativeLocationPath '/' Step * | AbbreviatedRelativeLocationPath * * @returns true if, and only if, a RelativeLocationPath was matched * * @throws javax.xml.transform.TransformerException */ protected boolean RelativeLocationPath() throws javax.xml.transform.TransformerException { if (!Step()) { return false; } while (tokenIs('/')) { nextToken(); if (!Step()) { // RelativeLocationPath can't end with a trailing '/' // "Location step expected following '/' or '//'" error(XPATHErrorResources.ER_EXPECTED_LOC_STEP, null); } } return true; }
Example #12
Source File: XMLUtilTest.java From jkube with Eclipse Public License 2.0 | 6 votes |
@Test public void testXMLWrite() throws IOException, ParserConfigurationException, TransformerException { // Given File cloneXML = folder.newFile("pom-clone.xml"); Document dom = XMLUtil.createNewDocument(); Element rootElement = dom.createElement("project"); rootElement.appendChild(createSimpleTextNode(dom, "groupId", "org.eclipse.jkube")); rootElement.appendChild(createSimpleTextNode(dom, "artifactId", "jkube-kit")); rootElement.appendChild(createSimpleTextNode(dom, "version", "1.0.0")); dom.appendChild(rootElement); // When XMLUtil.writeXML(dom, cloneXML); // Then assertTrue(cloneXML.exists()); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><project><groupId>org.eclipse.jkube</groupId><artifactId>jkube-kit</artifactId><version>1.0.0</version></project>", new String(Files.readAllBytes(cloneXML.toPath()))); }
Example #13
Source File: SystemIDResolver.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** * Take a SystemID string and try to turn it into a good absolute URI. * * @param urlString SystemID string * @param base The URI string used as the base for resolving the systemID * * @return The resolved absolute URI * @throws TransformerException thrown if the string can't be turned into a URI. */ public static String getAbsoluteURI(String urlString, String base) throws TransformerException { if (base == null) return getAbsoluteURI(urlString); String absoluteBase = getAbsoluteURI(base); URI uri = null; try { URI baseURI = new URI(absoluteBase); uri = new URI(baseURI, urlString); } catch (MalformedURIException mue) { throw new TransformerException(mue); } return replaceChars(uri.toString()); }
Example #14
Source File: XPathParser.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
/** * Consume an expected token, throwing an exception if it * isn't there. * * @param expected the character to be expected. * * @throws javax.xml.transform.TransformerException */ private final void consumeExpected(char expected) throws javax.xml.transform.TransformerException { if (tokenIs(expected)) { nextToken(); } else { error(XPATHErrorResources.ER_EXPECTED_BUT_FOUND, new Object[]{ String.valueOf(expected), m_token }); //"Expected "+expected+", but found: "+m_token); // Patch for Christina's gripe. She wants her errorHandler to return from // this error and continue trying to parse, rather than throwing an exception. // Without the patch, that put us into an endless loop. throw new XPathProcessorException(CONTINUE_AFTER_FATAL_ERROR); } }
Example #15
Source File: DcStreamEditor.java From proarc with GNU General Public License v3.0 | 6 votes |
@Deprecated public void write(DigitalObjectHandler handler, ModsDefinition mods, String model, long timestamp, String message) throws DigitalObjectException { try { JAXBSource jaxbSource = new JAXBSource(ModsUtils.defaultMarshaller(false), new cz.cas.lib.proarc.mods.ObjectFactory().createMods(mods)); // DO NOT include schemaLocation. Fedora validator does not accept it. Transformer t = DcUtils.modsTransformer(model); EditorResult result = editor.createResult(); JAXBResult jaxbResult = new JAXBResult(DcUtils.defaultUnmarshaller()); t.transform(jaxbSource, jaxbResult); JAXBElement<OaiDcType> elm = (JAXBElement<OaiDcType>) jaxbResult.getResult(); OaiDcType dc = elm.getValue(); addDigitalObjectMetadata(handler, dc); DcUtils.marshal(result, dc, false); editor.write(result, timestamp, message); } catch (TransformerException | JAXBException ex) { throw new DigitalObjectException(object.getPid(), ex); } }
Example #16
Source File: XmlUtils.java From bundletool with Apache License 2.0 | 6 votes |
public static String documentToString(Node document) { StringWriter sw = new StringWriter(); try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(new DOMSource(document), new StreamResult(sw)); } catch (TransformerException e) { throw new IllegalStateException("An error occurred while converting the XML to a string", e); } return sw.toString(); }
Example #17
Source File: TransformerImpl.java From hottub with GNU General Public License v2.0 | 6 votes |
/** * Receive notification of a non-recoverable error. * The application must assume that the transformation cannot continue * after the Transformer has invoked this method, and should continue * (if at all) only to collect addition error messages. In fact, * Transformers are free to stop reporting events once this method has * been invoked. * * @param e The warning information encapsulated in a transformer * exception. * @throws TransformerException if the application chooses to discontinue * the transformation (always does in our case). */ @Override public void fatalError(TransformerException e) throws TransformerException { Throwable wrapped = e.getException(); if (wrapped != null) { System.err.println(new ErrorMsg(ErrorMsg.FATAL_ERR_PLUS_WRAPPED_MSG, e.getMessageAndLocation(), wrapped.getMessage())); } else { System.err.println(new ErrorMsg(ErrorMsg.FATAL_ERR_MSG, e.getMessageAndLocation())); } throw e; }
Example #18
Source File: GradebookUtil.java From lams with GNU General Public License v2.0 | 5 votes |
private static String getStringFromDocument(Document document) throws TransformerException { DOMSource domSource = new DOMSource(document); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); return writer.toString(); }
Example #19
Source File: ElemCopyOf.java From j2objc with Apache License 2.0 | 5 votes |
/** * This function is called after everything else has been * recomposed, and allows the template to set remaining * values that may be based on some other property that * depends on recomposition. */ public void compose(StylesheetRoot sroot) throws TransformerException { super.compose(sroot); StylesheetRoot.ComposeState cstate = sroot.getComposeState(); m_selectExpression.fixupVariables(cstate.getVariableNames(), cstate.getGlobalsSize()); }
Example #20
Source File: Test.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
private static String toString(Source response) throws TransformerException, IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(response, new StreamResult(bos)); bos.close(); return new String(bos.toByteArray()); }
Example #21
Source File: XSLTUtils.java From cxf with Apache License 2.0 | 5 votes |
public static Document transform(Templates xsltTemplate, Document in) { try { DOMSource beforeSource = new DOMSource(in); Document out = DOMUtils.createDocument(); Transformer trans = xsltTemplate.newTransformer(); trans.transform(beforeSource, new DOMResult(out)); return out; } catch (TransformerException e) { throw new Fault("XML_TRANSFORM", LOG, e, e.getMessage()); } }
Example #22
Source File: TransformerImpl.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
/** * Inform TrAX error listener of a warning */ private void postWarningToListener(String message) { try { _errorListener.warning(new TransformerException(message)); } catch (TransformerException e) { // ignored - transformation cannot be continued } }
Example #23
Source File: FuncDocument.java From j2objc with Apache License 2.0 | 5 votes |
/** * Tell the user of an error, and probably throw an * exception. * * @param xctxt The XPath runtime state. * @param msg The error message key * @param args Arguments to be used in the error message * @throws XSLProcessorException thrown if the active ProblemListener and XPathContext decide * the error condition is severe enough to halt processing. * * @throws javax.xml.transform.TransformerException */ public void error(XPathContext xctxt, String msg, Object args[]) throws javax.xml.transform.TransformerException { String formattedMsg = XSLMessages.createMessage(msg, args); ErrorListener errHandler = xctxt.getErrorListener(); TransformerException spe = new TransformerException(formattedMsg, (SourceLocator)xctxt.getSAXLocator()); if (null != errHandler) errHandler.error(spe); else System.out.println(formattedMsg); }
Example #24
Source File: XPathParser.java From JDKSourceCode1.8 with MIT License | 5 votes |
/** * * Argument ::= Expr * * * @throws javax.xml.transform.TransformerException */ protected void Argument() throws javax.xml.transform.TransformerException { int opPos = m_ops.getOp(OpMap.MAPINDEX_LENGTH); appendOp(2, OpCodes.OP_ARGUMENT); Expr(); m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH, m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos); }
Example #25
Source File: TransformerTest.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * @bug 8169112 * @summary Test compilation of large xsl file with outlining. * * This test merely compiles a large xsl file and tests if its bytecode * passes verification by invoking the transform() method for * dummy content. The test succeeds if no Exception is thrown */ @Test public final void testBug8169112() throws FileNotFoundException, TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); String xslFile = getClass().getResource("Bug8169112.xsl").toString(); Transformer t = tf.newTransformer(new StreamSource(xslFile)); String xmlIn = "<?xml version=\"1.0\"?><DOCROOT/>"; ByteArrayInputStream bis = new ByteArrayInputStream(xmlIn.getBytes()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); t.transform(new StreamSource(bis), new StreamResult(bos)); }
Example #26
Source File: ResponseObjectBuilderImpl.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
private List<String> toStringOmittingXmlDeclaration(NodeList nodes) throws TransformerException { List<String> assertions = new ArrayList(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer serializer = tf.newTransformer(); serializer.setOutputProperty("omit-xml-declaration", "yes"); for(int i = 0; i < nodes.getLength(); ++i) { StringWriter sw = new StringWriter(); serializer.transform(new DOMSource(nodes.item(i)), new StreamResult(sw)); assertions.add(sw.toString()); } return assertions; }
Example #27
Source File: XPathAPI.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
/** * Evaluate XPath string to an XObject. * XPath namespace prefixes are resolved from the namespaceNode. * The implementation of this is a little slow, since it creates * a number of objects each time it is called. This could be optimized * to keep the same objects around, but then thread-safety issues would arise. * * @param contextNode The node to start searching from. * @param str A valid XPath string. * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. * @see com.sun.org.apache.xpath.internal.objects.XObject * @see com.sun.org.apache.xpath.internal.objects.XNull * @see com.sun.org.apache.xpath.internal.objects.XBoolean * @see com.sun.org.apache.xpath.internal.objects.XNumber * @see com.sun.org.apache.xpath.internal.objects.XString * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag * * @throws TransformerException */ public static XObject eval(Node contextNode, String str, Node namespaceNode) throws TransformerException { // Since we don't have a XML Parser involved here, install some default support // for things like namespaces, etc. // (Changed from: XPathContext xpathSupport = new XPathContext(); // because XPathContext is weak in a number of areas... perhaps // XPathContext should be done away with.) XPathContext xpathSupport = new XPathContext(); // Create an object to resolve namespace prefixes. // XPath namespaces are resolved from the input context node's document element // if it is a root node, or else the current context node (for lack of a better // resolution space, given the simplicity of this sample code). PrefixResolverDefault prefixResolver = new PrefixResolverDefault( (namespaceNode.getNodeType() == Node.DOCUMENT_NODE) ? ((Document) namespaceNode).getDocumentElement() : namespaceNode); // Create the XPath object. XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); // Execute the XPath, and have it return the result // return xpath.execute(xpathSupport, contextNode, prefixResolver); int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode); return xpath.execute(xpathSupport, ctxtNode, prefixResolver); }
Example #28
Source File: TransformerImpl.java From JDKSourceCode1.8 with MIT License | 5 votes |
/** * Inform TrAX error listener of a warning */ private void postWarningToListener(String message) { try { _errorListener.warning(new TransformerException(message)); } catch (TransformerException e) { // ignored - transformation cannot be continued } }
Example #29
Source File: TemplatesHandlerImpl.java From JDKSourceCode1.8 with MIT License | 5 votes |
/** * This method implements XSLTC's SourceLoader interface. It is used to * glue a TrAX URIResolver to the XSLTC compiler's Input and Import classes. * * @param href The URI of the document to load * @param context The URI of the currently loaded document * @param xsltc The compiler that resuests the document * @return An InputSource with the loaded document */ public InputSource loadSource(String href, String context, XSLTC xsltc) { try { // A _uriResolver must be set if this method is called final Source source = _uriResolver.resolve(href, context); if (source != null) { return Util.getInputSource(xsltc, source); } } catch (TransformerException e) { // Falls through } return null; }
Example #30
Source File: XPathImpl.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
public XPathExpression compile(String expression) throws XPathExpressionException { requireNonNull(expression, "XPath expression"); try { com.sun.org.apache.xpath.internal.XPath xpath = new XPath (expression, null, prefixResolver, com.sun.org.apache.xpath.internal.XPath.SELECT); // Can have errorListener XPathExpressionImpl ximpl = new XPathExpressionImpl (xpath, prefixResolver, functionResolver, variableResolver, featureSecureProcessing, useServiceMechanism, featureManager); return ximpl; } catch (TransformerException te) { throw new XPathExpressionException (te) ; } }