List of usage examples for org.apache.commons.io IOUtils copy
public static void copy(Reader input, OutputStream output) throws IOException
Reader
to bytes on an OutputStream
using the default character encoding of the platform, and calling flush. From source file:com.googlecode.fannj.FannTrainerTest.java
@Test public void testTrainingQuickprop() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit();/* ww w . j a va 2 s. co m*/ IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_QUICKPROP); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); }
From source file:com.adaptris.core.stubs.MockEncoder.java
/** * Decode into an <code>AdaptrisMessage</code> object. * <p>//from w ww . j a v a 2 s. c o m * The source object is assumed to be of the type <code>InputStream</code> * </p> * * @see com.adaptris.core.AdaptrisMessageEncoder#readMessage(java.lang.Object) */ public AdaptrisMessage readMessage(Object source) throws CoreException { AdaptrisMessage msg = null; try { msg = currentMessageFactory().newMessage(); if (!(source instanceof InputStream)) { throw new IllegalArgumentException("MockEncoder can only decode from an InputStream"); } try (OutputStream out = msg.getOutputStream()) { IOUtils.copy((InputStream) source, out); } } catch (Exception e) { throw new CoreException("Could not parse supplied bytes into an AdaptrisMessage object", e); } return msg; }
From source file:com.controlj.green.modstat.servlets.ModstatZipServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/zip"); resp.setHeader("Content-disposition", "attachment;filename=modstat.zip"); try {//from ww w . j ava 2 s .c o m RunnableProgress work = (RunnableProgress) LongRunning.getWork(req); if (work == null || work.isAlive() || work.hasError()) { throw new Exception("Modstats not gathered yet"); } InputStream in = work.getCache(); IOUtils.copy(in, resp.getOutputStream()); resp.getOutputStream().flush(); } catch (Exception e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); System.err.println("Add-On Error in " + AddOnInfo.getAddOnInfo().getName()); e.printStackTrace(new PrintWriter(System.err)); } }
From source file:com.jaspersoft.android.jaspermobile.test.support.db.PermanentDatabase.java
public ResourceDatabase prepare() { File originalFile = resourceDatabase.getFile(); String copyResourceName = originalFile.getName() + "-copy"; File copyFile = new File(originalFile.getParentFile(), copyResourceName); InputStream in = resourceDatabase.getInputStream(); try {/*from w w w .j a v a 2s . co m*/ OutputStream out = new FileOutputStream(copyFile); IOUtils.copy(in, out); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); ResourceDatabase resourceDatabase = ResourceDatabase.get(copyResourceName); return resourceDatabase; } catch (FileNotFoundException e) { throw new RuntimeException(); } catch (IOException e) { throw new RuntimeException(); } }
From source file:com.googlecode.ddom.frontend.saaj.impl.SwAProfile.java
@Override public MessageDeserializer createDeserializer(InputStream in) { // TODO: optimize this and add support for lazy loading of attachments final MultipartReader mpr = new MultipartReader(in, boundary); return new MessageDeserializer() { public MimeHeaders getSOAPPartHeaders() throws IOException, SOAPException { if (!mpr.nextPart()) { throw new SOAPException("Message has no SOAP part"); }//w w w . j av a2 s. c o m return readMimeHeaders(mpr); } public InputStream getSOAPPartInputStream() throws IOException, SOAPException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(mpr.getContent(), baos); return new ByteArrayInputStream(baos.toByteArray()); } public AttachmentSet getAttachments() throws IOException, SOAPException { AttachmentSet attachments = new SimpleAttachmentSet(); while (mpr.nextPart()) { // TODO: shouldn't we have a factory method in AttachmentSet? AttachmentPartImpl attachment = new AttachmentPartImpl(readMimeHeaders(mpr)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(mpr.getContent(), baos); attachment.setDataHandler(new DataHandler( new ByteArrayDataSource(baos.toByteArray(), attachment.getContentType()))); attachments.add(attachment); } return attachments; } }; }
From source file:com.datatorrent.lib.io.HttpLinesInputOperatorTest.java
@Test public void testHttpInputModule() throws Exception { final List<String> receivedMessages = new ArrayList<String>(); Handler handler = new AbstractHandler() { @Override//w w w . ja v a2s . com public void handle(String string, Request rq, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(request.getInputStream(), bos); receivedMessages.add(new String(bos.toByteArray())); response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_OK); response.getOutputStream().println("Hello"); response.getOutputStream().println("World,"); response.getOutputStream().println("Big"); response.getOutputStream().println("Data!"); response.getOutputStream().flush(); ((Request) request).setHandled(true); } }; Server server = new Server(0); server.setHandler(handler); server.start(); String url = "http://localhost:" + server.getConnectors()[0].getLocalPort() + "/somecontext"; final HttpLinesInputOperator operator = new HttpLinesInputOperator(); CollectorTestSink<String> sink = TestUtils.setSink(operator.outputPort, new CollectorTestSink<String>()); operator.setUrl(new URI(url)); operator.setup(null); operator.activate(null); int timeoutMillis = 3000; while (sink.collectedTuples.isEmpty() && timeoutMillis > 0) { operator.emitTuples(); timeoutMillis -= 20; Thread.sleep(20); } Assert.assertTrue("tuple emitted", sink.collectedTuples.size() > 0); Assert.assertEquals("", sink.collectedTuples.get(0), "Hello"); Assert.assertEquals("", sink.collectedTuples.get(1), "World,"); Assert.assertEquals("", sink.collectedTuples.get(2), "Big"); Assert.assertEquals("", sink.collectedTuples.get(3), "Data!"); operator.deactivate(); operator.teardown(); server.stop(); }
From source file:biz.shadowservices.DegreesToolbox.HttpGetter.java
public String execute() throws ClientProtocolException, IOException { //TODO: Better exception handling/retries here, although just bumping it up seems to work if (response == null) { HttpClient httpClient = HttpClientSingleton.getInstance(); HttpResponse serverresponse = null; serverresponse = httpClient.execute(httpget); HttpEntity entity = serverresponse.getEntity(); StringWriter writer = new StringWriter(); IOUtils.copy(entity.getContent(), writer); response = writer.toString();/*from w w w.ja va 2 s .c o m*/ } return response; }
From source file:cltestgrid.GetBlob.java
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String userAgent = req.getHeader("User-Agent"); if (userAgent != null && userAgent.contains("Baiduspider")) { resp.setStatus(SC_MOVED_PERMANENTLY); resp.setHeader("Location", "http://www.baidu.com/search/spider.html"); resp.setHeader("X-READ-ME", "Please honor robots.txt and don't waste our resources. http://cl-test-grid.appspot.com/robots.txt"); return;/*ww w . j a v a2 s. co m*/ } final String key = req.getParameter("key"); String filename = "/gs/cl-test-grid-logs/" + key; AppEngineFile file = new AppEngineFile(filename); FileReadChannel readChannel = null; InputStream inputStream = null; try { final boolean lock = false; readChannel = FileServiceFactory.getFileService().openReadChannel(file, lock); inputStream = Channels.newInputStream(readChannel); resp.setContentType("text/plain"); // The log files are gzipped, but we can't serve gzipped content, // because GAE gzips servlet output itlself and so logs would end-up gzipped twice. // Therefore we need to ungzip the log. InputStream ungzipper = new GZIPInputStream(new BufferedInputStream(inputStream, 100 * 1024)); IOUtils.copy(ungzipper, resp.getOutputStream()); resp.getOutputStream().flush(); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(readChannel); } }
From source file:com.cloudbees.jenkins.support.filter.FilteredWriterTest.java
@Issue("JENKINS-21670") @Test/* w w w . j av a 2 s. com*/ public void shouldModifyStream() throws Exception { final int nrLines = FilteredConstants.DEFAULT_DECODER_CAPACITY; String inputContents = IntStream.range(0, nrLines).mapToObj(i -> "ManagedNode" + i) .collect(joining(System.lineSeparator())); CharSequenceReader reader = new CharSequenceReader(inputContents); ContentFilter filter = s -> s.replace("ManagedNode", "Anonymous_"); StringWriter output = new StringWriter(); FilteredWriter writer = new FilteredWriter(output, filter); IOUtils.copy(reader, writer); writer.flush(); String outputContents = output.toString(); assertThat(outputContents).isNotEmpty(); String[] lines = FilteredConstants.EOL.split(outputContents); assertThat(lines).allMatch(line -> !line.contains("ManagedNode") && line.startsWith("Anonymous_")) .hasSize(nrLines); }
From source file:annis.gui.exporter.CSVExporter.java
@Override public boolean convertText(String queryAnnisQL, int contextLeft, int contextRight, Set<String> corpora, List<String> keys, String argsAsString, WebResource annisResource, Writer out, EventBus eventBus) { //this is a full result export try {/*from w ww .j a v a 2 s . c o m*/ WebResource res = annisResource.path("search").path("matrix").queryParam("csv", "true") .queryParam("corpora", StringUtils.join(corpora, ",")) .queryParam("q", Helper.encodeJersey(queryAnnisQL)); if (argsAsString.startsWith("metakeys=")) { res = res.queryParam("metakeys", argsAsString.substring("metakeys".length() + 1)); } try (InputStream result = res.get(InputStream.class)) { IOUtils.copy(result, out); } out.flush(); return true; } catch (UniformInterfaceException ex) { log.error(null, ex); Notification n = new Notification("Service exception", ex.getResponse().getEntity(String.class), Notification.Type.WARNING_MESSAGE, true); n.show(Page.getCurrent()); } catch (ClientHandlerException ex) { log.error(null, ex); } catch (IOException ex) { log.error(null, ex); } return false; }