Java Code Examples for javax.xml.transform.TransformerException

The following examples show how to use javax.xml.transform.TransformerException. These examples are extracted from open source projects. 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 Project: Decision   Source File: SolrOperationsService.java    License: Apache License 2.0 6 votes vote down vote up
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 2
Source Project: hkxpack   Source File: Main.java    License: MIT License 6 votes vote down vote up
/**
 * 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 3
Source Project: netbeans   Source File: DesignSupport.java    License: Apache License 2.0 6 votes vote down vote up
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 4
Source Project: sldeditor   Source File: SLDWriterImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 5
Source Project: hottub   Source File: TransformerImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 6
Source Project: jkube   Source File: XMLUtilTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@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 7
Source Project: openjdk-jdk8u   Source File: XPathParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 8
Source Project: hottub   Source File: XPathParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 *
 * 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 9
Source Project: alipay-sdk   Source File: XmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 10
Source Project: ratis   Source File: RaftProperties.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 11
/**
 * 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 12
Source Project: proarc   Source File: DcStreamEditor.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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 13
Source Project: TranskribusCore   Source File: DocExporter.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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 14
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 15
Source Project: utah-parser   Source File: ConfigTests.java    License: Apache License 2.0 6 votes vote down vote up
@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 16
/**
 * 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 17
Source Project: bundletool   Source File: XmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
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 18
Source Project: proarc   Source File: OaiCatalogTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testOaiErrorResponseTransformation() throws Exception {
    OaiCatalog c = new OaiCatalog("", "");
    String srcUrl = OaiCatalogTest.class.getResource("oaiErrorResponse.xml").toExternalForm();
    try {
        c.transformOaiResponse(new StreamSource(srcUrl), new StreamResult(new StringWriter()));
        fail();
    } catch (TransformerException result) {
        String msg = result.getMessage();
        assertTrue(msg, msg.contains("cannotDisseminateFormat"));
    }
}
 
Example 19
Source Project: mycore   Source File: MCRXEditorTransformer.java    License: GNU General Public License v3.0 5 votes vote down vote up
public NodeSet getAdditionalParameters() throws ParserConfigurationException, TransformerException {
    org.w3c.dom.Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    NodeSet nodeSet = new NodeSet();

    Map<String, String[]> parameters = editorSession.getRequestParameters();
    for (String name : parameters.keySet()) {
        for (String value : parameters.get(name)) {
            if ((value != null) && !value.isEmpty()) {
                nodeSet.addNode(buildAdditionalParameterElement(dom, name, value));
            }
        }
    }

    String xPaths2CheckResubmission = editorSession.getSubmission().getXPaths2CheckResubmission();
    if (!xPaths2CheckResubmission.isEmpty()) {
        nodeSet.addNode(buildAdditionalParameterElement(dom, MCREditorSubmission.PREFIX_CHECK_RESUBMISSION,
            xPaths2CheckResubmission));
    }

    Map<String, String> defaultValues = editorSession.getSubmission().getDefaultValues();
    for (String xPath : defaultValues.keySet()) {
        nodeSet.addNode(buildAdditionalParameterElement(dom, MCREditorSubmission.PREFIX_DEFAULT_VALUE + xPath,
            defaultValues.get(xPath)));
    }

    editorSession.setBreakpoint("After transformation to HTML");
    nodeSet.addNode(buildAdditionalParameterElement(dom, MCREditorSessionStore.XEDITOR_SESSION_PARAM,
        editorSession.getCombinedSessionStepID()));

    return nodeSet;
}
 
Example 20
Source Project: jdk1.8-source-analysis   Source File: ToXMLStream.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method checks for the XML version of output document.
 * If XML version of output document is not specified, then output
 * document is of version XML 1.0.
 * If XML version of output doucment is specified, but it is not either
 * XML 1.0 or XML 1.1, a warning message is generated, the XML Version of
 * output document is set to XML 1.0 and processing continues.
 * @return string (XML version)
 */
