javax.xml.transform.Source Java Examples

The following examples show how to use javax.xml.transform.Source. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Unified2OrchestraTransformer.java    From fix-orchestra with Apache License 2.0 6 votes vote down vote up
public void transform(File inputXml, File phrasesFile, File outputXml)
    throws TransformerException {
  final File parentFile = outputXml.getParentFile();
  if (parentFile != null) {
    parentFile.mkdirs();
  }

  final Source xmlSource = new javax.xml.transform.stream.StreamSource(inputXml);
  final InputStream xsltFile =
      getClass().getClassLoader().getResourceAsStream("xsl/unified2orchestra.xslt");
  final Source xsltSource = new javax.xml.transform.stream.StreamSource(xsltFile);
  final Result result = new javax.xml.transform.stream.StreamResult(outputXml);

  final TransformerFactory transFact = new TransformerFactoryImpl();
  final Transformer trans = transFact.newTransformer(xsltSource);
  trans.setParameter("phrases-file", phrasesFile.toURI().toString());
  trans.transform(xmlSource, result);
}
 
Example #2
Source File: AbstractSourcePayloadProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static String getSourceAsString(Source s) throws Exception {
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        try (Writer out = new StringWriter()) {
            StreamResult streamResult = new StreamResult();
            streamResult.setWriter(out);
            transformer.transform(s, streamResult);
            return streamResult.getWriter().toString();
        }
    } catch (TransformerException te) {
        if ("javax.xml.transform.stax.StAXSource".equals(s.getClass().getName())) {
            //on java6, we will get this class if "stax" is configured
            //for the preferred type. However, older xalans don't know about it
            //we'll manually do it
            XMLStreamReader r = (XMLStreamReader)s.getClass().getMethod("getXMLStreamReader").invoke(s);
            return StaxUtils.toString(StaxUtils.read(r).getDocumentElement());
        }
        throw te;
    }
}
 
