Java Code Examples for javax.xml.transform.TransformerException

The following are top voted examples for showing how to use javax.xml.transform.TransformerException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: gradle-circle-style   File: CircleBuildFinishedAction.java   Source Code and License 6 votes vote down vote up
@Override
public void execute(BuildResult result) {
    String name = (container != null) ? "container " + container : "gradle";
    Report report = new Report.Builder()
            .name(name)
            .subname(name)
            .elapsedTimeNanos(System.nanoTime() - startTimeNanos)
            .addAllTestCases(failureListener.getTestCases())
            .build();
    Document xml = reportToXml(report);

    targetFile.getParentFile().mkdirs();
    try (FileWriter writer = new FileWriter(targetFile)) {
        XmlUtils.write(writer, xml);
    } catch (IOException | TransformerException e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Project: oscm   File: WsdlHandleTask.java   Source Code and License 6 votes vote down vote up
@Override
public void execute() throws BuildException {
    if (StringUtils.isEmpty(dirName)) {
        throw new BuildException("dirname is mandatory");
    }
    if (StringUtils.isEmpty(fileName)) {
        throw new BuildException("filename is mandatory");
    }
    File file = new File(dirName + File.separator + fileName);
    if (!file.exists()) {
        throw new BuildException("wsdl file does not exist");
    }
    try {
        Document doc = parse(file);
        Element element = doc.createElement("documentation");
        element.setTextContent("v" + version);

        doc.getElementsByTagName("definitions").item(0)
                .appendChild(element);

        save(dirName + File.separator + fileName, doc);
    } catch (ParserConfigurationException | SAXException | IOException
            | TransformerException e) {
        throw new BuildException(e);
    }
}
 
Example 3
Project: openjdk-jdk10   File: SystemIDResolver.java   Source Code and License 6 votes vote down vote up
/**
 * 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 4
Project: OperatieBRP   File: AbstractDienstVerzoekParser.java   Source Code and License 6 votes vote down vote up
/**
 * Hulpmethode om een xml fragment uit een node te halen middels xpath.
 * @param locatie de locatie van de node als xpath.
 * @param xPath een XPath instantie
 * @param node de basis node
 * @return de text
 */
protected static String getXmlFragment(final String locatie, final XPath xPath, final Node node) {
    try {
        final Node xPathNode = (Node) xPath.evaluate(locatie, node, XPathConstants.NODE);
        if (xPathNode != null) {
            final StringWriter buf = new StringWriter();
            final Transformer xform = TransformerFactory.newInstance().newTransformer();
            xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            xform.transform(new DOMSource(xPathNode), new StreamResult(buf));
            return buf.toString();
        }
    } catch (final XPathExpressionException | TransformerException e) {
        LOGGER.error("XPath voor text content kon niet worden geëvalueerd voor locatie {}.", locatie);
        throw new UnsupportedOperationException(e);
    }
    return null;
}
 
Example 5
Project: oscm   File: XmlDocument.java   Source Code and License 6 votes vote down vote up
/**
 * Converts the given document to an XML string. Uses UTF-8 as character
 * encoding.
 * 
 * @return the XML as byte array
 */
byte[] docToXml() {
    try {
        DOMSource domSource = new DOMSource(xmldoc);
        final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(buffer);
        Transformer transformer = Transformers.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(
                "{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(domSource, result);
        return buffer.toByteArray();
    } catch (TransformerException e) {
        throw new SaaSSystemException(e);
    }
}
 
Example 6
Project: openjdk-jdk10   File: XPathParser.java   Source Code and License 6 votes vote down vote up
/**
 * Warn the user of a problem.
 *
 * @param msg An error msgkey that corresponds to one of the constants found
 *            in {@link com.sun.org.apache.xpath.internal.res.XPATHErrorResources}, which is
 *            a key for a format string.
 * @param args An array of arguments represented in the format string, which
 *             may be null.
 *
 * @throws TransformerException if the current ErrorListoner determines to
 *                              throw an exception.
 */
void warn(String msg, Object[] args) throws TransformerException
{

  String fmsg = XSLMessages.createXPATHWarning(msg, args);
  ErrorListener ehandler = this.getErrorListener();

  if (null != ehandler)
  {
    // TO DO: Need to get stylesheet Locator from here.
    ehandler.warning(new TransformerException(fmsg, m_sourceLocator));
  }
  else
  {
    // Should never happen.
    System.err.println(fmsg);
  }
}
 
Example 7
Project: incubator-ratis   File: RaftProperties.java   Source Code and License 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 8
Project: EVE   File: Weather.java   Source Code and License 6 votes vote down vote up
private void generateForecast(String c) throws IOException, SAXException, TransformerException, ParserConfigurationException {
    city = c;

    // creating the URL
    String url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=" + city + ",us&mode=xml&cnt=6&appid=" + APIKey;

    // printing out XML
    URL urlString = new URL(url);
    URLConnection conn = urlString.openConnection();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(conn.getInputStream());

    TransformerFactory transformer = TransformerFactory.newInstance();
    Transformer xform = transformer.newTransformer();

    xform.transform(new DOMSource(doc), new StreamResult(System.out));
}
 
Example 9
Project: oscm   File: PaypalRequest.java   Source Code and License 6 votes vote down vote up
/**
 * Converts a given document into its string representation.
 * 
 * @param doc
 *            The document to be converted.
 * @param xmlDecl
 *            should the output contain a XML declaration?
 * @return The string representation of the document.
 * @throws TransformerException
 *             Thrown in case the conversion fails.
 */
private String getDocAsString(final Node doc) throws TransformerException {
    final DOMSource docSource = new DOMSource(doc);
    final TransformerFactory transformerFactory = TransformerFactory
            .newInstance();
    final Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    final StringWriter buffer = new StringWriter();
    transformer.transform(docSource, new StreamResult(buffer));
    lastRequest = buffer.toString();
    return lastRequest;
}
 
Example 10
Project: code-sentinel   File: asl2xml.java   Source Code and License 6 votes vote down vote up
TransformerFactory getFactory() throws Exception {
    if (fac == null) {
        fac = TransformerFactory.newInstance();
        fac.setURIResolver(new URIResolver() {
            public Source resolve(String href, String base) throws TransformerException {
                try {
                    return new StreamSource(asl2xml.class.getResource("/xml/" + href).openStream());
                } catch (Exception e) {
                    System.err.println("Error - " + href + "-" + base);
                    e.printStackTrace();
                    return null;
                }
            }
        });
    }
    return fac;
}
 
Example 11
Project: OpenJSharp   File: TransformerFactoryImpl.java   Source Code and License 6 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
 */
@Override
public InputSource loadSource(String href, String context, XSLTC xsltc) {
    try {
        if (_uriResolver != null) {
            final Source source = _uriResolver.resolve(href, context);
            if (source != null) {
                return Util.getInputSource(xsltc, source);
            }
        }
    }
    catch (TransformerException e) {
        // should catch it when the resolver explicitly throws the exception
        final ErrorMsg msg = new ErrorMsg(ErrorMsg.INVALID_URI_ERR, href + "\n" + e.getMessage(), this);
        xsltc.getParser().reportError(Constants.FATAL, msg);
    }

    return null;
}
 
Example 12
Project: KeYExperienceReport   File: SPLOpltionGenerator.java   Source Code and License 6 votes vote down vote up
private static void writeOut(Document doc) throws TransformerException {
	TransformerFactory transformerFactory = TransformerFactory
			.newInstance();
	Transformer transformer = transformerFactory.newTransformer();
	transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
	transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
	DOMSource source = new DOMSource(doc);
	File f = new File("splFile.xml");
	f.delete();
	StreamResult result = new StreamResult(f);

	// Output to console for testing
	// StreamResult result = new StreamResult(System.out);

	transformer.transform(source, result);

	System.out.println("File saved!");

}
 
Example 13
Project: openjdk-jdk10   File: TransformerFactoryImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Pass error messages from the compiler to the error listener
 */
private void passErrorsToListener(ArrayList<ErrorMsg> messages) {
    try {
        if (_errorListener == null || messages == null) {
            return;
        }
        // Pass messages to listener, one by one
        final int count = messages.size();
        for (int pos = 0; pos < count; pos++) {
            String message = messages.get(pos).toString();
            _errorListener.error(new TransformerException(message));
        }
    }
    catch (TransformerException e) {
        // nada
    }
}
 
Example 14
Project: KeYExperienceReport   File: FeatureIdeOpltionGenerator.java   Source Code and License 6 votes vote down vote up
private static void writeOut(Document doc) throws TransformerException {
	TransformerFactory transformerFactory = TransformerFactory
			.newInstance();
	Transformer transformer = transformerFactory.newTransformer();
	transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
	transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
	DOMSource source = new DOMSource(doc);
	File f = new File("file.xml");
	f.delete();
	StreamResult result = new StreamResult(f);

	// Output to console for testing
	// StreamResult result = new StreamResult(System.out);

	transformer.transform(source, result);

	System.out.println("File saved!");

}
 
Example 15
Project: openjdk-jdk10   File: TransformerImpl.java   Source Code and License 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 16
Project: KeYExperienceReport   File: SPL2OpltionGenerator.java   Source Code and License 6 votes vote down vote up
private static void writeOut(Document doc) throws TransformerException {
	TransformerFactory transformerFactory = TransformerFactory
			.newInstance();
	Transformer transformer = transformerFactory.newTransformer();
	transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
	transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
	DOMSource source = new DOMSource(doc);
	File f = new File("splFile.xml");
	f.delete();
	StreamResult result = new StreamResult(f);

	// Output to console for testing
	// StreamResult result = new StreamResult(System.out);

	transformer.transform(source, result);

	System.out.println("File saved!");

}
 
Example 17
Project: pay   File: XmlUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Converts the Node/Element instance to XML payload.
 *
 * @param node the node/element instance to convert
 * @return the XML payload representing the node/element
 * @throws AlipayApiException problem converting XML to string
 */
public static String childNodeToString(Node node) throws AlipayApiException {
    String payload = null;

    try {
        Transformer tf = TransformerFactory.newInstance().newTransformer();

        Properties props = tf.getOutputProperties();
        props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);
        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 18
Project: openjdk-jdk10   File: XPath.java   Source Code and License 6 votes vote down vote up
/**
 * Tell the user of an error, and probably throw an
 * exception.
 *
 * @param xctxt The XPath runtime context.
 * @param sourceNode Not used.
 * @param msg An error msgkey that corresponds to one of the constants found
 *            in {@link com.sun.org.apache.xpath.internal.res.XPATHErrorResources}, which is
 *            a key for a format string.
 * @param args An array of arguments represented in the format string, which
 *             may be null.
 *
 * @throws TransformerException if the current ErrorListoner determines to
 *                              throw an exception.
 */
public void error(
        XPathContext xctxt, int sourceNode, String msg, Object[] args)
          throws javax.xml.transform.TransformerException
{

  String fmsg = XSLMessages.createXPATHMessage(msg, args);
  ErrorListener ehandler = xctxt.getErrorListener();

  if (null != ehandler)
  {
    ehandler.fatalError(new TransformerException(fmsg,
                            (SAXSourceLocator)xctxt.getSAXLocator()));
  }
  else
  {
    SourceLocator slocator = xctxt.getSAXLocator();
    System.out.println(fmsg + "; file " + slocator.getSystemId()
                       + "; line " + slocator.getLineNumber() + "; column "
                       + slocator.getColumnNumber());
  }
}
 
Example 19
Project: openjdk-jdk10   File: TransformerFactoryImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Pass warning messages from the compiler to the error listener
 */
private void passWarningsToListener(ArrayList<ErrorMsg> messages)
    throws TransformerException
{
    if (_errorListener == null || messages == null) {
        return;
    }
    // Pass messages to listener, one by one
    final int count = messages.size();
    for (int pos = 0; pos < count; pos++) {
        ErrorMsg msg = messages.get(pos);
        // Workaround for the TCK failure ErrorListener.errorTests.error001.
        if (msg.isWarningError())
            _errorListener.error(
                new TransformerConfigurationException(msg.toString()));
        else
            _errorListener.warning(
                new TransformerConfigurationException(msg.toString()));
    }
}
 
Example 20
Project: xpath-to-xml   File: XmlBuilderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldBuildDocumentFromSetOfXPathsAndSetValues()
        throws XPathExpressionException, TransformerException, IOException {
    Map<String, Object> xmlProperties = fixtureAccessor.getXmlProperties();
    Document document = documentBuilder.newDocument();
    document.setXmlStandalone(true);
    Document builtDocument = new XmlBuilder(namespaceContext)
            .putAll(xmlProperties)
            .build(document);

    for (Entry<String, Object> xpathToValuePair : xmlProperties.entrySet()) {
        XPath xpath = xpathFactory.newXPath();
        if (null != namespaceContext) {
            xpath.setNamespaceContext(namespaceContext);
        }
        assertThat(xpath.evaluate(xpathToValuePair.getKey(), builtDocument, XPathConstants.STRING))
                .isEqualTo(xpathToValuePair.getValue());
    }
    assertThat(xmlToString(builtDocument)).isEqualTo(fixtureAccessor.getPutValueXml());
}
 
Example 21
Project: neoscada   File: SignatureRequestBuilder.java   Source Code and License 6 votes vote down vote up
public Document cloneDoc ( final Document doc ) throws TransformerException
{
    final Transformer tx = this.tf.newTransformer ();
    final DOMSource source = new DOMSource ( doc );
    final DOMResult result = new DOMResult ();
    tx.transform ( source, result );
    return (Document)result.getNode ();
}
 
Example 22
Project: openjdk-jdk10   File: TransformerExcpTest.java   Source Code and License 6 votes vote down vote up
/**
 * Transform an unformatted style-sheet file. TransformerException is thrown.
 */
@Test
public void tfexception() {
    try {
        // invalid.xsl has well-formedness error. Therefore transform throws
        // TransformerException
        StreamSource streamSource
                = new StreamSource(new File(XML_DIR + "invalid.xsl"));
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer(streamSource);
        transformer.transform(
                new StreamSource(new File(XML_DIR + "cities.xml")),
                new SAXResult());
        fail("TransformerException is not thrown as expected");
    } catch (TransformerException e) {
        assertNotNull(e.getCause());
        assertNotNull(e.getException());
        assertNull(e.getLocationAsString());
        assertEquals(e.getMessageAndLocation(),e.getMessage());
    }
}
 
Example 23
Project: OpenJSharp   File: SourceTreeManager.java   Source Code and License 6 votes vote down vote up
/**
 * Get the source tree from the a base URL and a URL string.
 *
 * @param base The base URI to use if the urlString is relative.
 * @param urlString An absolute or relative URL string.
 * @param locator The location of the caller, for diagnostic purposes.
 *
 * @return should be a non-null reference to the node identified by the
 * base and urlString.
 *
 * @throws TransformerException If the URL can not resolve to a node.
 */
public int getSourceTree(
        String base, String urlString, SourceLocator locator, XPathContext xctxt)
          throws TransformerException
{

  // System.out.println("getSourceTree");
  try
  {
    Source source = this.resolveURI(base, urlString, locator);

    // System.out.println("getSourceTree - base: "+base+", urlString: "+urlString+", source: "+source.getSystemId());
    return getSourceTree(source, locator, xctxt);
  }
  catch (IOException ioe)
  {
    throw new TransformerException(ioe.getMessage(), locator, ioe);
  }

  /* catch (TransformerException te)
   {
     throw new TransformerException(te.getMessage(), locator, te);
   }*/
}
 
Example 24
Project: parabuild-ci   File: UnwrapLinks.java   Source Code and License 5 votes vote down vote up
/**
  * <p>Unwrap links</p>
  *
  * @param rtf The result tree fragment of the verbatim environment.
  *
  * @return The modified result tree fragment.
  */
 public static NodeSetValue unwrapLinks (Context context,
				  NodeSetValue rtf_ns) {

   FragmentValue rtf = (FragmentValue) rtf_ns;
   boolean tryAgain = true;

   setupUnwrapLinks(context);

   try {
     Controller controller = context.getController();
     NamePool namePool = controller.getNamePool();

     while (tryAgain) {
UnwrapLinksEmitter ulEmitter = new UnwrapLinksEmitter(controller,
						      namePool,
						      foStylesheet);
rtf.replay(ulEmitter);
tryAgain = ulEmitter.tryAgain();
rtf = (FragmentValue) ulEmitter.getResultTreeFragment();
     }

     return rtf;

   } catch (TransformerException e) {
     // This "can't" happen.
     System.out.println("Transformer Exception in unwrapLinks");
     return rtf;
   }
 }
 
Example 25
Project: alvisnlp   File: XMLReader.java   Source Code and License 5 votes vote down vote up
public static void references(XSLProcessorContext ctx, ElemExtensionCall call) throws TransformerException {
	TransformerImpl transformer = ctx.getTransformer();
	XMLReaderContext xrctx = (XMLReaderContext) transformer.getParameter(XML_READER_CONTEXT_PARAMETER);
	xrctx.startRefScope();
	transformer.executeChildTemplates(call, false);
	xrctx.endRefScope();
}
 
Example 26
Project: OperatieBRP   File: AbstractGeneriekeBerichtParser.java   Source Code and License 5 votes vote down vote up
/**
 * Parst een verzoek XML op een generieke manier. Hierbij wordt er een {@link Node} en een {@link XPath} gebruikt.
 * @param node de {@link Node}
 * @return het {@link Verzoek}
 * @throws VerzoekParseException fout bij het parsen.
 */
public final T parse(final Node node) throws VerzoekParseException {
    try {
        final T verzoek = maakVerzoek();
        final VerzoekParser<T> dienstBerichtParser = geefDienstSpecifiekeParser(node);
        dienstBerichtParser.vulStuurgegevens(verzoek, node, xpath);
        dienstBerichtParser.vulParameters(verzoek, node, xpath);
        dienstBerichtParser.vulDienstSpecifiekeGegevens(verzoek, node, xpath);
        zetBerichtXml(verzoek, node);
        return verzoek;
    } catch (final TransformerException | ParseException e) {
        throw new VerzoekParseException(e);
    }
}
 
Example 27
Project: OpenJSharp   File: EfficientStreamingTransformer.java   Source Code and License 5 votes vote down vote up
public void setURIResolver(javax.xml.transform.URIResolver uRIResolver) {
    try {
        materialize();
        m_realTransformer.setURIResolver(uRIResolver);
    } catch (TransformerException e) {
        // will be caught later
    }
}
 
Example 28
Project: OpenJSharp   File: XPath.java   Source Code and License 5 votes vote down vote up
/**
 * Get the match score of the given node.
 *
 * @param xctxt XPath runtime context.
 * @param context The current source tree context node.
 *
 * @return score, one of {@link #MATCH_SCORE_NODETEST},
 * {@link #MATCH_SCORE_NONE}, {@link #MATCH_SCORE_OTHER},
 * or {@link #MATCH_SCORE_QNAME}.
 *
 * @throws javax.xml.transform.TransformerException
 */
public double getMatchScore(XPathContext xctxt, int context)
        throws javax.xml.transform.TransformerException
{

  xctxt.pushCurrentNode(context);
  xctxt.pushCurrentExpressionNode(context);

  try
  {
    XObject score = m_mainExp.execute(xctxt);

    if (DEBUG_MATCHES)
    {
      DTM dtm = xctxt.getDTM(context);
      System.out.println("score: " + score.num() + " for "
                         + dtm.getNodeName(context) + " for xpath "
                         + this.getPatternString());
    }

    return score.num();
  }
  finally
  {
    xctxt.popCurrentNode();
    xctxt.popCurrentExpressionNode();
  }

  // return XPath.MATCH_SCORE_NONE;
}
 
Example 29
Project: qpp-conversion-tool   File: MarkupManipulator.java   Source Code and License 5 votes vote down vote up
public InputStream upsetTheNorm(String xPath, boolean remove) {
	try {
		document = dbf.newDocumentBuilder().parse(new File(pathname));
		XPath xpath = xpf.newXPath();
		XPathExpression expression = xpath.compile(xPath);

		NodeList searchedNodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
		if (searchedNodes == null) {
			System.out.println("bad path: " + xPath);
		} else {
			for (int i = 0; i < searchedNodes.getLength(); i++) {
				Node searched = searchedNodes.item(i);

				Node owningElement = (searched instanceof ElementImpl)
						? searched
						: ((AttrImpl) searched).getOwnerElement();

				Node containingParent = owningElement.getParentNode();

				if (remove) {
					containingParent.removeChild(owningElement);
				} else {
					containingParent.appendChild(owningElement.cloneNode(true));
				}

			}
		}

		Transformer t = tf.newTransformer();
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		Result result = new StreamResult(os);
		t.transform(new DOMSource(document), result);
		return new ByteArrayInputStream(os.toByteArray());
	} catch (ParserConfigurationException | IOException | SAXException |
			XPathExpressionException | TransformerException ex) {
		throw new RuntimeException(ex);
	}
}
 
Example 30
Project: api-harvester   File: Main.java   Source Code and License 5 votes vote down vote up
private static void apiHarverst()
    throws IOException, ParserConfigurationException, TransformerException, SAXException, URISyntaxException {
  LOGGER.info("Initialize Properties");
  File propertiesFile = new File(propertiesPath);
  Properties properties = new Properties();
  //Properties on the level of the jar or in the resources directory
  if (propertiesFile.exists()) {
    properties.load(new FileInputStream(propertiesPath));
  } else {
    properties.load(Main.class.getResourceAsStream("/" + propertiesPath));
  }
  String apiEndpoint = properties.getProperty("api.endpoint");
  String directoryNamePrefix = properties.getProperty("directory.name.prefix");
  boolean jsonConvertToXml = Boolean
      .parseBoolean(properties.getProperty("json.convert.to.xml"));
  String offsetParameterName = properties.getProperty("offset.parameter.name");
  String limitParameterName = properties.getProperty("limit.parameter.name");
  int offset = Integer.parseInt(properties.getProperty("offset"));
  int limit = Integer.parseInt(properties.getProperty("limit"));
  String recordListField = properties.getProperty("record.list.field");
  String harvestOutputDirectory = properties.getProperty("harvest.output.directory");
  String rootElementName = properties.getProperty("root.element.name");
  String listElementNames = properties.getProperty("list.element.names");

  ApiHarvester apiHarvester = new ApiHarvester(apiEndpoint, directoryNamePrefix,
      jsonConvertToXml, recordListField, offsetParameterName, offset, limitParameterName,
      limit, harvestOutputDirectory);
  if (jsonConvertToXml) {
    apiHarvester.setRootElementName(rootElementName);
    apiHarvester.setListElementNames(listElementNames);
  }
  LOGGER.info("Initiate Harvest");
  apiHarvester.harvest(false, true);
}
 
Example 31
Project: alvisnlp   File: XMLReader.java   Source Code and License 5 votes vote down vote up
public static final void arg(XSLProcessorContext ctx, ElemExtensionCall call) throws TransformerException {
	TransformerImpl transformer = ctx.getTransformer();
	XMLReaderContext xrctx = (XMLReaderContext) transformer.getParameter(XML_READER_CONTEXT_PARAMETER);
	String role = getAttributeStringValue(ctx, call, "xpath-role", "role");
	String ref = getAttributeStringValue(ctx, call, "xpath-ref", "ref");
	xrctx.setArgument(role, ref);
}
 
Example 32
Project: jdk8u-jdk   File: SaajEmptyNamespaceTest.java   Source Code and License 5 votes vote down vote up
private String nodeToText(Node node) throws TransformerException {
    Transformer trans = TransformerFactory.newInstance().newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    trans.transform(new DOMSource(node), result);
    String bodyContent = writer.toString();
    System.out.println("SOAP body content read by SAAJ:"+bodyContent);
    return bodyContent;
}
 
Example 33
Project: openjdk-jdk10   File: XPathParser.java   Source Code and License 5 votes vote down vote up
/**
 *
 * PredicateExpr ::= Expr
 *
 *
 * @throws javax.xml.transform.TransformerException
 */
protected void PredicateExpr() throws javax.xml.transform.TransformerException
{

  int opPos = m_ops.getOp(OpMap.MAPINDEX_LENGTH);

  appendOp(2, OpCodes.OP_PREDICATE);
  Expr();

  // Terminate for safety.
  m_ops.setOp(m_ops.getOp(OpMap.MAPINDEX_LENGTH), OpCodes.ENDOP);
  m_ops.setOp(OpMap.MAPINDEX_LENGTH, m_ops.getOp(OpMap.MAPINDEX_LENGTH) + 1);
  m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH,
    m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos);
}
 
Example 34
Project: openjdk-jdk10   File: WSEndpointReference.java   Source Code and License 5 votes vote down vote up
/**
 * Dumps the EPR infoset in a human-readable string.
 */
@Override
public String toString() {
    try {
        // debug convenience
        StringWriter sw = new StringWriter();
        XmlUtil.newTransformer().transform(asSource("EndpointReference"),new StreamResult(sw));
        return sw.toString();
    } catch (TransformerException e) {
        return e.toString();
    }
}
 
Example 35
Project: openjdk-jdk10   File: XPathParser.java   Source Code and License 5 votes vote down vote up
/**
 * The context of the right hand side expressions is the context of the
 * left hand side expression. The results of the right hand side expressions
 * are node sets. The result of the left hand side UnionExpr is the union
 * of the results of the right hand side expressions.
 *
 *
 * UnionExpr    ::=    PathExpr
 * | UnionExpr '|' PathExpr
 *
 *
 * @throws javax.xml.transform.TransformerException
 */
protected void UnionExpr() throws javax.xml.transform.TransformerException
{

  int opPos = m_ops.getOp(OpMap.MAPINDEX_LENGTH);
  boolean continueOrLoop = true;
  boolean foundUnion = false;

  do
  {
    PathExpr();

    if (tokenIs('|'))
    {
      if (false == foundUnion)
      {
        foundUnion = true;

        insertOp(opPos, 2, OpCodes.OP_UNION);
      }

      nextToken();
    }
    else
    {
      break;
    }

    // this.m_testForDocOrder = true;
  }
  while (continueOrLoop);

  m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH,
        m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos);
}
 
Example 36
Project: openjdk-jdk10   File: XPathImpl.java   Source Code and License 5 votes vote down vote up
public Object evaluate(String expression, InputSource source,
        QName returnType) throws XPathExpressionException {
    isSupported(returnType);

    try {
        Document document = getDocument(source);
        XObject resultObject = eval(expression, document);
        return getResultAsType(resultObject, returnType);
    } catch (TransformerException te) {
        Throwable nestedException = te.getException();
        if (nestedException instanceof javax.xml.xpath.XPathFunctionException) {
            throw (javax.xml.xpath.XPathFunctionException)nestedException;
        } else {
            throw new XPathExpressionException (te);
        }
    }
}
 
Example 37
Project: alvisnlp   File: LibraryModel.java   Source Code and License 5 votes vote down vote up
void generateClass(ModelContext ctx) throws IOException, TransformerException {
       Transformer transformer = ctx.getTransformerFactory().newTransformer(new StreamSource(ctx.getLibraryClassTemplate()));
       FileObject fo = ctx.getFiler().createSourceFile(fullName, (javax.lang.model.element.Element[])null);
       PrintWriter out = new PrintWriter(fo.openWriter());
       transformer.transform(new DOMSource(getDOM(ctx, XMLUtils.docBuilder)), new StreamResult(out));
       out.close();
}
 
Example 38
Project: openjdk-jdk10   File: XPathParser.java   Source Code and License 5 votes vote down vote up
/**
 *
 * 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 39
Project: alvisnlp   File: AlvisNLPAnnotationProcessor.java   Source Code and License 5 votes vote down vote up
@Override
	public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
		try {
			String prefix = ctx.hasOption("classPrefix") ? ctx.getOption("classPrefix") : "Concrete";

			if (annotations.contains(ctx.getModuleAnnotation())) {				
				String moduleFactoryName = ctx.getOption("moduleFactoryName");
				String dataClass = ctx.getOption("dataClass");
				String sequenceImplementationClass = ctx.getOption("sequenceImplementationClass");
				String factoryInterface = ctx.getOption("factoryInterface");
				String shellModule = ctx.getOption("shellModule");
				ModuleFactoryModel moduleFactory = new ModuleFactoryModel(moduleFactoryName, dataClass, sequenceImplementationClass, factoryInterface, prefix, shellModule);

				ctx.note("processing module sources");
				for (TypeElement moduleElement : ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(ctx.getModuleAnnotation()))) {
					ModuleModel module = new ModuleModel(ctx, moduleElement);
					moduleFactory.addModule(ctx, module);
				}

				ctx.note("generating module factory for data class " + dataClass + " (" + moduleFactory.moduleCount() + " modules, " + moduleFactory.betaCount() + " beta, " + moduleFactory.obsoleteCount() + " obsolete)");
				moduleFactory.generateClass(ctx);
				ctx.note("generating module classes");
				moduleFactory.generateModules(ctx);
				// XXX broken in maven build
				//ctx.note("generating module documentation");
				//moduleFactory.generateModuleDocs(ctx);
				//ctx.note("generating module factory service");
				//moduleFactory.generateService(ctx);
			}

			if (annotations.contains(ctx.getConverterAnnotation())) {
				if (!ctx.hasOption("converterFactoryName")) {
					ctx.error("missing option -AconverterFactoryName");
					return true;
				}
				String converterFactoryName = ctx.getOption("converterFactoryName");
				List<String> resourceBases = Arrays.asList(ctx.getOption("resourceBases").split(":"));
				ConverterFactoryModel converterFactory = new ConverterFactoryModel(converterFactoryName, resourceBases);
				ctx.note("processing converter sources");
				for (TypeElement converterElement : ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(ctx.getConverterAnnotation()))) {
					ConverterModel converter = new ConverterModel(ctx, converterElement);
					converterFactory.addConverter(converter);
				}
				ctx.note("generating converter factory class");
				converterFactory.generateClass(ctx);
				ctx.note("generating converter documentation");
				converterFactory.generateConvertersDoc(ctx);
				//ctx.note("generating converter factory service");
				//converterFactory.generateService(ctx);
			}

			if (annotations.contains(ctx.getLibraryAnnotation())) {
				for (TypeElement libraryElement : ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(ctx.getLibraryAnnotation()))) {
					ctx.note("generating library class: " + libraryElement.getAnnotation(Library.class).value());
					LibraryModel libModel = new LibraryModel(ctx, libraryElement, prefix);
					libModel.generateClass(ctx);
					// XXX broken by maven
					// libModel.generateDocumentation(ctx);
				}
			}
		}
		catch (TransformerException te) {
			ctx.error("error while processing source: " + te.getMessage());
		}
		catch (IOException ioe) {
			ctx.error("error while processing source: " + ioe.getMessage());
		}
		catch (ModelException me) {
			ctx.error(me.getMessage());
		}
//		catch (XPathExpressionException xpee) {
//			ctx.error(xpee.getMessage());
//		}
		catch (TransformerFactoryConfigurationError tfce) {
			ctx.error(tfce.getMessage());
		}
//		catch (SAXException saxe) {
//			ctx.error(saxe.getMessage());
//		}
		return true;
	}
 
Example 40
Project: openjdk-jdk10   File: TransformerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void run() throws TransformerFactoryConfigurationError, TransformerException {
    Transformer t = getTransformer();
    t.setParameter("config", getClass().getResource("config.xml").toString());
    t.setParameter("mapsFile", getClass().getResource("maps.xml").toString());
    StringWriter resultWriter = new StringWriter();
    t.transform(getStreamSource(), new StreamResult(resultWriter));
    String resultString = resultWriter.toString();
    Assert.assertTrue(resultString.contains("map1key1value") && resultString.contains("map2key1value"));
}
 
Example 41
Project: OpenJSharp   File: CachedXPathAPI.java   Source Code and License 5 votes vote down vote up
/**
 * Use an XPath string to select a single node.
 * XPath namespace prefixes are resolved from the namespaceNode.
 *
 * @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 The first node found that matches the XPath, or null.
 *
 * @throws TransformerException
 */
public  Node selectSingleNode(
        Node contextNode, String str, Node namespaceNode)
          throws TransformerException
{

  // Have the XObject return its result as a NodeSetDTM.
  NodeIterator nl = selectNodeIterator(contextNode, str, namespaceNode);

  // Return the first node, or null
  return nl.nextNode();
}
 
Example 42
Project: ARCLib   File: ArclibXmlGeneratorTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests the aggregation mapping for generation of the <i>ARCLIB:eventAgent</i> element.
 */
@Test
public void generateArclibEventAgent() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException,
        TransformerException {
    SipProfile profile = new SipProfile();
    String sipProfileXml = Resources.toString(this.getClass().getResource(
            "/arclibxmlgeneration/sipProfiles/sipProfileEventCount.xml"), StandardCharsets.UTF_8);
    profile.setXml(sipProfileXml);

    store.save(profile);

    String arclibXml = generator.generateArclibXml(SIP_PATH, profile.getId());
    assertThat(arclibXml, is("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<METS:mets xmlns:METS=\"http://www.loc.gov/METS/\"><METS:amdSec xmlns:METS=\"http://arclib.lib.cas.cz/ARCLIB_XML\"><METS:digiprovMD><METS:mdWrap><METS:xmlData><ARCLIB:eventAgents xmlns:ARCLIB=\"http://arclib.lib.cas.cz/ARCLIB_XML\"><ARCLIB:eventAgent><premis:eventType>capture</premis:eventType>\r\n</ARCLIB:eventAgent></ARCLIB:eventAgents></METS:xmlData></METS:mdWrap></METS:digiprovMD></METS:amdSec><METS:amdSec xmlns:METS=\"http://arclib.lib.cas.cz/ARCLIB_XML\"><METS:digiprovMD><METS:mdWrap><METS:xmlData><ARCLIB:eventAgents xmlns:ARCLIB=\"http://arclib.lib.cas.cz/ARCLIB_XML\"><ARCLIB:eventAgent><premis:eventType>migration</premis:eventType>\r\n</ARCLIB:eventAgent></ARCLIB:eventAgents></METS:xmlData></METS:mdWrap></METS:digiprovMD></METS:amdSec></METS:mets>"));
}
 
Example 43
Project: convertigo-engine   File: SourcePickerHelperWrap.java   Source Code and License 5 votes vote down vote up
private Document getXpathData(Document document, String xPath) {
    if (document == null) {
        return null;
    }
    if (xPath == null) {
        return null;
    }

    try {
        Document doc = XMLUtils.getDefaultDocumentBuilder().newDocument();
        Element root =  (Element) doc.createElement("root"); 
        doc.appendChild(root);

        NodeList nl = twsCachedXPathAPI.selectNodeList(document, xPath);
        if (nl != null)
            for (int i = 0; i < nl.getLength(); i++) {
                Node node = doc.importNode(nl.item(i), true);
                Element elt = doc.getDocumentElement();
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    elt.appendChild(node);
                }
                if (node.getNodeType() == Node.TEXT_NODE) {
                    elt.appendChild(node);
                }
                if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
                    elt.setAttribute(node.getNodeName() + "_" + i, node.getNodeValue());
                }
            }

        return doc;
    }
    catch (TransformerException e) {
        //ConvertigoPlugin.logWarning("Error for xpath : '" + xPath + "'\r " + e.getMessage());
        return null;
    }
}
 
