Java 类javax.xml.transform.TransformerException 实例源码

项目:gradle-circle-style    文件:CircleBuildFinishedAction.java   
@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);
    }
}
项目:oscm    文件:WsdlHandleTask.java   
@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);
    }
}
项目:openjdk-jdk10    文件:SystemIDResolver.java   
/**
 * 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());
}
项目:OperatieBRP    文件:AbstractDienstVerzoekParser.java   
/**
 * 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;
}
项目:openjdk-jdk10    文件:XPathImpl.java   
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);
        }
    }
}
项目:oscm    文件:XmlDocument.java   
/**
 * 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);
    }
}
项目:openjdk-jdk10    文件:XPathParser.java   
/**
 * 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);
  }
}
项目:incubator-ratis    文件:RaftProperties.java   
/**
 * 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);
  }
}
项目:EVE    文件:Weather.java   
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));
}
项目:oscm    文件:PaypalRequest.java   
/**
 * 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;
}
项目:code-sentinel    文件:asl2xml.java   
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;
}
项目:OpenJSharp    文件:TransformerFactoryImpl.java   
/**
 * 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;
}
项目:KeYExperienceReport    文件:SPLOpltionGenerator.java   
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!");

}
项目:openjdk-jdk10    文件:TransformerFactoryImpl.java   
/**
 * 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
    }
}
项目:KeYExperienceReport    文件:FeatureIdeOpltionGenerator.java   
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!");

}
项目:openjdk-jdk10    文件:TransformerImpl.java   
/**
 * 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;
}
项目:KeYExperienceReport    文件:SPL2OpltionGenerator.java   
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!");

}
项目:pay    文件:XmlUtils.java   
/**
 * 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;
}
项目:openjdk-jdk10    文件:XPath.java   
/**
 * 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());
  }
}
项目:openjdk-jdk10    文件:TransformerFactoryImpl.java   
/**
 * 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()));
    }
}
项目:xpath-to-xml    文件:XmlBuilderTest.java   
@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());
}
项目:neoscada    文件:SignatureRequestBuilder.java   
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 ();
}
项目:openjdk-jdk10    文件:TransformerExcpTest.java   
/**
 * 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());
    }
}
项目:OpenJSharp    文件:SourceTreeManager.java   
/**
 * 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);
   }*/
}
项目:parabuild-ci    文件:UnwrapLinks.java   
/**
  * <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;
   }
 }
项目:alvisnlp    文件:XMLReader.java   
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();
}
项目:OperatieBRP    文件:AbstractGeneriekeBerichtParser.java   
/**
 * 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);
    }
}
项目:OpenJSharp    文件:EfficientStreamingTransformer.java   
public void setURIResolver(javax.xml.transform.URIResolver uRIResolver) {
    try {
        materialize();
        m_realTransformer.setURIResolver(uRIResolver);
    } catch (TransformerException e) {
        // will be caught later
    }
}
项目:OpenJSharp    文件:XPath.java   
/**
 * 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;
}
项目:qpp-conversion-tool    文件:MarkupManipulator.java   
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);
    }
}
项目:api-harvester    文件:Main.java   
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);
}
项目:alvisnlp    文件:XMLReader.java   
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);
}
项目:jdk8u-jdk    文件:SaajEmptyNamespaceTest.java   
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;
}
项目:openjdk-jdk10    文件:XPathParser.java   
/**
 *
 * 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);
}
项目:openjdk-jdk10    文件:WSEndpointReference.java   
/**
 * 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();
    }
}
项目:openjdk-jdk10    文件:XPathParser.java   
/**
 * 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);
}
项目:alvisnlp    文件:LibraryModel.java   
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();
}
项目:openjdk-jdk10    文件:XPathParser.java   
/**
 *
 * 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);
}
项目:openjdk-jdk10    文件:TransformerTest.java   
@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"));
}
项目:OpenJSharp    文件:CachedXPathAPI.java   
/**
 * 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();
}