List of usage examples for java.io InputStream reset
public synchronized void reset() throws IOException
mark
method was last called on this input stream. From source file:com.zotoh.core.io.StreamUte.java
/** * @param iso//from w ww.j a va 2s.c o m */ public static void resetInputSource(InputSource iso) { if (iso != null) { Reader rdr = iso.getCharacterStream(); InputStream ism = iso.getByteStream(); try { if (ism != null) ism.reset(); } catch (Exception e) { } try { if (rdr != null) rdr.reset(); } catch (Exception e) { } } }
From source file:Main.java
protected static byte[] readBuffer(InputStream is) throws IOException { if (is.available() == 0) { return new byte[0]; }// w w w.j av a2 s. c om byte[] buffer = new byte[BUFFER_SIZE]; is.mark(BUFFER_SIZE); int bytesRead = is.read(buffer, 0, BUFFER_SIZE); int totalBytesRead = bytesRead; while (bytesRead != -1 && (totalBytesRead < BUFFER_SIZE)) { bytesRead = is.read(buffer, totalBytesRead, BUFFER_SIZE - totalBytesRead); if (bytesRead != -1) totalBytesRead += bytesRead; } if (totalBytesRead < BUFFER_SIZE) { byte[] smallerBuffer = new byte[totalBytesRead]; System.arraycopy(buffer, 0, smallerBuffer, 0, totalBytesRead); smallerBuffer = buffer; } is.reset(); return buffer; }
From source file:byps.BWire.java
/** * Reads a ByteBuffer from an InputStream * Closes the InputStream./*from w w w . j a v a 2 s.co m*/ * @param is * @return * @throws IOException */ public static ByteBuffer bufferFromStream(InputStream is, Boolean gzip) throws IOException { if (is == null) return null; try { ByteBuffer ibuf = ByteBuffer.allocate(10 * 1000); if (gzip != null) { if (gzip) { is = new GZIPInputStream(is); } } else { if (!is.markSupported()) is = new BufferedInputStream(is, 2); is.mark(2); int magic = is.read() | (is.read() << 8); is.reset(); if (magic == GZIPInputStream.GZIP_MAGIC) { is = new GZIPInputStream(is); } } ReadableByteChannel rch = Channels.newChannel(is); while (rch.read(ibuf) != -1) { if (ibuf.remaining() == 0) { ByteBuffer nbuf = ByteBuffer.allocate(ibuf.capacity() * 2); ibuf.flip(); nbuf.put(ibuf); ibuf = nbuf; } } ibuf.flip(); return ibuf; } finally { is.close(); } }
From source file:Main.java
/** * Decodes from an input stream that optimally supports mark and reset * operations. If a maximum width and/or height are specified then the * passed stream must support mark and reset so that the bitmap can be down * sampled properly. If the width and/or height are specified and the input * stream does not support mark and reset, then an IllegalArgumentException * will be throw./* w w w.j av a 2 s.c om*/ */ public static Bitmap decodeSampledBitmapFromStream(InputStream inputStream, int width, int height) { if ((width != 0 || height != 0) && !inputStream.markSupported()) { throw new IllegalArgumentException( "Bitmap decoding requires an input stream that supports " + "mark and reset"); } // Set a mark for reset. Since we have no idea of the size of this // image, just set the maximum value possible. inputStream.mark(Integer.MAX_VALUE); // First decode with inJustDecodeBounds=true to check dimensions. final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(inputStream, null, options); // Reset the stream for the actual decoding phase. try { inputStream.reset(); } catch (IOException e) { Log.e(TAG, "Failed to reset input stream during bitmap decoding"); return null; } // If either width or height is passed in as 0, then use the actual // stored image dimension. if (width == 0) { width = options.outWidth; } if (height == 0) { height = options.outHeight; } // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, width, height); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeStream(inputStream, null, options); }
From source file:com.stratuscom.harvester.codebase.ClassServer.java
/** * Read up to CRLF, return false if EOF/*from w w w.ja v a2s . co m*/ */ private static boolean readLine(InputStream in, StringBuffer buf) throws IOException { while (true) { int c = in.read(); if (c < 0) { return buf.length() > 0; } /* * The characters below are part of the http protocol and not * localizable, so we're OK with character literals. */ if (c == '\r') { in.mark(1); c = in.read(); if (c != '\n') { in.reset(); } return true; } if (c == '\n') { return true; } buf.append((char) c); } }
From source file:org.syphr.prom.PropertiesManagerTest.java
@BeforeClass public static void setUpBeforeClass() throws Exception { Assert.assertTrue("Unable to create \"" + TEST_DATA_DIR.getAbsolutePath() + "\"", TEST_DATA_DIR.isDirectory() || TEST_DATA_DIR.mkdirs()); InputStream baseIn1 = PropertiesManagerTest.class.getResourceAsStream(BASE_PROPS_1_RESOURCE_PATH); Assert.assertNotNull("Base properties 1 is missing", baseIn1); OutputStream baseOut1 = new FileOutputStream(TEST_PROPS_1); IOUtils.copy(baseIn1, baseOut1);//from w ww . jav a 2 s.c o m baseIn1.close(); baseOut1.close(); InputStream baseIn2 = PropertiesManagerTest.class.getResourceAsStream(BASE_PROPS_2_RESOURCE_PATH); Assert.assertNotNull("Base properties 2 is missing", baseIn2); OutputStream baseOut2 = new FileOutputStream(TEST_PROPS_2); IOUtils.copy(baseIn2, baseOut2); baseIn2.close(); baseOut2.close(); InputStream baseIn2Default = PropertiesManagerTest.class .getResourceAsStream(BASE_PROPS_2_DEFAULT_RESOURCE_PATH); Assert.assertNotNull("Base properties 2 default is missing", baseIn2Default); baseIn2Default.mark(Integer.MAX_VALUE); OutputStream baseOut2Default = new FileOutputStream(TEST_PROPS_2_DEFAULT); IOUtils.copy(baseIn2Default, baseOut2Default); baseIn2Default.reset(); test2DefaultProperties = new Properties(); test2DefaultProperties.load(baseIn2Default); baseIn2Default.close(); baseOut2Default.close(); TRANSLATOR1 = new Translator<Key1>() { @Override public String getPropertyName(Key1 propertyKey) { return propertyKey.name().toLowerCase().replace('_', '-'); } @Override public Key1 getPropertyKey(String propertyName) { String enumName = propertyName.toUpperCase().replace('-', '_'); return Key1.valueOf(enumName); } }; EXECUTOR = Executors.newCachedThreadPool(); }
From source file:com.reydentx.core.common.PhotoUtils.java
public static byte[] resizeImageScaleCrop(InputStream data, int img_width, int img_height, boolean isPNG) { BufferedImage originalImage;/*w w w .j av a2s . co m*/ try { originalImage = ImageIO.read(data); Dimension origDimentsion = new Dimension(originalImage.getWidth(), originalImage.getHeight()); Dimension fitDimentsion = new Dimension(img_width, img_height); int flag = testThresholdMinWidthHeightImage(origDimentsion, fitDimentsion); // size Anh dang: MinW < W < 720, MinH < H < 720. if (flag == -1) { data.reset(); ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); byte[] read = new byte[2048]; int i = 0; while ((i = data.read(read)) > 0) { byteArray.write(read, 0, i); } data.close(); return byteArray.toByteArray(); } else if (flag == 0) { // size Anh dang: MinW < W < 720 < H || MinH < H < 720 < W double ratioWidth = (origDimentsion.width * 1.0) / fitDimentsion.width; double ratioHeight = (origDimentsion.height * 1.0) / fitDimentsion.height; if (ratioWidth < ratioHeight) { // fit width, crop height image. int yH = 0; if (origDimentsion.height > fitDimentsion.height) { yH = (origDimentsion.height - fitDimentsion.height) / 2; } return cropBufferedImage(isPNG, originalImage, 0, yH, origDimentsion.width, fitDimentsion.height); } else { // fit height, crop width image. int xW = 0; if (origDimentsion.width > fitDimentsion.width) { xW = (origDimentsion.width - fitDimentsion.width) / 2; } return cropBufferedImage(isPNG, originalImage, xW, 0, fitDimentsion.width, origDimentsion.height); } } else { // size Anh dang: 720 < W,H. // Scale Image. double ratioWidth = (origDimentsion.width * 1.0) / fitDimentsion.width; double ratioHeight = (origDimentsion.height * 1.0) / fitDimentsion.height; if (ratioWidth < ratioHeight) { // fit width, crop height image. int new_width = fitDimentsion.width; int new_height = (int) (origDimentsion.height / ratioWidth); int yH = 0; if (new_height > fitDimentsion.height) { yH = (new_height - fitDimentsion.height) / 2; } byte[] scaleByteImage = scaleBufferedImage(isPNG, originalImage, 0, 0, new_width, new_height); if (scaleByteImage != null && scaleByteImage.length > 0) { InputStream isImg = new ByteArrayInputStream(scaleByteImage); BufferedImage scaleBufferedImage = ImageIO.read(isImg); // Crop width image. return cropBufferedImage(isPNG, scaleBufferedImage, 0, yH, fitDimentsion.width, fitDimentsion.height); } } else { // fit height, crop width image. int new_width = (int) (origDimentsion.width / ratioHeight); int new_height = fitDimentsion.height; int xW = 0; if (new_width > fitDimentsion.width) { xW = (new_width - fitDimentsion.width) / 2; } byte[] scaleByteImage = scaleBufferedImage(isPNG, originalImage, 0, 0, new_width, new_height); if (scaleByteImage != null && scaleByteImage.length > 0) { InputStream isImg = new ByteArrayInputStream(scaleByteImage); BufferedImage scaleBufferedImage = ImageIO.read(isImg); // Crop height image. return cropBufferedImage(isPNG, scaleBufferedImage, xW, 0, fitDimentsion.width, fitDimentsion.height); } } } } catch (Exception ex) { } return null; }
From source file:de.innovationgate.wga.common.beans.csconfig.v1.CSConfig.java
public static CSConfig load(InputStream in, boolean forceClose) throws IOException, InvalidCSConfigVersionException { boolean marked = false; try {//w ww. j a v a2 s . c o m if (in.markSupported()) { in.mark(1024 * 64); marked = true; } CSConfig csConfig = (CSConfig) XStreamUtils.loadUtf8FromInputStream(XSTREAM, in, forceClose); csConfig.init(); return csConfig; } catch (CannotResolveClassException e) { if (marked) { try { in.reset(); throw new InvalidCSConfigVersionException(in); } catch (IOException ee) { } } throw new InvalidCSConfigVersionException(); } }
From source file:com.zotoh.core.io.StreamUte.java
/** * @param src//from w w w.j a v a2 s. c o m * @param out * @param reset * @throws IOException */ public static void streamToStream(InputStream src, OutputStream out, boolean reset) throws IOException { tstObjArg("out-stream", out); tstObjArg("in-stream", src); byte[] bits = new byte[4096]; int cnt; while ((cnt = src.read(bits)) > 0) { out.write(bits, 0, cnt); } safeFlush(out); if (reset && src.markSupported()) { src.reset(); } }
From source file:org.jets3t.service.utils.SignatureUtils.java
/** * Return SHA256 payload hash value already set on HTTP request, or if none * is yet set calculate this value if possible. * * @param httpMethod/*from w ww .j av a 2 s . co m*/ * the request's HTTP method just prior to sending * @return hex-encoded SHA256 hash of payload data. */ public static String awsV4GetOrCalculatePayloadHash(HttpUriRequest httpMethod) { // Lookup and return request payload SHA256 hash if present String requestPayloadHexSHA256Hash = null; Header sha256Header = httpMethod.getFirstHeader("x-amz-content-sha256"); if (sha256Header != null) { return sha256Header.getValue(); } // If request payload SHA256 isn't available, check for a payload if (httpMethod instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) httpMethod).getEntity(); // We will automatically generate the SHA256 hash for a limited // set of payload entities, and bail out early for the // unsupported ones. if (entity instanceof StringEntity || entity instanceof ByteArrayEntity || entity instanceof RepeatableRequestEntity) { try { // Hack to get to underlying input stream if this has been // wrapped by JetS3t's ProgressMonitoredInputStream, since // the caller didn't intend to monitor the progress of this // last-ditch effort to calculate a SHA256 hash. InputStream requestIS = entity.getContent(); while (requestIS instanceof ProgressMonitoredInputStream) { requestIS = ((ProgressMonitoredInputStream) requestIS).getWrappedInputStream(); } requestPayloadHexSHA256Hash = ServiceUtils.toHex(ServiceUtils.hashSHA256(requestIS, true // resetInsteadOfClose - reset don't close )); requestIS.reset(); } catch (IOException e) { throw new RuntimeException("Failed to automatically set required header" + " \"x-amz-content-sha256\" for request with" + " entity " + entity, e); } } // For unsupported payload entities bail out with a (hopefully) // useful error message. // We don't want to do too much automatically because it could // kill performance, without the reason being clear to users. else if (entity != null) { throw new RuntimeException("Header \"x-amz-content-sha256\" set to the hex-encoded" + " SHA256 hash of the request payload is required for" + " AWS Version 4 request signing, please set this on: " + httpMethod); } } if (requestPayloadHexSHA256Hash == null) { // If no payload, we set the SHA256 hash of an empty string. requestPayloadHexSHA256Hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; } return requestPayloadHexSHA256Hash; }