Example 44
Project: openjdk-jdk10   File: XMLStreamBuffer.java   Source Code and License 5 votes vote down vote up
/**
 * Writes out the contents of this buffer as DOM node and append that to the given node.
 *
 * Faster implementation would be desirable.
 *
 * @return
 *      The newly added child node.
 */
public final Node writeTo(Node n) throws XMLStreamBufferException {
    try {
        Transformer t = trnsformerFactory.get().newTransformer();
        t.transform(new XMLStreamBufferSource(this), new DOMResult(n));
        return n.getLastChild();
    } catch (TransformerException e) {
        throw new XMLStreamBufferException(e);
    }
}
 
Example 45
Project: ccpa   File: TreeOptimizer.java   Source Code and License 5 votes vote down vote up
private static void outputFile() throws TransformerException
{
	TransformerFactory transformerFactory = TransformerFactory.newInstance();
	Transformer transformer = transformerFactory.newTransformer();
	DOMSource source = new DOMSource(doc);
	StreamResult result = new StreamResult(System.out);
	transformer.transform(source, result);
}
 
Example 46
Project: OpenJSharp   File: SourceTreeManager.java   Source Code and License 5 votes vote down vote up
/**
 * Try to create a DOM source tree from the input source.
 *
 * @param source The Source object that identifies the source node.
 * @param locator The location of the caller, for diagnostic purposes.
 *
 * @return non-null reference to node identified by the source argument.
 *
 * @throws TransformerException if the source argument can not be resolved
 *         to a source node.
 */