private String getXMLVersion()
{
    String xmlVersion = getVersion();
    if(xmlVersion == null || xmlVersion.equals(XMLVERSION10))
    {
        xmlVersion = XMLVERSION10;
    }
    else if(xmlVersion.equals(XMLVERSION11))
    {
        xmlVersion = XMLVERSION11;
    }
    else
    {
        String msg = Utils.messages.createMessage(
                           MsgKey.ER_XML_VERSION_NOT_SUPPORTED,new Object[]{ xmlVersion });
        try
        {
            // Prepare to issue the warning message
            Transformer tran = super.getTransformer();
            ErrorListener errHandler = tran.getErrorListener();
            // Issue the warning message
            if (null != errHandler && m_sourceLocator != null)
                errHandler.warning(new TransformerException(msg, m_sourceLocator));
            else
                System.out.println(msg);
        }
        catch (Exception e){}
        xmlVersion = XMLVERSION10;
    }
    return xmlVersion;
}
 
Example 21
Source Project: jdk8u60   Source File: XPathParser.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * The value of the Literal is the sequence of characters inside
 * the " or ' characters>.
 *
 * Literal  ::=  '"' [^"]* '"'
 * | "'" [^']* "'"
 *
 *
 * @throws javax.xml.transform.TransformerException
 */
protected void Literal() throws javax.xml.transform.TransformerException
{

  int last = m_token.length() - 1;
  char c0 = m_tokenChar;
  char cX = m_token.charAt(last);

  if (((c0 == '\"') && (cX == '\"')) || ((c0 == '\'') && (cX == '\'')))
  {

    // Mutate the token to remove the quotes and have the XString object
    // already made.
    int tokenQueuePos = m_queueMark - 1;

    m_ops.m_tokenQueue.setElementAt(null,tokenQueuePos);

    Object obj = new XString(m_token.substring(1, last));

    m_ops.m_tokenQueue.setElementAt(obj,tokenQueuePos);

    // lit = m_token.substring(1, last);
    m_ops.setOp(m_ops.getOp(OpMap.MAPINDEX_LENGTH), tokenQueuePos);
    m_ops.setOp(OpMap.MAPINDEX_LENGTH, m_ops.getOp(OpMap.MAPINDEX_LENGTH) + 1);

    nextToken();
  }
  else
  {
    error(XPATHErrorResources.ER_PATTERN_LITERAL_NEEDS_BE_QUOTED,
          new Object[]{ m_token });  //"Pattern literal ("+m_token+") needs to be quoted!");
  }
}
 
Example 22
Source Project: google-cloud-eclipse   Source File: Xslt.java    License: Apache License 2.0 5 votes vote down vote up
public static void transformInPlace(IFile file, URL xslt)
    throws IOException, CoreException, TransformerException {
  try (InputStream in = file.getContents();
      InputStream stylesheetStream = xslt.openStream();
      InputStream resultStream = applyXslt(in, stylesheetStream)) {
    boolean force = true;
    boolean keepHistory = true;
    file.setContents(resultStream, force, keepHistory, null /* monitor */);
  }
}
 
Example 23
Source Project: j2objc   Source File: ElemVariable.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Execute a variable declaration and push it onto the variable stack.
 * @see <a href="http://www.w3.org/TR/xslt#variables">variables in XSLT Specification</a>
 *
 * @param transformer non-null reference to the the current transform-time state.
 *
 * @throws TransformerException
 */
public void execute(TransformerImpl transformer) throws TransformerException
{

  int sourceNode = transformer.getXPathContext().getCurrentNode();

  XObject var = getValue(transformer, sourceNode);

  // transformer.getXPathContext().getVarStack().pushVariable(m_qname, var);
  transformer.getXPathContext().getVarStack().setLocalVariable(m_index, var);
}
 
Example 24
Source Project: openjdk-8   Source File: XPathException.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Print the the trace of methods from where the error
 * originated.  This will trace all nested exception
 * objects, as well as this object.
 * @param s The stream where the dump will be sent to.
 */
public void printStackTrace(java.io.PrintStream s)
{

  if (s == null)
    s = System.err;

  try
  {
    super.printStackTrace(s);
  }
  catch (Exception e){}

  Throwable exception = m_exception;

  for (int i = 0; (i < 10) && (null != exception); i++)
  {
    s.println("---------");
    exception.printStackTrace(s);

    if (exception instanceof TransformerException)
    {
      TransformerException se = (TransformerException) exception;
      Throwable prev = exception;

      exception = se.getException();

      if (prev == exception)
        break;
    }
    else
    {
      exception = null;
    }
  }
}
 
Example 25
Source Project: xml-combiner   Source File: XmlCombinerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void defaults() throws SAXException, IOException, ParserConfigurationException, TransformerException {
	String recessive = "\n"
			+ "<config>\n"
			+ "    <service id='1' combine.self='DEFAULTS'>\n"
			+ "        <parameter>parameter</parameter>\n"
			+ "        <parameter9>parameter2</parameter9>\n"
			+ "        <parameter3>parameter3</parameter3>\n"
			+ "    </service>\n"
			+ "    <service id='2' combine.self='DEFAULTS'>\n"
			+ "        <parameter>parameter</parameter>\n"
			+ "        <parameter2>parameter2</parameter2>\n"
			+ "    </service>\n"
			+ "</config>";
	String dominant = "\n"
			+ "<config>\n"
			+ "    <service id='2'>\n"
			+ "    </service>\n"
			+ "</config>";
	String result = "\n"
			+ "<config>\n"
			+ "    <service id='2'>\n"
			+ "        <parameter>parameter</parameter>\n"
			+ "        <parameter2>parameter2</parameter2>\n"
			+ "    </service>\n"
			+ "</config>";
	assertXMLIdentical(new Diff(result, combineWithIdKey(recessive, dominant)), true);
}
 
Example 26
Source Project: aspectj-maven-plugin   Source File: EclipseAjcMojo.java    License: MIT License 5 votes vote down vote up
/**
 * write document to the file
 *
 * @param document
 * @param file
 * @throws TransformerException
 * @throws FileNotFoundException
 */
private void writeDocument( Document document, File file )
    throws TransformerException, FileNotFoundException
{
    document.normalize();
    DOMSource source = new DOMSource( document );
    StreamResult result = new StreamResult( new FileOutputStream( file ) );
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
    transformer.transform( source, result );
}
 
Example 27
Source Project: iaf   Source File: XpathTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testXpathXmlSwitchCase1() throws ConfigurationException, DomBuilderException, TransformerException, IOException, SAXException {
	String input=TestFileUtils.getTestFile("/XmlSwitch/in.xml");
	String expression="name(/Envelope/Body/*[name()!='MessageHeader'])";
	String expected="SetRequest";
	xpathTest(input,expression,expected);
}
 
Example 28
Source Project: JVoiceXML   Source File: XmlDocument.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns the contents of this object as an XML formatted string.
 *
 * @return XML representation of this object.
 *
 * @exception IOException
 *            Error writing to the writer.
 */
public final String toXml()
        throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final Result result = new StreamResult(out);
    final TransformerFactory transformerFactory =
        TransformerFactory.newInstance();
    try {
        final Transformer transformer = transformerFactory.newTransformer();
        final String encoding = System.getProperty("jvoicexml.xml.encoding",
            "UTF-8");
        transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
        transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
        final DocumentType type = getDoctype();
        if (type != null) {
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
                    type.getPublicId());
            transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
                    type.getSystemId());
        }
        final Source source = new DOMSource(document);
        transformer.transform(source, result);
        return out.toString(encoding);
    } catch (TransformerException e) {
        throw new IOException(e.getMessage(), e);
    }
}
 
Example 29
Source Project: JDKSourceCode1.8   Source File: TemplatesHandlerImpl.java    License: MIT License 5 votes vote down vote up
/**
 * 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 Project: openjdk-jdk9   Source File: XPathImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
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) ;
    }
}