Java Code Examples for org.apache.cxf.helpers.IOUtils#copy()
The following examples show how to use
org.apache.cxf.helpers.IOUtils#copy() .
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: EngineLifecycleTest.java From cxf with Apache License 2.0 | 6 votes |
private static void verifyStaticHtml() throws Exception { String response = null; for (int i = 0; i < 50 && null == response; i++) { try (InputStream in = new URL("http://localhost:" + PORT2 + "/test.html").openConnection() .getInputStream()) { ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(in, os); response = new String(os.toByteArray()); } catch (Exception ex) { Thread.sleep(100L); } } assertNotNull("Test doc can not be read", response); String html; try (InputStream htmlFile = EngineLifecycleTest.class.getResourceAsStream("test.html")) { byte[] buf = new byte[htmlFile.available()]; htmlFile.read(buf); html = new String(buf); } assertEquals("Can't get the right test html", html, response); }
Example 2
Source File: AbstractHTTPServlet.java From cxf with Apache License 2.0 | 6 votes |
protected void serveStaticContent(HttpServletRequest request, HttpServletResponse response, String pathInfo) throws ServletException { try (InputStream is = getResourceAsStream(pathInfo)) { if (is == null) { throw new ServletException("Static resource " + pathInfo + " is not available"); } int ind = pathInfo.lastIndexOf('.'); if (ind > 0) { String type = getStaticResourceContentType(pathInfo.substring(ind + 1)); if (type != null) { response.setContentType(type); } } String cacheControl = getServletConfig().getInitParameter(STATIC_CACHE_CONTROL); if (cacheControl != null) { response.setHeader("Cache-Control", cacheControl.trim()); } IOUtils.copy(is, response.getOutputStream()); } catch (IOException ex) { throw new ServletException("Static resource " + pathInfo + " can not be written to the output stream"); } }
Example 3
Source File: EndpointImplTest.java From cxf with Apache License 2.0 | 6 votes |
public void onMessage(Message message) { try { Conduit backChannel = message.getDestination().getBackChannel(message); backChannel.prepare(message); OutputStream out = message.getContent(OutputStream.class); assertNotNull(out); InputStream in = message.getContent(InputStream.class); assertNotNull(in); IOUtils.copy(in, out, 2045); out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } }
Example 4
Source File: GenericWebServiceServlet.java From BIMserver with GNU Affero General Public License v3.0 | 6 votes |
protected void serveStaticContent(HttpServletRequest request, HttpServletResponse response, String pathInfo) throws ServletException { InputStream is = super.getServletContext().getResourceAsStream(pathInfo); if (is == null) { throw new ServletException("Static resource " + pathInfo + " is not available"); } try { int ind = pathInfo.lastIndexOf("."); if (ind != -1 && ind < pathInfo.length()) { String type = STATIC_CONTENT_TYPES.get(pathInfo.substring(ind + 1)); if (type != null) { response.setContentType(type); } } ServletOutputStream os = response.getOutputStream(); IOUtils.copy(is, os); os.flush(); } catch (IOException ex) { throw new ServletException("Static resource " + pathInfo + " can not be written to the output stream"); } }
Example 5
Source File: AbstractCommand.java From tomee with Apache License 2.0 | 5 votes |
protected String format(final String json) throws IOException { final StringIndenter formatter = new StringIndenter(json); final Writer outWriter = new StringWriter(); IOUtils.copy(new StringReader(formatter.result()), outWriter, 2048); outWriter.close(); return outWriter.toString(); }
Example 6
Source File: MAPAggregatorImpl.java From cxf with Apache License 2.0 | 5 votes |
/** * Called for an incoming message. * * @param inMessage */ public void onMessage(Message inMessage) { // disposable exchange, swapped with real Exchange on correlation inMessage.setExchange(new ExchangeImpl()); inMessage.getExchange().put(Bus.class, bus); inMessage.put(Message.DECOUPLED_CHANNEL_MESSAGE, Boolean.TRUE); inMessage.put(Message.RESPONSE_CODE, HttpURLConnection.HTTP_OK); // remove server-specific properties //inMessage.remove(AbstractHTTPDestination.HTTP_REQUEST); //inMessage.remove(AbstractHTTPDestination.HTTP_RESPONSE); inMessage.remove(Message.ASYNC_POST_RESPONSE_DISPATCH); updateResponseCode(inMessage); //cache this inputstream since it's defer to use in case of async try { InputStream in = inMessage.getContent(InputStream.class); if (in != null) { CachedOutputStream cos = new CachedOutputStream(); IOUtils.copy(in, cos); inMessage.setContent(InputStream.class, cos.getInputStream()); } observer.onMessage(inMessage); } catch (IOException e) { e.printStackTrace(); } }
Example 7
Source File: JAXBAttachmentUnmarshaller.java From cxf with Apache License 2.0 | 5 votes |
@Override public byte[] getAttachmentAsByteArray(String contentId) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { InputStream is = AttachmentUtil.getAttachmentDataSource(contentId, attachments) .getInputStream(); IOUtils.copy(is, bos); is.close(); bos.close(); } catch (IOException e) { throw new Fault(new org.apache.cxf.common.i18n.Message("ATTACHMENT_READ_ERROR", LOG), e); } return bos.toByteArray(); }
Example 8
Source File: AttachmentDeserializer.java From cxf with Apache License 2.0 | 5 votes |
private void cache(DelegatingInputStream input) throws IOException { if (loaded.contains(input)) { return; } loaded.add(input); InputStream origIn = input.getInputStream(); try (CachedOutputStream out = new CachedOutputStream()) { AttachmentUtil.setStreamedAttachmentProperties(message, out); IOUtils.copy(input, out); input.setInputStream(out.getInputStream()); origIn.close(); } }
Example 9
Source File: TestUtilities.java From cxf with Apache License 2.0 | 5 votes |
public byte[] invokeBytes(String address, String transport, String message) throws Exception { EndpointInfo ei = new EndpointInfo(null, "http://schemas.xmlsoap.org/soap/http"); ei.setAddress(address); ConduitInitiatorManager conduitMgr = getBus().getExtension(ConduitInitiatorManager.class); ConduitInitiator conduitInit = conduitMgr.getConduitInitiator(transport); Conduit conduit = conduitInit.getConduit(ei, getBus()); TestMessageObserver obs = new TestMessageObserver(); conduit.setMessageObserver(obs); Message m = new MessageImpl(); conduit.prepare(m); OutputStream os = m.getContent(OutputStream.class); InputStream is = getResourceAsStream(message); if (is == null) { throw new RuntimeException("Could not find resource " + message); } IOUtils.copy(is, os); // TODO: shouldn't have to do this. IO caching needs cleaning // up or possibly removal... os.flush(); is.close(); os.close(); return obs.getResponseStream().toByteArray(); }
Example 10
Source File: ServiceListGeneratorServlet.java From cxf with Apache License 2.0 | 5 votes |
private void renderStyleSheet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/css; charset=UTF-8"); URL url = this.getClass().getResource("servicelist.css"); if (url != null) { try (InputStream inputStream = url.openStream()) { IOUtils.copy(inputStream, response.getOutputStream()); } } }
Example 11
Source File: BinaryDataProvider.java From cxf with Apache License 2.0 | 5 votes |
public T readFrom(Class<T> clazz, Type genericType, Annotation[] annotations, MediaType type, MultivaluedMap<String, String> headers, InputStream is) throws IOException { try { if (InputStream.class.isAssignableFrom(clazz)) { if (DigestInputStream.class.isAssignableFrom(clazz)) { is = new MessageDigestInputStream(is); } return clazz.cast(is); } if (Reader.class.isAssignableFrom(clazz)) { return clazz.cast(new InputStreamReader(is, getEncoding(type))); } if (byte[].class.isAssignableFrom(clazz)) { return clazz.cast(IOUtils.readBytesFromStream(is)); } if (File.class.isAssignableFrom(clazz)) { LOG.warning("Reading data into File objects with the help of pre-packaged" + " providers is not recommended - use InputStream or custom File reader"); // create a temp file, delete on exit File f = FileUtils.createTempFile("File" + UUID.randomUUID().toString(), "jaxrs", null, true); OutputStream os = Files.newOutputStream(f.toPath()); IOUtils.copy(is, os, bufferSize); os.close(); return clazz.cast(f); } if (StreamingOutput.class.isAssignableFrom(clazz)) { return clazz.cast(new ReadingStreamingOutput(is)); } } catch (ClassCastException e) { String msg = "Unsupported class: " + clazz.getName(); LOG.warning(msg); throw ExceptionUtils.toInternalServerErrorException(null, null); } throw new IOException("Unrecognized class"); }
Example 12
Source File: AbstractJwsWriterProvider.java From cxf with Apache License 2.0 | 5 votes |
protected void writeJws(JwsCompactProducer p, JwsSignatureProvider theSigProvider, OutputStream os) throws IOException { p.signWith(theSigProvider); JoseUtils.traceHeaders(p.getJwsHeaders()); byte[] bytes = StringUtils.toBytesUTF8(p.getSignedEncodedJws()); IOUtils.copy(new ByteArrayInputStream(bytes), os); }
Example 13
Source File: SwAOutInterceptor.java From cxf with Apache License 2.0 | 5 votes |
private DataSource createDataSource(Source o, String ct) { DataSource ds = null; if (o instanceof StreamSource) { StreamSource src = (StreamSource)o; try { if (src.getInputStream() != null) { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(2048)) { IOUtils.copy(src.getInputStream(), bos, 1024); ds = new ByteDataSource(bos.toByteArray(), ct); } } else { ds = new ByteDataSource(IOUtils.toString(src.getReader()).getBytes(StandardCharsets.UTF_8), ct); } } catch (IOException e) { throw new Fault(e); } } else { ByteArrayOutputStream bwriter = new ByteArrayOutputStream(); XMLStreamWriter writer = null; try { writer = StaxUtils.createXMLStreamWriter(bwriter); StaxUtils.copy(o, writer); writer.flush(); ds = new ByteDataSource(bwriter.toByteArray(), ct); } catch (XMLStreamException e1) { throw new Fault(e1); } finally { StaxUtils.close(writer); } } return ds; }
Example 14
Source File: CreateSignatureInterceptor.java From cxf with Apache License 2.0 | 5 votes |
private void addDigest(WriterInterceptorContext context) throws IOException { // make sure we have all content OutputStream originalOutputStream = context.getOutputStream(); CachedOutputStream cachedOutputStream = new CachedOutputStream(); context.setOutputStream(cachedOutputStream); context.proceed(); cachedOutputStream.flush(); // then digest using requested encoding String encoding = context.getMediaType().getParameters() .getOrDefault(MediaType.CHARSET_PARAMETER, StandardCharsets.UTF_8.toString()); String digestAlgorithm = digestAlgorithmName; if (digestAlgorithm == null) { Message m = PhaseInterceptorChain.getCurrentMessage(); digestAlgorithm = (String)m.getContextualProperty(HTTPSignatureConstants.RSSEC_HTTP_SIGNATURE_DIGEST_ALGORITHM); if (digestAlgorithm == null) { digestAlgorithm = DefaultSignatureConstants.DIGEST_ALGORITHM; } } // not so nice - would be better to have a stream String digest = SignatureHeaderUtils.createDigestHeader( new String(cachedOutputStream.getBytes(), encoding), digestAlgorithm); // add header context.getHeaders().add(DIGEST_HEADER_NAME, digest); sign(context); // write the contents context.setOutputStream(originalOutputStream); IOUtils.copy(cachedOutputStream.getInputStream(), originalOutputStream); }
Example 15
Source File: MtomPolicyTest.java From cxf with Apache License 2.0 | 4 votes |
private void sendMtomMessage(String a) throws Exception { EndpointInfo ei = new EndpointInfo(null, "http://schemas.xmlsoap.org/wsdl/http"); ei.setAddress(a); ConduitInitiatorManager conduitMgr = getStaticBus().getExtension(ConduitInitiatorManager.class); ConduitInitiator conduitInit = conduitMgr.getConduitInitiator("http://schemas.xmlsoap.org/soap/http"); Conduit conduit = conduitInit.getConduit(ei, getStaticBus()); TestUtilities.TestMessageObserver obs = new TestUtilities.TestMessageObserver(); conduit.setMessageObserver(obs); Message m = new MessageImpl(); String ct = "multipart/related; type=\"application/xop+xml\"; " + "start=\"<[email protected]>\"; " + "start-info=\"text/xml; charset=utf-8\"; " + "boundary=\"----=_Part_4_701508.1145579811786\""; m.put(Message.CONTENT_TYPE, ct); conduit.prepare(m); OutputStream os = m.getContent(OutputStream.class); InputStream is = testUtilities.getResourceAsStream("request"); if (is == null) { throw new RuntimeException("Could not find resource " + "request"); } IOUtils.copy(is, os); os.flush(); is.close(); os.close(); byte[] res = obs.getResponseStream().toByteArray(); MessageImpl resMsg = new MessageImpl(); resMsg.setContent(InputStream.class, new ByteArrayInputStream(res)); resMsg.put(Message.CONTENT_TYPE, obs.getResponseContentType()); resMsg.setExchange(new ExchangeImpl()); AttachmentDeserializer deserializer = new AttachmentDeserializer(resMsg); deserializer.initializeAttachments(); Collection<Attachment> attachments = resMsg.getAttachments(); assertNotNull(attachments); assertEquals(1, attachments.size()); Attachment inAtt = attachments.iterator().next(); try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { IOUtils.copy(inAtt.getDataHandler().getInputStream(), out); assertEquals(27364, out.size()); } }
Example 16
Source File: BinaryDataProvider.java From cxf with Apache License 2.0 | 4 votes |
public void write(OutputStream outputStream) throws IOException { IOUtils.copy(inputStream, outputStream); }
Example 17
Source File: AttachmentSerializerTest.java From cxf with Apache License 2.0 | 4 votes |
@Test public void testMessageMTOM() throws Exception { MessageImpl msg = new MessageImpl(); Collection<Attachment> atts = new ArrayList<>(); AttachmentImpl a = new AttachmentImpl("test.xml"); InputStream is = getClass().getResourceAsStream("my.wav"); ByteArrayDataSource ds = new ByteArrayDataSource(is, "application/octet-stream"); a.setDataHandler(new DataHandler(ds)); atts.add(a); msg.setAttachments(atts); // Set the SOAP content type msg.put(Message.CONTENT_TYPE, "application/soap+xml"); ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.setContent(OutputStream.class, out); AttachmentSerializer serializer = new AttachmentSerializer(msg); serializer.writeProlog(); String ct = (String) msg.get(Message.CONTENT_TYPE); assertTrue(ct.indexOf("multipart/related;") == 0); assertTrue(ct.indexOf("start=\"<[email protected]>\"") > -1); assertTrue(ct.indexOf("start-info=\"application/soap+xml\"") > -1); out.write("<soap:Body/>".getBytes()); serializer.writeAttachments(); out.flush(); DataSource source = new ByteArrayDataSource(new ByteArrayInputStream(out.toByteArray()), ct); MimeMultipart mpart = new MimeMultipart(source); Session session = Session.getDefaultInstance(new Properties()); MimeMessage inMsg = new MimeMessage(session); inMsg.setContent(mpart); inMsg.addHeaderLine("Content-Type: " + ct); MimeMultipart multipart = (MimeMultipart) inMsg.getContent(); MimeBodyPart part = (MimeBodyPart) multipart.getBodyPart(0); assertEquals("application/xop+xml; charset=UTF-8; type=\"application/soap+xml\"", part.getHeader("Content-Type")[0]); assertEquals("binary", part.getHeader("Content-Transfer-Encoding")[0]); assertEquals("<[email protected]>", part.getHeader("Content-ID")[0]); InputStream in = part.getDataHandler().getInputStream(); ByteArrayOutputStream bodyOut = new ByteArrayOutputStream(); IOUtils.copy(in, bodyOut); out.close(); in.close(); assertEquals("<soap:Body/>", bodyOut.toString()); MimeBodyPart part2 = (MimeBodyPart) multipart.getBodyPart(1); assertEquals("application/octet-stream", part2.getHeader("Content-Type")[0]); assertEquals("binary", part2.getHeader("Content-Transfer-Encoding")[0]); assertEquals("<test.xml>", part2.getHeader("Content-ID")[0]); }
Example 18
Source File: AttachmentStreamSourceXMLProvider.java From cxf with Apache License 2.0 | 4 votes |
public StreamSource invoke(StreamSource source) { MessageContext mc = wsContext.getMessageContext(); String httpMethod = (String)mc.get(MessageContext.HTTP_REQUEST_METHOD); if ("POST".equals(httpMethod)) { int count = 0; // we really want to verify that a root part is a proper XML as expected try { Document doc = StaxUtils.read(source); count = Integer.parseInt(doc.getDocumentElement().getAttribute("count")); } catch (Exception ex) { // ignore } Map<String, DataHandler> dataHandlers = CastUtils.cast( (Map<?, ?>)mc.get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS)); StringBuilder buf = new StringBuilder(); buf.append("<response>"); int i = 0; for (Map.Entry<String, DataHandler> entry : dataHandlers.entrySet()) { if (i++ > count) { break; } try (ByteArrayOutputStream bous = new ByteArrayOutputStream()) { InputStream is = entry.getValue().getInputStream(); IOUtils.copy(is, bous); buf.append("<att contentId=\"" + entry.getKey() + "\">"); buf.append(Base64Utility.encode(bous.toByteArray())); buf.append("</att>"); } catch (IOException ioe) { ioe.printStackTrace(); } } buf.append("</response>"); Map<String, List<String>> respHeaders = CastUtils .cast((Map<?, ?>)mc.get(MessageContext.HTTP_RESPONSE_HEADERS)); if (respHeaders == null) { respHeaders = new HashMap<>(); mc.put(MessageContext.HTTP_RESPONSE_HEADERS, respHeaders); } List<String> contentTypeValues = new ArrayList<>(); contentTypeValues.add("application/xml+custom"); respHeaders.put(Message.CONTENT_TYPE, contentTypeValues); Map<String, DataHandler> outDataHandlers = CastUtils.cast((Map<?, ?>)mc.get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS)); byte[] data = new byte[50]; for (int x = 0; x < data.length; x++) { data[x] = (byte)(x + '0'); } DataHandler foo = new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")); outDataHandlers.put("foo", foo); return new StreamSource(new StringReader(buf.toString())); } return source; }
Example 19
Source File: AbstractJweJsonWriterProvider.java From cxf with Apache License 2.0 | 4 votes |
protected void writeJws(JwsJsonProducer p, OutputStream os) throws IOException { byte[] bytes = StringUtils.toBytesUTF8(p.getJwsJsonSignedDocument()); IOUtils.copy(new ByteArrayInputStream(bytes), os); }
Example 20
Source File: JwkUtils.java From cxf with Apache License 2.0 | 4 votes |
public static void jwkKeyToJson(JsonWebKey jwkKey, OutputStream os) throws IOException { IOUtils.copy(new ByteArrayInputStream(StringUtils.toBytesUTF8(jwkKeyToJson(jwkKey))), os); }