public int parseToNode(Source source, SourceLocator locator, XPathContext xctxt)
        throws TransformerException
{

  try
  {
    Object xowner = xctxt.getOwnerObject();
    DTM dtm;
    if(null != xowner && xowner instanceof com.sun.org.apache.xml.internal.dtm.DTMWSFilter)
    {
      dtm = xctxt.getDTM(source, false,
                        (com.sun.org.apache.xml.internal.dtm.DTMWSFilter)xowner, false, true);
    }
    else
    {
      dtm = xctxt.getDTM(source, false, null, false, true);
    }
    return dtm.getDocument();
  }
  catch (Exception e)
  {
    //e.printStackTrace();
    throw new TransformerException(e.getMessage(), locator, e);
  }

}
 
Example 47
Project: xpath-to-xml   File: XmlBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldModifyDocumentWhenXPathsAreNotTraversable()
        throws XPathExpressionException, TransformerException, IOException, SAXException {
    Map<String, Object> xmlProperties = fixtureAccessor.getXmlProperties();
    String xml = fixtureAccessor.getPutXml();
    Document oldDocument = stringToXml(xml);
    Document builtDocument = new XmlBuilder(namespaceContext)
            .putAll(xmlProperties)
            .build(oldDocument);

    assertThat(xmlToString(builtDocument)).isEqualTo(fixtureAccessor.getPutValueXml());
}
 
