List of usage examples for org.apache.commons.io.output ByteArrayOutputStream flush
public void flush() throws IOException
From source file:com.couchbase.lite.syncgateway.GzippedAttachmentTest.java
private static byte[] getBytesFromInputStream(InputStream is) { ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 8]; int len = 0;/*w w w . j a v a 2 s . c o m*/ try { while ((len = is.read(buffer)) > 0) { os.write(buffer, 0, len); } os.flush(); } catch (IOException e) { Log.e(Log.TAG, "is.read(buffer) or os.flush() error", e); return null; } return os.toByteArray(); }
From source file:net.paissad.waqtsalat.service.utils.HttpUtils.java
private static InputStream sendRequest(final String url, final RequestType requestType) throws WSException { InputStream in = null;/*from ww w . j a v a 2 s .c o m*/ HttpClient client = null; HttpRequestBase request = null; boolean errorOccured = false; try { request = getNewHttpRequest(url, requestType, null); client = getNewHttpClient(); HttpResponse resp = client.execute(request); int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(resp.getEntity().getContent(), baos); baos.flush(); in = new ByteArrayInputStream(baos.toByteArray()); } else { // The response code is not OK. StringBuilder errMsg = new StringBuilder(); errMsg.append("HTTP ").append(requestType).append(" failed => ").append(resp.getStatusLine()); if (request != null) { errMsg.append(" : ").append(request.getURI()); } throw new WSException(errMsg.toString()); } return in; } catch (Exception e) { errorOccured = true; throw new WSException("Error during file HTTP request.", e); } finally { if (errorOccured) { if (request != null) { request.abort(); } } if (client != null) { client.getConnectionManager().shutdown(); } } }
From source file:com.cisco.dbds.utils.selenium.SeleniumUtilities.java
/** * This function captures the Screenshot of the screen and converts it into * a byte array to embed in cucumber reports. * //from www .java 2 s . c om * @return the byte[] * @throws Exception * the exception */ public static byte[] captureScreen() throws Exception { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle screenRectangle = new Rectangle(screenSize); Robot robot = new Robot(); BufferedImage image = robot.createScreenCapture(screenRectangle); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "png", baos); baos.flush(); byte[] bytes = baos.toByteArray(); baos.close(); return bytes; }
From source file:ch.admin.isb.hermes5.util.ImageUtilsTest.java
private byte[] getResourceAsStream(String string) { InputStream resource = ImageUtilsTest.class.getResourceAsStream(string); assertNotNull(resource);//from w w w . ja v a 2s .co m ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { byteArrayOutputStream.write(resource); byteArrayOutputStream.flush(); return byteArrayOutputStream.toByteArray(); } catch (Exception e) { throw new RuntimeException(e); } finally { try { byteArrayOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
From source file:com.tdclighthouse.prototype.services.callbacks.ImageCreationCallBack.java
@Override public String doInSession(Session session) throws RepositoryException { String result = null;//from w w w .j av a 2s .com try { // FIXME refactor Node node = createImageSetNode(session, contentType); result = DocumentManager.getHandle(node).getIdentifier(); String mimeType = new MimetypesFileTypeMap().getContentType(file); Node galleryProcessorService = session.getNode(PluginConstants.Paths.GALLERY_PROCESSOR_SERVICE); for (NodeIterator sizes = galleryProcessorService.getNodes(); sizes.hasNext();) { Node size = sizes.nextNode(); if (size.isNodeType(PluginConstants.NodeType.FRONTEND_PLUGINCONFIG)) { Node subjectNode = getNode(node, size.getName(), PluginConstants.NodeType.HIPPOGALLERY_IMAGE); Long height = size.getProperty(PluginConstants.PropertyName.HEIGHT).getLong(); Long width = size.getProperty(PluginConstants.PropertyName.WIDTH).getLong(); BufferedImage bufferedImage = ImageIO.read(file); InputStream inputStream; if (height == 0 && width == 0) { inputStream = new FileInputStream(file); height = (long) bufferedImage.getHeight(); width = (long) bufferedImage.getWidth(); } else { ImageSize scaledSize = getScaledSize(height, width, bufferedImage); BufferedImage scaledImage = ImageUtils.scaleImage(bufferedImage, scaledSize.width.intValue(), scaledSize.height.intValue(), ScalingStrategy.BEST_QUALITY); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ImageIO.write(scaledImage, "jpg", byteArrayOutputStream); byteArrayOutputStream.flush(); inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); height = (long) scaledImage.getHeight(); width = (long) scaledImage.getWidth(); } subjectNode.setProperty(PluginConstants.PropertyName.JCR_DATA, session.getValueFactory().createBinary(inputStream)); subjectNode.setProperty(PluginConstants.PropertyName.JCR_MIME_TYPE, mimeType); subjectNode.setProperty(PluginConstants.PropertyName.JCR_LAST_MODIFIED, new GregorianCalendar()); subjectNode.setProperty(PluginConstants.PropertyName.HIPPOGALLERY_HEIGHT, height); subjectNode.setProperty(PluginConstants.PropertyName.HIPPOGALLERY_WIDTH, width); } } } catch (IOException | WorkflowException e) { throw new RepositoryException(e); } return result; }
From source file:io.anserini.embeddings.IndexW2V.java
public void indexEmbeddings() throws IOException, InterruptedException { LOG.info("Starting indexer..."); long startTime = System.currentTimeMillis(); final WhitespaceAnalyzer analyzer = new WhitespaceAnalyzer(); final IndexWriterConfig config = new IndexWriterConfig(analyzer); final IndexWriter writer = new IndexWriter(directory, config); BufferedReader bRdr = new BufferedReader(new FileReader(args.input)); String line = null;/*from w w w .ja v a2s . c o m*/ bRdr.readLine(); Document document = new Document(); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int cnt = 0; while ((line = bRdr.readLine()) != null) { String[] termEmbedding = line.trim().split("\t"); document.add(new StringField(LuceneDocumentGenerator.FIELD_ID, termEmbedding[0], Field.Store.NO)); String[] parts = termEmbedding[1].split(" "); for (int i = 0; i < parts.length; ++i) { byteStream.write(ByteBuffer.allocate(4).putFloat(Float.parseFloat(parts[i])).array()); } document.add(new StoredField(FIELD_BODY, byteStream.toByteArray())); byteStream.flush(); byteStream.reset(); writer.addDocument(document); document.clear(); cnt++; if (cnt % 100000 == 0) { LOG.info(cnt + " terms indexed"); } } LOG.info(String.format("Total of %s terms added", cnt)); try { writer.commit(); writer.forceMerge(1); } finally { try { writer.close(); } catch (IOException e) { LOG.error(e); } } LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms"); }
From source file:au.com.gaiaresources.bdrs.controller.test.TestDataCreator.java
private byte[] createImage(int width, int height, String text) throws IOException { if (width < 0) { width = random.nextInt(DEFAULT_MAX_IMAGE_WIDTH - DEFAULT_MIN_IMAGE_WIDTH) + DEFAULT_MIN_IMAGE_WIDTH; }//from w ww.j a va2 s. c om if (height < 0) { height = random.nextInt(DEFAULT_MAX_IMAGE_HEIGHT - DEFAULT_MIN_IMAGE_HEIGHT) + DEFAULT_MIN_IMAGE_HEIGHT; } BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = (Graphics2D) img.getGraphics(); g2.setBackground(new Color(220, 220, 220)); Dimension size; float fontSize = g2.getFont().getSize(); // Make the text as large as possible. do { g2.setFont(g2.getFont().deriveFont(fontSize)); FontMetrics metrics = g2.getFontMetrics(g2.getFont()); int hgt = metrics.getHeight(); int adv = metrics.stringWidth(text); size = new Dimension(adv + 2, hgt + 2); fontSize = fontSize + 1f; } while (size.width < Math.round(0.9 * width) && size.height < Math.round(0.9 * height)); g2.setColor(Color.DARK_GRAY); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.drawString(text, (width - size.width) / 2, (height - size.height) / 2); g2.setColor(Color.LIGHT_GRAY); g2.drawRect(0, 0, width - 1, height - 1); ByteArrayOutputStream baos = new ByteArrayOutputStream(width * height); ImageIO.write(img, "png", baos); baos.flush(); byte[] rawBytes = baos.toByteArray(); baos.close(); return rawBytes; }
From source file:au.com.gaiaresources.bdrs.controller.test.TestDataCreator.java
private byte[] getAndScaleImageData(int targetWidth, int targetHeight, File file) throws IOException { if (file == null) { return null; }/*from w w w . j av a 2s.c om*/ BufferedImage sourceImage = ImageIO.read(file); BufferedImage targetImage; if (targetWidth > -1 && targetHeight > -1) { // Resize the image as required to fit the space targetImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2_scaled = targetImage.createGraphics(); // Better scaling g2_scaled.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2_scaled.setBackground(Color.WHITE); g2_scaled.clearRect(0, 0, targetWidth, targetHeight); int sourceWidth = sourceImage.getWidth(); int sourceHeight = sourceImage.getHeight(); double widthRatio = (double) targetWidth / (double) sourceWidth; double heightRatio = (double) targetHeight / (double) targetHeight; if (heightRatio > widthRatio) { int scaledHeight = (int) Math.round(widthRatio * sourceHeight); g2_scaled.drawImage(sourceImage, 0, (targetImage.getHeight() - scaledHeight) / 2, targetImage.getWidth(), scaledHeight, g2_scaled.getBackground(), null); } else { int scaledWidth = (int) Math.round(heightRatio * sourceWidth); g2_scaled.drawImage(sourceImage, (targetImage.getWidth() - scaledWidth) / 2, 0, scaledWidth, targetImage.getHeight(), new Color(0, 0, 0, 255), null); } } else { targetImage = sourceImage; } ByteArrayOutputStream baos = new ByteArrayOutputStream(targetWidth * targetHeight); ImageIO.write(targetImage, "png", baos); baos.flush(); byte[] data = baos.toByteArray(); baos.close(); return data; }
From source file:de.dal33t.powerfolder.util.ByteSerializer.java
/** * Serialize an object. This method is non-static an re-uses the internal * byteoutputstream/*from w w w . j a v a2s . c om*/ * * @param target * The object to be serialized * @param compress * true if serialization should compress. * @param padToSize * the size to pad the output buffer to. number below 0 means no * padding. * @return The serialized object * @throws IOException * In case the object cannot be serialized */ public byte[] serialize(Serializable target, boolean compress, int padToSize) throws IOException { long start = System.currentTimeMillis(); ByteArrayOutputStream byteOut; // Reset buffer if (outBufferRef != null && outBufferRef.get() != null) { // Reuse old buffer byteOut = outBufferRef.get(); byteOut.reset(); } else { // logFiner("Creating send buffer (512bytes)"); // Create new bytearray output, 512b buffer byteOut = new ByteArrayOutputStream(512); if (CACHE_OUT_BUFFER) { // Chache outgoing buffer outBufferRef = new SoftReference<ByteArrayOutputStream>(byteOut); } } OutputStream targetOut; // Serialize.... if (compress) { PFZIPOutputStream zipOut = new PFZIPOutputStream(byteOut); targetOut = zipOut; } else { targetOut = byteOut; } ObjectOutputStream objOut = new ObjectOutputStream(targetOut); // Write try { objOut.writeUnshared(target); } catch (StreamCorruptedException e) { LOG.log(Level.WARNING, "Problem while serializing: " + e, e); throw e; } catch (InvalidClassException e) { LOG.log(Level.WARNING, "Problem while serializing: " + target + ": " + e, e); throw e; } objOut.close(); if (padToSize > 0) { int modulo = byteOut.size() % padToSize; if (modulo != 0) { int additionalBytesRequired = padToSize - (modulo); // LOG.warn("Buffersize: " + byteOut.size() // + ", Additonal bytes required: " + additionalBytesRequired); for (int i = 0; i < additionalBytesRequired; i++) { byteOut.write(0); } } } byteOut.flush(); byteOut.close(); if (byteOut.size() >= 256 * 1024) { logWarning("Send buffer exceeds 256KB! " + Format.formatBytes(byteOut.size()) + ". Message: " + target); } byte[] buf = byteOut.toByteArray(); if (BENCHMARK) { totalObjects++; totalTime += System.currentTimeMillis() - start; int count = 0; if (CLASS_STATS.containsKey(target.getClass())) { count = CLASS_STATS.get(target.getClass()); } count++; CLASS_STATS.put(target.getClass(), count); } return buf; }
From source file:au.org.ala.biocache.dao.SearchDAOImpl.java
/** * Returns the values and counts for a single facet field. *//*from w w w . ja v a2 s . c o m*/ public List<FieldResultDTO> getValuesForFacet(SpatialSearchRequestParams requestParams) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); writeFacetToStream(requestParams, true, false, false, outputStream, null); outputStream.flush(); outputStream.close(); String includedValues = outputStream.toString(); includedValues = includedValues == null ? "" : includedValues; String[] values = includedValues.split("\n"); List<FieldResultDTO> list = new ArrayList<FieldResultDTO>(); boolean first = true; for (String value : values) { if (first) { first = false; } else { int idx = value.lastIndexOf(","); //handle values enclosed in " list.add(new FieldResultDTO(value.substring(0, idx), Long.parseLong(value.substring(idx + 1).replace("\"", "")))); } } return list; }