Example #3
Source File: UnmarshallerImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public Object unmarshal0( Source source, JaxBeanInfo expectedType ) throws JAXBException {
    if (source instanceof SAXSource) {
        SAXSource ss = (SAXSource) source;

        XMLReader locReader = ss.getXMLReader();
        if (locReader == null) {
            locReader = getXMLReader();
        }

        return unmarshal0(locReader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
        return unmarshal0(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource) {
        return unmarshal0(((DOMSource) source).getNode(), expectedType);
    }

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example #4
Source File: DOMForest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks the correctness of the XML Schema documents and return true
 * if it's OK.
 *
 * <p>
 * This method performs a weaker version of the tests where error messages
 * are provided without line number information. So whenever possible
 * use {@link SchemaConstraintChecker}.
 *
 * @see SchemaConstraintChecker
 */
public boolean checkSchemaCorrectness(ErrorReceiver errorHandler) {
    try {
        boolean disableXmlSecurity = false;
        if (options != null) {
            disableXmlSecurity = options.disableXmlSecurity;
        }
        SchemaFactory sf = XmlFactory.createSchemaFactory(W3C_XML_SCHEMA_NS_URI, disableXmlSecurity);
        ErrorReceiverFilter filter = new ErrorReceiverFilter(errorHandler);
        sf.setErrorHandler(filter);
        Set<String> roots = getRootDocuments();
        Source[] sources = new Source[roots.size()];
        int i=0;
        for (String root : roots) {
            sources[i++] = new DOMSource(get(root),root);
        }
        sf.newSchema(sources);
        return !filter.hadError();
    } catch (SAXException e) {
        // the errors should have been reported
        return false;
    }
}
 
Example #5
Source File: RuleFlowMigrator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static void transform(String stylesheet,
                             Source src,
                             Result res,
                             HashMap<String, String> params) throws Exception {

    Transformer transformer = getTransformer(stylesheet);

    transformer.clearParameters();

    if (params != null && params.size() > 0) {
        Iterator<String> itKeys = params.keySet().iterator();

        while (itKeys.hasNext()) {
            String key = itKeys.next();
            String value = params.get(key);
            transformer.setParameter(key,
                                     value);
        }
    }

    transformer.transform(src,
                          res);
}
 
Example #6
Source File: HandlerChainInvokerTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private String getSourceAsString(Source s) {
    String result = "";

    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        OutputStream out = new ByteArrayOutputStream();
        StreamResult streamResult = new StreamResult();
        streamResult.setOutputStream(out);
        transformer.transform(s, streamResult);
        return streamResult.getOutputStream().toString();
    } catch (Exception e) {
        //do nothing
    }
    return result;
}
 
Example #7
Source File: JAXRSServiceImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void createMessagePartInfo(OperationInfo oi, Class<?> type, QName qname, Method m,
                                   boolean input) {
    if (type == void.class || Source.class.isAssignableFrom(type)) {
        return;
    }
    if (InjectionUtils.isPrimitive(type) || Response.class == type) {
        return;
    }
    QName mName = new QName(qname.getNamespaceURI(),
                            (input ? "in" : "out") + m.getName());
    MessageInfo ms = oi.createMessage(mName,
                                       input ? MessageInfo.Type.INPUT : MessageInfo.Type.OUTPUT);
    if (input) {
        oi.setInput("in", ms);
    } else {
        oi.setOutput("out", ms);
    }
    QName mpQName = JAXRSUtils.getClassQName(type);
    MessagePartInfo mpi = ms.addMessagePart(mpQName);
    mpi.setConcreteName(mpQName);
    mpi.setTypeQName(mpQName);
    mpi.setTypeClass(type);
}
 
Example #8
Source File: SmartTransformerFactoryImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a Transformer object that from the input stylesheet
 * Uses the com.sun.org.apache.xalan.internal.processor.TransformerFactory.
 * @param source the stylesheet.
 * @return A Transformer object.
 */
public Transformer newTransformer(Source source) throws
    TransformerConfigurationException
{
    if (_xalanFactory == null) {
        createXalanTransformerFactory();
    }
    if (_errorlistener != null) {
        _xalanFactory.setErrorListener(_errorlistener);
    }
    if (_uriresolver != null) {
        _xalanFactory.setURIResolver(_uriresolver);
    }
    _currFactory = _xalanFactory;
    return _currFactory.newTransformer(source);
}
 
Example #9
Source File: UnmarshallerImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public Object unmarshal0( Source source, JaxBeanInfo expectedType ) throws JAXBException {
    if (source instanceof SAXSource) {
        SAXSource ss = (SAXSource) source;

        XMLReader locReader = ss.getXMLReader();
        if (locReader == null) {
            locReader = getXMLReader();
        }

        return unmarshal0(locReader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
        return unmarshal0(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource) {
        return unmarshal0(((DOMSource) source).getNode(), expectedType);
    }

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example #10
Source File: SourceTreeManager.java    From openjdk-8-source with GNU General Public License v2.0 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 #11
Source File: XsltView.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected void renderMergedOutputModel(
		Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
		throws Exception {

	Templates templates = this.cachedTemplates;
	if (templates == null) {
		templates = loadTemplates();
	}

	Transformer transformer = createTransformer(templates);
	configureTransformer(model, response, transformer);
	configureResponse(model, response, transformer);
	Source source = null;
	try {
		source = locateSource(model);
		if (source == null) {
			throw new IllegalArgumentException("Unable to locate Source object in model: " + model);
		}
		transformer.transform(source, createResult(response));
	}
	finally {
		closeSourceIfNecessary(source);
	}
}
 
Example #12
Source File: XmlFormatter.java    From journaldev with MIT License 6 votes vote down vote up
public static String prettyFormat(String input, String indent) {
	Source xmlInput = new StreamSource(new StringReader(input));
	StringWriter stringWriter = new StringWriter();
	try {
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", indent);
		transformer.transform(xmlInput, new StreamResult(stringWriter));

		return stringWriter.toString().trim();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #13
Source File: NamespacePrefixTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testConcurrentTransformations() throws Exception {
    final TransformerFactory tf = TransformerFactory.newInstance();
    final Source xslsrc = new StreamSource(new StringReader(XSL));
    final Templates tmpl = tf.newTemplates(xslsrc);
    concurrentTestPassed.set(true);

    // Execute multiple TestWorker tasks
    for (int id = 0; id < THREADS_COUNT; id++) {
        EXECUTOR.execute(new TransformerThread(tmpl.newTransformer(), id));
    }
    // Initiate shutdown of previously submitted task
    EXECUTOR.shutdown();
    // Wait for termination of submitted tasks
    if (!EXECUTOR.awaitTermination(THREADS_COUNT, TimeUnit.SECONDS)) {
        // If not all tasks terminates during the time out force them to shutdown
        EXECUTOR.shutdownNow();
    }
    // Check if all transformation threads generated the correct namespace prefix
    assertTrue(concurrentTestPassed.get());
}
 
Example #14
Source File: SAXImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct a SAXImpl object using the default block size.
 */
public SAXImpl(XSLTCDTMManager mgr, Source source,
               int dtmIdentity, DTMWSFilter whiteSpaceFilter,
               XMLStringFactory xstringfactory,
               boolean doIndexing, boolean buildIdIndex)
{
    this(mgr, source, dtmIdentity, whiteSpaceFilter, xstringfactory,
        doIndexing, DEFAULT_BLOCKSIZE, buildIdIndex, false);
}
 
Example #15
Source File: SAAJMessage.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gets the attachment as a {@link javax.xml.transform.Source}.
 * Note that there's no guarantee that the attachment is actually an XML.
 */
public Source asSource() {
    try {
        return new StreamSource(ap.getRawContent());
    } catch (SOAPException e) {
        throw new WebServiceException(e);
    }
}
 
Example #16
Source File: AntProjectModule.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean verifyWriterCorrect() throws Exception {
    final String IDENTITY_XSLT_WITH_INDENT =
            "<xsl:stylesheet version='1.0' " + // NOI18N
            "xmlns:xsl='http://www.w3.org/1999/XSL/Transform' " + // NOI18N
            "xmlns:xalan='http://xml.apache.org/xslt' " + // NOI18N
            "exclude-result-prefixes='xalan'>" + // NOI18N
            "<xsl:output method='xml' indent='yes' xalan:indent-amount='4'/>" + // NOI18N
            "<xsl:template match='@*|node()'>" + // NOI18N
            "<xsl:copy>" + // NOI18N
            "<xsl:apply-templates select='@*|node()'/>" + // NOI18N
            "</xsl:copy>" + // NOI18N
            "</xsl:template>" + // NOI18N
            "</xsl:stylesheet>"; // NOI18N
    String data = "<root xmlns='root'/>"; // NOI18N
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(data)));
    doc.getDocumentElement().appendChild(doc.createElementNS("child", "child")); // NOI18N
    Transformer t = TransformerFactory.newInstance().newTransformer(
            new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
    Source source = new DOMSource(doc);
    CharArrayWriter output = new CharArrayWriter();
    Result result = new StreamResult(output);
    t.transform(source, result);
    
    output.close();
    
    String text = output.toString();
    
    return text.indexOf("\"child\"") != (-1) || text.indexOf("'child'") != (-1); // NOI18N
}
 
Example #17
Source File: SAX2DTM2.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct a SAX2DTM2 object using the given block size.
 */
public SAX2DTM2(DTMManager mgr, Source source, int dtmIdentity,
               DTMWSFilter whiteSpaceFilter,
               XMLStringFactory xstringfactory,
               boolean doIndexing,
               int blocksize,
               boolean usePrevsib,
               boolean buildIdIndex,
               boolean newNameTable)
{

  super(mgr, source, dtmIdentity, whiteSpaceFilter,
        xstringfactory, doIndexing, blocksize, usePrevsib, newNameTable);

  // Initialize the values of m_SHIFT and m_MASK.
  int shift;
  for(shift=0; (blocksize>>>=1) != 0; ++shift);

  m_blocksize = 1<<shift;
  m_SHIFT = shift;
  m_MASK = m_blocksize - 1;

  m_buildIdIndex = buildIdIndex;

  // Some documents do not have attribute nodes. That is why
  // we set the initial size of this Vector to be small and set
  // the increment to a bigger number.
  m_values = new Vector(32, 512);

  m_maxNodeIndex = 1 << DTMManager.IDENT_DTM_NODE_BITS;

  // Set the map0 values in the constructor.
  m_exptype_map0 = m_exptype.getMap0();
  m_nextsib_map0 = m_nextsib.getMap0();
  m_firstch_map0 = m_firstch.getMap0();
  m_parent_map0  = m_parent.getMap0();
}
 
Example #18
Source File: Bug4892774.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testStAX2DOM() {
    try {
        Source input = staxUtil.prepareStreamSource(this.getClass().getResourceAsStream(XML10_FILE));
        DOMResult domResult = (DOMResult) domUtil.prepareResult();
        idTransform.transform(input, domResult);
        domUtil.checkResult(domResult, "1.0");
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Exception occured: " + e.getMessage());
    }
}
 
Example #19
Source File: LogicalMessageImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public Source getPayload() {
    assert (!(payloadSrc instanceof DOMSource));
    try {
        Transformer transformer = XmlUtil.newTransformer();
        DOMResult domResult = new DOMResult();
        transformer.transform(payloadSrc, domResult);
        DOMSource dom = new DOMSource(domResult.getNode());
        lm = new DOMLogicalMessageImpl((DOMSource) dom);
        payloadSrc = null;
        return dom;
    } catch (TransformerException te) {
        throw new WebServiceException(te);
    }
}
 
Example #20
Source File: AbstractSchematronResource.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
@Nullable
public SchematronOutputType applySchematronValidationToSVRL (@Nonnull final Source aXMLSource) throws Exception
{
  if (!isValidSchematron ())
    return null;

  final Node aXMLNode = getAsNode (aXMLSource);
  if (aXMLNode == null)
    return null;

  return applySchematronValidationToSVRL (aXMLNode, aXMLSource.getSystemId ());
}
 
Example #21
Source File: SmartTransformerFactoryImpl.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Get a TransformerHandler object that can process SAX ContentHandler
 * events based on a transformer specified by the stylesheet Source.
 * Uses com.sun.org.apache.xalan.internal.processor.TransformerFactory.
 */
public TransformerHandler newTransformerHandler(Source src)
    throws TransformerConfigurationException
{
    if (_xalanFactory == null) {
        createXalanTransformerFactory();
    }
    if (_errorlistener != null) {
        _xalanFactory.setErrorListener(_errorlistener);
    }
    if (_uriresolver != null) {
        _xalanFactory.setURIResolver(_uriresolver);
    }
    return _xalanFactory.newTransformerHandler(src);
}
 
Example #22
Source File: SourceTreeManager.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
   * Given a Source object, find the node associated with it.
   *
   * @param source The Source object to act as the key.
   *
   * @return The node that is associated with the Source, or null if not found.
   */
  public int getNode(Source source)
  {

//    if (source instanceof DOMSource)
//      return ((DOMSource) source).getNode();

    // TODO: Not sure if the BaseID is really the same thing as the ID.
    String url = source.getSystemId();

    if (null == url)
      return DTM.NULL;

    int n = m_sourceTree.size();

    // System.out.println("getNode: "+n);
    for (int i = 0; i < n; i++)
    {
      SourceTree sTree = (SourceTree) m_sourceTree.elementAt(i);

      // System.out.println("getNode -         url: "+url);
      // System.out.println("getNode - sTree.m_url: "+sTree.m_url);
      if (url.equals(sTree.m_url))
        return sTree.m_root;
    }

    // System.out.println("getNode - returning: "+node);
    return DTM.NULL;
  }
 
Example #23
Source File: ClientServerSwaTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testSwaTypes() throws Exception {
    SwAService service = new SwAService();

    SwAServiceInterface port = service.getSwAServiceHttpPort();
    setAddress(port, "http://localhost:" + serverPort + "/swa");

    URL url1 = this.getClass().getResource("resources/attach.text");
    URL url2 = this.getClass().getResource("resources/attach.html");
    URL url3 = this.getClass().getResource("resources/attach.xml");
    URL url4 = this.getClass().getResource("resources/attach.jpeg1");
    URL url5 = this.getClass().getResource("resources/attach.gif");

    DataHandler dh1 = new DataHandler(url1);
    DataHandler dh2 = new DataHandler(url2);
    DataHandler dh3 = new DataHandler(url3);
    //DataHandler dh4 = new DataHandler(url4);
    //DataHandler dh5 = new DataHandler(url5);
    Holder<DataHandler> attach1 = new Holder<>();
    attach1.value = dh1;
    Holder<DataHandler> attach2 = new Holder<>();
    attach2.value = dh2;
    Holder<Source> attach3 = new Holder<>();
    attach3.value = new StreamSource(dh3.getInputStream());
    Holder<Image> attach4 = new Holder<>();
    Holder<Image> attach5 = new Holder<>();
    attach4.value = ImageIO.read(url4);
    attach5.value = ImageIO.read(url5);
    VoidRequest request = new VoidRequest();
    OutputResponseAll response = port.echoAllAttachmentTypes(request, attach1, attach2, attach3, attach4,
                                                             attach5);

    assertNotNull(response);
    Map<?, ?> map = CastUtils.cast((Map<?, ?>)((BindingProvider)port).getResponseContext()
                                       .get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS));
    assertNotNull(map);
    assertEquals(5, map.size());
}
 
Example #24
Source File: LogicalMessageImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private ImmutableLM createLogicalMessageImpl(Source payload) {
    if (payload == null) {
        lm = new EmptyLogicalMessageImpl();
    } else if (payload instanceof DOMSource) {
        lm = new DOMLogicalMessageImpl((DOMSource) payload);
    } else {
        lm = new SourceLogicalMessageImpl(payload);
    }
    return lm;
}
 
Example #25
Source File: MarshallingMessageConverter.java    From java-technology-stack with MIT License 5 votes vote down vote up
private Source getSource(Object payload) {
	if (payload instanceof byte[]) {
		return new StreamSource(new ByteArrayInputStream((byte[]) payload));
	}
	else {
		return new StreamSource(new StringReader((String) payload));
	}
}
 
Example #26
Source File: BasicJavaClientREST.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
/**
 * Convert inputsource to string. Used on InputSourceHandle
 * 
 * @param fileRead
 * @return
 * @throws IOException
 * @throws TransformerException
 */
public String convertInputSourceToString(InputSource fileRead) throws IOException, TransformerException
{
  Source saxsrc = new SAXSource(fileRead);
  TransformerFactory tf = TransformerFactory.newInstance();
  Transformer transformer = tf.newTransformer();
  transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  StringWriter writer = new StringWriter();
  transformer.transform(saxsrc, new StreamResult(writer));
  String output = writer.getBuffer().toString();
  return output;
}
 
Example #27
Source File: BonitaToBPMNExporter.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private void generateXSDForConnector(final File connectorToTransform)
        throws URISyntaxException, IOException, TransformerException {
    if (xslTemplate == null) {
        final TransformerFactory transFact = TransformerFactory.newInstance();
        final URL xsltUrl = ConnectorPlugin.getDefault().getBundle().getEntry("transfo/genConnectorsXSD.xsl");
        final File xsltFileoriginal = new File(FileLocator.toFileURL(xsltUrl).getFile());
        final Source xsltSource = new StreamSource(xsltFileoriginal);
        xslTemplate = transFact.newTemplates(xsltSource);
    }

    //FIXME: this is only a workaround because currently we can't serialize the xml file in a way that both EMF and xslt can handle it correctly
    // see http://java.dzone.com/articles/emf-reading-model-xml-%E2%80%93-how
    final File connectorToTransformWC = File.createTempFile(connectorToTransform.getName(), "");
    FileUtil.copy(connectorToTransform, connectorToTransformWC);
    FileUtil.replaceStringInFile(connectorToTransformWC,
            "xmlns:definition=\"http://www.bonitasoft.org/ns/connector/definition/6.0\"",
            "xmlns=\"http://www.bonitasoft.org/ns/connector/definition/6.0\" xmlns:definition=\"http://www.bonitasoft.org/ns/connector/definition/6.0\"");

    final Source xmlSource = new StreamSource(connectorToTransformWC);

    final String generatedXsdName = connectorToTransform.getName() + "connectors.xsd";
    final File connectorsDefFolder = new File(
            destBpmnFile.getParentFile().getAbsolutePath() + File.separator + "connectorDefs");
    if (!connectorsDefFolder.exists()) {
        connectorsDefFolder.mkdirs();
    }
    try (final OutputStream stream = new FileOutputStream(
            new File(connectorsDefFolder.getAbsolutePath(), generatedXsdName))) {
        final Result result = new StreamResult(stream);
        final Transformer transformer = xslTemplate.newTransformer();
        transformer.setParameter("indent", true);
        transformer.transform(xmlSource, result);
    } finally {
        connectorToTransformWC.delete();
    }
}
 
Example #28
Source File: RuntimeBuiltinLeafInfoImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public Source parse(CharSequence text) throws SAXException  {
    try {
        if(text instanceof Base64Data)
            return new DataSourceSource( ((Base64Data)text).getDataHandler() );
        else
            return new DataSourceSource(new ByteArrayDataSource(decodeBase64(text),
                UnmarshallingContext.getInstance().getXMIMEContentType()));
    } catch (MimeTypeParseException e) {
        UnmarshallingContext.getInstance().handleError(e);
        return null;
    }
}
 
Example #29
Source File: XMLProviderArgumentBuilder.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
static XMLProviderArgumentBuilder createBuilder(ProviderEndpointModel model, WSBinding binding) {
    if (model.mode == Service.Mode.PAYLOAD) {
        return new PayloadSource();
    } else {
        if(model.datatype==Source.class)
            return new PayloadSource();
        if(model.datatype== DataSource.class)
            return new DataSourceParameter(binding);
        throw new WebServiceException(ServerMessages.PROVIDER_INVALID_PARAMETER_TYPE(model.implClass,model.datatype));
    }
}
 
Example #30
Source File: ColocUtil.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void convertSourceToObject(Message message) {
    List<Object> content = CastUtils.cast(message.getContent(List.class));
    if (content == null || content.isEmpty()) {
        // nothing to convert
        return;
    }
    // only supporting the wrapped style for now  (one pojo <-> one source)
    Source source = (Source)content.get(0);
    DataReader<XMLStreamReader> reader =
        message.getExchange().getService().getDataBinding().createReader(XMLStreamReader.class);
    MessagePartInfo mpi = getMessageInfo(message).getMessagePart(0);
    XMLStreamReader streamReader = null;
    Object wrappedObject = null;
    try {
        streamReader = StaxUtils.createXMLStreamReader(source);
        wrappedObject = reader.read(mpi, streamReader);
    } finally {
        try {
            StaxUtils.close(streamReader);
        } catch (XMLStreamException e) {
            // Ignore
        }
    }
    MessageContentsList parameters = new MessageContentsList();
    parameters.put(mpi, wrappedObject);

    message.setContent(List.class, parameters);
}