Example 48
Project: directory-ldap-api   File: ParserUtils.java   Source Code and License 5 votes vote down vote up
/**
 * XML Pretty Printer XSLT Transformation
 * 
 * @param document the Dom4j Document
 * @return the transformed document
 */
public static Document styleDocument( Document document )
{
    // load the transformer using JAXP
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = null;

    try
    {
        transformer = factory.newTransformer( new StreamSource( ParserUtils.class
            .getResourceAsStream( "/org/apache/directory/shared/dsmlv2/DSMLv2.xslt" ) ) );
    }
    catch ( TransformerConfigurationException e1 )
    {
        LOG.warn( "Failed to create the XSLT transformer", e1 );
        // return original document
        return document;
    }

    // now lets style the given document
    DocumentSource source = new DocumentSource( document );
    DocumentResult result = new DocumentResult();

    try
    {
        transformer.transform( source, result );
    }
    catch ( TransformerException e )
    {
        // return original document
        return document;
    }

    // return the transformed document
    return result.getDocument();
}
 
Example 49
Project: octoBubbles   File: PersistenceManager.java   Source Code and License 5 votes vote down vote up
public static void exportXMI(Graph pGraph, String path){
    try{
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();

        DOMSource source = new DOMSource(createXmi(pGraph));

        StreamResult result = new StreamResult(new File(path));
        transformer.transform(source, result);
    } catch (TransformerException tfe) {
        tfe.printStackTrace();
    }
}
 
