List of usage examples for java.io ByteArrayOutputStream size
public synchronized int size()
From source file:org.jahia.utils.maven.plugin.osgi.ConvertToOSGiMojo.java
public List<String> checkForMigrationIssues(File currentFile, boolean performMigration) throws FileNotFoundException { List<String> messages = new ArrayList<String>(); if (currentFile.isFile()) { FileInputStream fileInputStream = new FileInputStream(currentFile); ByteArrayOutputStream byteArrayOutputStream = null; if (performMigration) { // we use byte arrays as we will be writing to the same file as the input file byteArrayOutputStream = new ByteArrayOutputStream(); }//w w w.j a v a 2 s . co m messages.addAll(Migrators.getInstance().migrate(fileInputStream, byteArrayOutputStream, currentFile.getPath(), new Version("6.6"), new Version("7.0"), performMigration)); IOUtils.closeQuietly(fileInputStream); if (performMigration && messages.size() > 0 && byteArrayOutputStream.size() > 0) { getLog().info("Renaming existing file " + currentFile + " to " + currentFile.getName() + ".backup"); if (!currentFile.renameTo(new File(currentFile.getPath() + ".backup"))) { getLog().error("Error renaming " + currentFile + "!"); } byte[] byteArray = byteArrayOutputStream.toByteArray(); getLog().info("Writing modified file " + currentFile + "..."); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray); FileOutputStream fileOutputStream = new FileOutputStream(currentFile); long bytesCopied = 0; try { bytesCopied = IOUtils.copyLarge(byteArrayInputStream, fileOutputStream); fileOutputStream.flush(); } catch (IOException e) { getLog().error("Error writing to file " + currentFile, e); } getLog().info("Wrote " + bytesCopied + " bytes to file " + currentFile); IOUtils.closeQuietly(fileOutputStream); } return messages; } if (!currentFile.isDirectory()) { getLog().warn("Found non-file or directory at " + currentFile + ",ignoring..."); return messages; } File[] currentChildren = currentFile.listFiles(); for (File currentChild : currentChildren) { messages.addAll(checkForMigrationIssues(currentChild, performMigration)); } return messages; }
From source file:org.broadleafcommerce.core.search.service.solr.index.SolrIndexServiceImpl.java
protected int getCacheSizeInMemoryApproximation(CatalogStructure structure) { try {//w w w .ja v a2 s . com if (structure == null) { return 0; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(structure); IOUtils.closeQuietly(oos); int size = baos.size(); IOUtils.closeQuietly(baos); return size; } catch (IOException e) { throw ExceptionHelper.refineException(e); } }
From source file:com.adaptris.ftp.ApacheFtpClientImpl.java
/** * Get data as a byte array from a server file * //w ww.j a va 2 s. c o m * @param remoteFile file to be read on the server */ @Override public byte[] get(String remoteFile) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(4096); try { acquireLock(); log("{} {}", FTPCmd.RETR, remoteFile); try (InputStream i = ftpClient().retrieveFileStream(remoteFile); OutputStream o = out) { IOUtils.copy(i, o); } ftpClient().completePendingCommand(); logReply(ftpClient().getReplyStrings()); log("Transferred {} bytes from remote host", out.size()); } finally { releaseLock(); } return out.toByteArray(); }
From source file:org.apache.olingo.fit.utils.AbstractUtilities.java
public Response createResponse(final String location, final InputStream entity, final String etag, final Accept accept, final Response.Status status) { final Response.ResponseBuilder builder = Response.ok(); if (StringUtils.isNotBlank(etag)) { builder.header("ETag", etag); }//from www .ja v a2 s . c o m if (status != null) { builder.status(status); } int contentLength = 0; String contentTypeEncoding = StringUtils.EMPTY; if (entity != null) { try { final InputStream toBeStreamedBack; if (Accept.JSON == accept || Accept.JSON_NOMETA == accept) { toBeStreamedBack = Commons.changeFormat(entity, accept); } else { toBeStreamedBack = entity; } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(toBeStreamedBack, bos); IOUtils.closeQuietly(toBeStreamedBack); contentLength = bos.size(); builder.entity(new ByteArrayInputStream(bos.toByteArray())); contentTypeEncoding = ";odata.streaming=true;charset=utf-8"; } catch (IOException ioe) { LOG.error("Error streaming response entity back", ioe); } } builder.header("Content-Length", contentLength); builder.header("Content-Type", (accept == null ? "*/*" : accept.toString()) + contentTypeEncoding); if (StringUtils.isNotBlank(location)) { builder.header("Location", location); } return builder.build(); }
From source file:org.ohmage.request.Request.java
/** * <p>/*ww w. j a v a 2 s . c o m*/ * Retrieves a parameter from either parts or the servlet container's * deserialization. * </p> * * <p> * This supersedes {@link #getMultipartValue(HttpServletRequest, String)}. * </p> * * @param httpRequest * The HTTP request. * * @param key * The parameter key. * * @return The parameter if given otherwise null. * * @throws ValidationException * There was a problem reading from the request. */ protected byte[] getParameter(final HttpServletRequest httpRequest, final String key) throws ValidationException { // First, attempt to decode it as a multipart/form-data post. try { // Get the part. If it isn't a multipart/form-data post, an // exception will be thrown. If it is and such a part does not // exist, return null. Part part = httpRequest.getPart(key); if (part == null) { return null; } // If the part exists, attempt to retrieve it. InputStream partInputStream = part.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] chunk = new byte[4096]; int amountRead; while ((amountRead = partInputStream.read(chunk)) != -1) { outputStream.write(chunk, 0, amountRead); } // If the buffer is empty, return null. Otherwise, return the byte // array. if (outputStream.size() == 0) { return null; } else { return outputStream.toByteArray(); } } // This will be thrown if it isn't a multipart/form-post, at which // point we can attempt to use the servlet container's deserialization // of the parameters. catch (ServletException e) { // Get the parameter. String result = httpRequest.getParameter(key); // If it doesn't exist, return null. if (result == null) { return null; } // Otherwise, return its bytes. else { return result.getBytes(); } } // If we could not read a parameter, something more severe happened, // and we need to fail the request and throw an exception. catch (IOException e) { LOGGER.info("There was an error reading the message from the input " + "stream.", e); setFailed(); throw new ValidationException(e); } }
From source file:ddf.catalog.resource.download.ReliableResourceDownloadManagerTest.java
private void verifyClientBytesRead(ByteArrayOutputStream clientBytesRead) { // Verifies client read same contents as product input file if (clientBytesRead != null) { assertThat(clientBytesRead.size(), is(Long.valueOf(expectedFileSize).intValue())); assertEquals(expectedFileContents, new String(clientBytesRead.toByteArray())); }//from w ww.j a v a 2s .c o m }
From source file:com.att.ajsc.csilogging.common.CSILoggingUtils.java
private String getResponseLength(HttpServletRequest request) { long length = -1; if (request.getAttribute(CommonNames.RESPONSE_ENTITY) != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream os = null; try {/* w w w. ja va 2 s .c om*/ os = new ObjectOutputStream(out); os.writeObject(request.getAttribute(CommonNames.RESPONSE_ENTITY)); } catch (IOException e) { logger.error("error while getting the response length" + e); } length = out.size(); } else if (request.getAttribute(CommonNames.RESPONSE_LENGTH) != null) { length = (long) request.getAttribute(CommonNames.RESPONSE_LENGTH); } return String.valueOf(length); }
From source file:ddf.catalog.resource.download.ReliableResourceDownloadManagerTest.java
/** * Tests that if exception with the FileBackedOutputStream being written to and concurrently read by the client occurs * during a product retrieval, then the product download to the client is stopped, but the caching of the * file continues.//from w ww . ja v a 2 s. c o m * * @throws Exception */ @Test @Ignore // Currently Ignored because cannot figure out how to get FileBackedOutputStream (FBOS) to throw exception // during product download - this test successfully closes the FBOS, but the ReliableResourceCallable // does not seem to detect this and continues to stream successfully to the client. public void testStreamToClientExceptionDuringProductDownloadCachingEnabled() throws Exception { mis = new MockInputStream(productInputFilename); Metacard metacard = getMockMetacard(EXPECTED_METACARD_ID, EXPECTED_METACARD_SOURCE_ID); resourceResponse = getMockResourceResponse(); downloadMgr = new ReliableResourceDownloadManager(resourceCache, eventPublisher, eventListener, downloadStatusInfo, Executors.newSingleThreadExecutor()); // Use small chunk size so download takes long enough for client // to have time to simulate FileBackedOutputStream exception int chunkSize = 2; downloadMgr.setChunkSize(chunkSize); ResourceRetriever retriever = mock(ResourceRetriever.class); when(retriever.retrieveResource()).thenReturn(resourceResponse); ArgumentCaptor<ReliableResource> argument = ArgumentCaptor.forClass(ReliableResource.class); ResourceResponse newResourceResponse = downloadMgr.download(resourceRequest, metacard, retriever); assertThat(newResourceResponse, is(notNullValue())); productInputStream = newResourceResponse.getResource().getInputStream(); assertThat(productInputStream, is(instanceOf(ReliableResourceInputStream.class))); // On second chunk read by client it will close the download manager's cache file output stream // to simulate a cache file exception that should be detected by the ReliableResourceCallable executor = Executors.newCachedThreadPool(); ProductDownloadClient productDownloadClient = new ProductDownloadClient(productInputStream, chunkSize); productDownloadClient.setSimulateFbosException(chunkSize, downloadMgr); future = executor.submit(productDownloadClient); ByteArrayOutputStream clientBytesRead = future.get(); // Verify client did not receive entire product download assertTrue(clientBytesRead.size() < expectedFileSize); // Captures the ReliableResource object that should have been put in the ResourceCache's map verify(resourceCache, timeout(3000)).put(argument.capture()); verifyCaching(argument.getValue(), EXPECTED_CACHE_KEY); cleanup(); }
From source file:org.guvnor.common.services.backend.file.upload.AbstractFileServlet.java
protected void processAttachmentDownload(final String url, final HttpServletRequest request, final HttpServletResponse response) throws IOException { final ByteArrayOutputStream output = new ByteArrayOutputStream(); try {//from w w w. ja v a 2 s. co m final Path sourcePath = convertPath(url); if (!validateAccess(Paths.convert(sourcePath), response)) { return; } IOUtils.copy(doLoad(sourcePath, request), output); //Use the encoded form from in the URL (rather than encode/decode for fun!) //See http://tools.ietf.org/html/rfc6266 for details of filename* content-disposition usage final String fileName = url.substring(url.lastIndexOf("/") + 1); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment; filename*=utf-8''" + fileName); response.setContentLength(output.size()); response.getOutputStream().write(output.toByteArray()); response.getOutputStream().flush(); } catch (Exception e) { throw new org.uberfire.java.nio.IOException(e.getMessage()); } }
From source file:ddf.catalog.resource.download.ReliableResourceDownloadManagerTest.java
/** * Tests that if network connection drops repeatedly during a product retrieval such that all * of the retry attempts are used up before entire product is downloaded, then the (partially) cached file is deleted and not * placed in the cache map, and product download fails. * * @throws Exception/*from w w w . j av a 2s . c o m*/ */ @Test @Ignore public void testRetryAttemptsExhaustedDuringProductDownload() throws Exception { mis = new MockInputStream(productInputFilename); Metacard metacard = getMockMetacard(EXPECTED_METACARD_ID, EXPECTED_METACARD_SOURCE_ID); resourceResponse = getMockResourceResponse(); ResourceRetriever retriever = getMockResourceRetrieverWithRetryCapability( RetryType.NETWORK_CONNECTION_UP_AND_DOWN); int chunkSize = 50; startDownload(true, chunkSize, false, metacard, retriever); ByteArrayOutputStream clientBytesRead = clientRead(chunkSize, productInputStream); // Verify client did not receive entire product download assertTrue(clientBytesRead.size() < expectedFileSize); // Verify product was not cached, i.e., its pending caching entry was removed String cacheKey = new CacheKey(metacard, resourceResponse.getRequest()).generateKey(); verify(resourceCache, timeout(3000)).removePendingCacheEntry(cacheKey); cleanup(); }