Example 50
Project: jdk8u-jdk   File: Test.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws IOException, TransformerException {

        try {
            String address = deployWebservice();
            Service service = Service.create(new URL(address), ServiceImpl.SERVICE_NAME);

            Dispatch<Source> d = service.createDispatch(ServiceImpl.PORT_NAME, Source.class, Service.Mode.MESSAGE);
            Source response = d.invoke(new StreamSource(new StringReader(XML_REQUEST)));

            String resultXml = toString(response);

            log("= request ======== \n");
            log(XML_REQUEST);
            log("= result ========= \n");
            log(resultXml);
            log("\n==================");

            boolean xsAnyMixedPartSame = resultXml.contains(XS_ANY_MIXED_PART);
            log("resultXml.contains(XS_ANY_PART) = " + xsAnyMixedPartSame);
            if (!xsAnyMixedPartSame) {
                fail("The xs:any content=mixed part is supposed to be same in request and response.");
                throw new RuntimeException();
            }

            log("TEST PASSED");
        } finally {
            stopWebservice();

            // if you need to debug or explore wsdl generation result
            // comment this line out:
            deleteGeneratedFiles();
        }
    }
 
Example 51
Project: xmlrss   File: AbstractXMLRSSTest.java   Source Code and License 5 votes vote down vote up
protected void printDocument(Document document) throws TransformerException {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
//        trans.setOutputProperty(OutputKeys.INDENT, "yes");
//        trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        trans.transform(new DOMSource(document), new StreamResult(System.out));
    }
 
Example 52
Project: openjdk-jdk10   File: Test.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws IOException, TransformerException {

        try {
            String address = deployWebservice();
            Service service = Service.create(new URL(address), ServiceImpl.SERVICE_NAME);

            Dispatch<Source> d = service.createDispatch(ServiceImpl.PORT_NAME, Source.class, Service.Mode.MESSAGE);
            Source response = d.invoke(new StreamSource(new StringReader(XML_REQUEST)));

            String resultXml = toString(response);

            log("= request ======== \n");
            log(XML_REQUEST);
            log("= result ========= \n");
            log(resultXml);
            log("\n==================");

            boolean xsAnyMixedPartSame = resultXml.contains(XS_ANY_MIXED_PART);
            log("resultXml.contains(XS_ANY_PART) = " + xsAnyMixedPartSame);
            if (!xsAnyMixedPartSame) {
                fail("The xs:any content=mixed part is supposed to be same in request and response.");
                throw new RuntimeException();
            }

            log("TEST PASSED");
        } finally {
            stopWebservice();

            // if you need to debug or explore wsdl generation result
            // comment this line out:
            deleteGeneratedFiles();
        }
    }
 
Example 53
Project: openjdk-jdk10   File: XPathParser.java   Source Code and License 5 votes vote down vote up
/**
 *
 * StringExpr  ::=  Expr
 *
 *
 * @throws javax.xml.transform.TransformerException
 */
protected void StringExpr() throws javax.xml.transform.TransformerException
{

  int opPos = m_ops.getOp(OpMap.MAPINDEX_LENGTH);

  appendOp(2, OpCodes.OP_STRING);
  Expr();

  m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH,
    m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos);
}
 
Example 54
Project: OpenJSharp   File: EfficientStreamingTransformer.java   Source Code and License 5 votes vote down vote up
public String getOutputProperty(String str)
    throws java.lang.IllegalArgumentException {
    try {
        materialize();
        return m_realTransformer.getOutputProperty(str);
    } catch (TransformerException e) {
        // will be caught later
    }
    return null;
}
 
Example 55
Project: openjdk-jdk10   File: TransformerHandlerImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Implements org.xml.sax.ContentHandler.endDocument()
 * Receive notification of the end of a document.
 */
@Override
public void endDocument() throws SAXException {
    // Signal to the DOMBuilder that the document is complete
    _handler.endDocument();

    if (!_isIdentity) {
        // Run the transformation now if we have a reference to a Result object
        if (_result != null) {
            try {
                _transformer.setDOM(_dom);
                _transformer.transform(null, _result);
            }
            catch (TransformerException e) {
                throw new SAXException(e);
            }
        }
        // Signal that the internal DOM is built (see 'setResult()').
        _done = true;

        // Set this DOM as the transformer's DOM
        _transformer.setDOM(_dom);
    }
    if (_isIdentity && _result instanceof DOMResult) {
        ((DOMResult)_result).setNode(_transformer.getTransletOutputHandlerFactory().getNode());
    }
}
 
Example 56
Project: RA-Reader   File: WriteToXML.java   Source Code and License 5 votes vote down vote up
public void writeDOM(Document doc, FileWriter inputFile) throws SAXException, IOException, TransformerConfigurationException, TransformerException, ParserConfigurationException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    Result output = new StreamResult(inputFile);
    Source input = new DOMSource(doc);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(input, output);
}
 
Example 57
Project: sbc-qsystem   File: XsltTester.java   Source Code and License 4 votes vote down vote up
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    if (args.length != 3) {
        System.err.println("Where are three parameters required: xml xsl txt");
        System.err
            .println("URL for file ex: file:///E:/temp/Xslt/data/official_exchange_rates.xsl");
        System.exit(1);
    }

    try {
        String url = args[0];

        final Pattern pattern = Pattern.compile("##.+?##");
        final Matcher matcher = pattern.matcher(url);
        // check all occurance
        while (matcher.find()) {
            System.out.print("Start index: " + matcher.start());
            System.out.print(" End index: " + matcher.end() + " ");
            System.out.println(matcher.group());
            SimpleDateFormat sdf = new SimpleDateFormat(
                matcher.group().substring(2, (matcher.group().length() - 2)));
            url = url.replace(matcher.group(), sdf.format(new Date()));
        }
        System.out.println(url);

        final URL xmlIn = new URL(url);

        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder builder = factory.newDocumentBuilder();
        //document = builder.parse(datafile);
        final Document document = builder.parse(xmlIn.openStream());

        // Use a Transformer for output
        final URL xslIn = new URL(args[1]);
        //StreamSource stylesource = new StreamSource(stylesheet);
        final StreamSource stylesource = new StreamSource(xslIn.openStream());

        final TransformerFactory tFactory = TransformerFactory.newInstance();
        final Transformer transformer = tFactory.newTransformer(stylesource);

        final DOMSource source = new DOMSource(document);
        final FileOutputStream fos = new FileOutputStream(args[2]);
        final StreamResult resultF = new StreamResult(fos);
        final StreamResult result = new StreamResult(System.out);
        transformer.transform(source, result);
        transformer.transform(source, resultF);
    } catch (TransformerConfigurationException tce) {
        // Error generated by the parser
        System.out.println("\n** Transformer Factory error");
        System.out.println("   " + tce.getMessage());
    } catch (TransformerException te) {
        // Error generated by the parser
        System.out.println("\n** Transformation error");
        System.out.println("   " + te.getMessage());
    } catch (SAXException sxe) {
        System.out.println("\n** Parsing error");
        System.out.println("   " + sxe.getMessage());
    } catch (ParserConfigurationException pce) {
        System.out.println("\n** Parsing configuration error");
        System.out.println("   " + pce.getMessage());
    } catch (IOException ioe) {
        System.out.println("\n** Reading or writing error");
        System.out.println("   " + ioe.getMessage());
    }
}
 
Example 58
Project: parabuild-ci   File: CopyEmitter.java   Source Code and License 4 votes vote down vote up
/** Copy set unparsed entity events. */
public void setUnparsedEntity(java.lang.String name, java.lang.String uri)
  throws TransformerException {
  rtfEmitter.setUnparsedEntity(name, uri);
}
 
Example 59
Project: uroborosql   File: CoberturaCoverageHandler.java   Source Code and License 4 votes vote down vote up
synchronized void write() throws IOException, ParserConfigurationException, TransformerException {
	if (!updated) {//更新が無い場合は書き込みしない
		return;
	}

	List<PackageSummary> packageNodes = summaryPackages();

	DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
	Document document = documentBuilder.newDocument();

	Element coverage = document.createElement("coverage");

	coverage.setAttribute("timestamp", String.valueOf(System.currentTimeMillis()));
	coverage.setAttribute("complexity", "0");
	coverage.setAttribute("version", "0.1");

	document.appendChild(coverage);
	Element sources = document.createElement("sources");
	coverage.appendChild(sources);
	Element source = document.createElement("source");
	source.setTextContent(sourcesDirPath.toString());
	sources.appendChild(source);

	Element packages = document.createElement("packages");
	coverage.appendChild(packages);

	//packages内のrenderとカバレッジ集計
	CoverageSummaryTotal total = renderPackages(document, packages, packageNodes);

	CoverageSummary lines = total.line;
	coverage.setAttribute("lines-valid", String.valueOf(lines.valid));
	coverage.setAttribute("lines-covered", String.valueOf(lines.covered));
	coverage.setAttribute("lines-rate", String.valueOf(lines.getRate()));

	CoverageSummary branches = total.branch;
	coverage.setAttribute("branches-valid", String.valueOf(branches.valid));
	coverage.setAttribute("branches-covered", String.valueOf(branches.covered));
	coverage.setAttribute("branches-rate", String.valueOf(branches.getRate()));

	write(document);

	//書込が終了したので「更新なし」にする
	updated = false;
}
 
Example 60
Project: alvisnlp   File: AbstractAlvisNLP.java   Source Code and License 4 votes vote down vote up
@CLIOption(value="-libraryDocXML", stop=true)
public final void libraryDocXML(String name) throws TransformerFactoryConfigurationError, TransformerException { 
	Source source = new DOMSource(getLibraryDocumentation(name));
	Result result = new StreamResult(System.out);
	xmlDocTransformer.transform(source, result);
}