Java Code Examples for java.io.InputStream.reset()

The following are Jave code examples for showing how to use reset() of the java.io.InputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: CacheWebView   File: BytesEncodingDetect.java   View Source Code Vote up 7 votes
public String detectEncodingStr(InputStream inputStream){
    String strEnc ="UTF-8";
    inputStream.mark(0);
    int enc = detectEncoding(inputStream);
    try {
        if (inputStream.markSupported()){
            inputStream.reset();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (enc!=-1){
        return Encoding.htmlname[enc];
    }

    return strEnc;
}
 
Example 2
Project: openjdk-jdk10   File: XIncludeTextReader.java   View Source Code Vote up 6 votes
/**
 * XMLEntityManager cares about endian-ness, since it creates its own optimized
 * readers. Since we're just using generic Java readers for now, we're not caring
 * about endian-ness.  If this changes, even more code needs to be copied from
 * XMLEntity manager. -- PJM
 */
protected String getEncodingName(InputStream stream) throws IOException {
    final byte[] b4 = new byte[4];
    String encoding = null;

    // this has the potential to throw an exception
    // it will be fixed when we ensure the stream is rewindable (see note above)
    stream.mark(4);
    int count = stream.read(b4, 0, 4);
    stream.reset();
    if (count == 4) {
        encoding = getEncodingName(b4);
    }

    return encoding;
}
 
Example 3
Project: ibm-cos-sdk-java   File: AbstractAWSSigner.java   View Source Code Vote up 6 votes
/**
 * Returns the request's payload contents as binary data, without processing
 * any query string params (i.e. no form encoding for query params).
 *
 * @param request
 *            The request
 * @return The request's payload contents as binary data, not including any
 *         form encoding of query string params.
 */
protected byte[] getBinaryRequestPayloadWithoutQueryParams(SignableRequest<?> request) {
    InputStream content = getBinaryRequestPayloadStreamWithoutQueryParams(request);

    try {
        ReadLimitInfo info = request.getReadLimitInfo();
        content.mark(info == null ? -1 : info.getReadLimit());
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 5];
        while (true) {
            int bytesRead = content.read(buffer);
            if (bytesRead == -1) break;

            byteArrayOutputStream.write(buffer, 0, bytesRead);
        }

        byteArrayOutputStream.close();
        content.reset();

        return byteArrayOutputStream.toByteArray();
    } catch (Exception e) {
        throw new SdkClientException("Unable to read request payload to sign request: " + e.getMessage(), e);
    }
}
 
Example 4
Project: lams   File: HttpUnitUtils.java   View Source Code Vote up 6 votes
/**
 * parse the given inputStream with a new Parser
 * @param inputStream
 * @return the document parsed from the input Stream
 */
public static Document parse(InputStream inputStream) throws SAXException,IOException {
	DocumentBuilder db=newParser();
	try {
		Document doc=db.parse(inputStream);
	return doc;  			
	} catch (java.net.MalformedURLException mue) {
		if (EXCEPTION_DEBUG) {
			String msg=mue.getMessage();
			if (msg!=null) {
				System.err.println(msg);
			}	
			InputStream is=inputStream;
			is.reset();
			String content=parseISToString(is);
			System.err.println(content);
		}	
		throw mue;
	}
}
 
Example 5
Project: guava-mock   File: ByteStreamsTest.java   View Source Code Vote up 6 votes
public void testLimit_mark() throws Exception {
  byte[] big = newPreFilledByteArray(5);
  InputStream bin = new ByteArrayInputStream(big);
  InputStream lin = ByteStreams.limit(bin, 2);

  int read = lin.read();
  assertEquals(big[0], read);
  lin.mark(2);

  read = lin.read();
  assertEquals(big[1], read);
  read = lin.read();
  assertEquals(-1, read);

  lin.reset();
  read = lin.read();
  assertEquals(big[1], read);
  read = lin.read();
  assertEquals(-1, read);
}
 
Example 6
Project: GitHub   File: Downsampler.java   View Source Code Vote up 5 votes
private static Bitmap decodeStream(InputStream is, BitmapFactory.Options options,
    DecodeCallbacks callbacks) throws IOException {
  if (options.inJustDecodeBounds) {
    is.mark(MARK_POSITION);
  } else {
    // Once we've read the image header, we no longer need to allow the buffer to expand in
    // size. To avoid unnecessary allocations reading image data, we fix the mark limit so that it
    // is no larger than our current buffer size here. We need to do so immediately before
    // decoding the full image to avoid having our mark limit overridden by other calls to
    // markand reset. See issue #225.
    callbacks.onObtainBounds();
  }
  // BitmapFactory.Options out* variables are reset by most calls to decodeStream, successful or
  // otherwise, so capture here in case we log below.
  int sourceWidth = options.outWidth;
  int sourceHeight = options.outHeight;
  String outMimeType = options.outMimeType;
  final Bitmap result;
  TransformationUtils.getBitmapDrawableLock().lock();
  try {
    result = BitmapFactory.decodeStream(is, null, options);
  } catch (IllegalArgumentException e) {
    throw newIoExceptionForInBitmapAssertion(e, sourceWidth, sourceHeight, outMimeType, options);
  } finally {
    TransformationUtils.getBitmapDrawableLock().unlock();
  }

  if (options.inJustDecodeBounds) {
    is.reset();

  }
  return result;
}
 
Example 7
Project: aws-sdk-java-v2   File: Aws4Signer.java   View Source Code Vote up 5 votes
/**
 * Calculate the hash of the request's payload. Subclass could override this
 * method to provide different values for "x-amz-content-sha256" header or
 * do any other necessary set-ups on the request headers. (e.g. aws-chunked
 * uses a pre-defined header value, and needs to change some headers
 * relating to content-encoding and content-length.)
 */
protected String calculateContentHash(Aws4SignerRequestParams signerRequestParams,
                                      SdkHttpFullRequest.Builder requestBuilder) {
    SdkHttpFullRequest.Builder requestToSign = signerRequestParams.httpRequest();
    InputStream payloadStream = getBinaryRequestPayloadStream(requestToSign.content());
    payloadStream.mark(getReadLimit(signerRequestParams));
    String contentSha256 = BinaryUtils.toHex(hash(payloadStream));
    try {
        payloadStream.reset();
    } catch (IOException e) {
        throw new SdkClientException("Unable to reset stream after calculating AWS4 signature", e);
    }
    return contentSha256;
}
 
Example 8
Project: jdk8u-jdk   File: WaveExtensibleFileReader.java   View Source Code Vote up 5 votes
public AudioFileFormat getAudioFileFormat(InputStream stream)
        throws UnsupportedAudioFileException, IOException {

    stream.mark(200);
    AudioFileFormat format;
    try {
        format = internal_getAudioFileFormat(stream);
    } finally {
        stream.reset();
    }
    return format;
}
 
Example 9
Project: aws-sdk-java-v2   File: AsyncRetryableStage.java   View Source Code Vote up 5 votes
/**
 * Reset the input stream of the request before a retry.
 *
 * @throws ResetException If Input Stream can't be reset which means the request can't be retried.
 */
private static void resetRequestInputStream(InputStream inputStream) throws ResetException {
    if (inputStream.markSupported()) {
        try {
            inputStream.reset();
        } catch (IOException ex) {
            throw new ResetException("Failed to reset the request input stream", ex);
        }
    }
}
 
Example 10
Project: hadoop   File: TestTextInputFormat.java   View Source Code Vote up 5 votes
@Test (timeout=5000)
public void testMRMaxLine() throws Exception {
  final int MAXPOS = 1024 * 1024;
  final int MAXLINE = 10 * 1024;
  final int BUF = 64 * 1024;
  final InputStream infNull = new InputStream() {
    int position = 0;
    final int MAXPOSBUF = 1024 * 1024 + BUF; // max LRR pos + LineReader buf
    @Override
    public int read() {
      ++position;
      return 0;
    }
    @Override
    public int read(byte[] b) {
      assertTrue("Read too many bytes from the stream", position < MAXPOSBUF);
      Arrays.fill(b, (byte) 0);
      position += b.length;
      return b.length;
    }
    public void reset() {
      position=0;
    }
  };
  final LongWritable key = new LongWritable();
  final Text val = new Text();
  LOG.info("Reading a line from /dev/null");
  final Configuration conf = new Configuration(false);
  conf.setInt(org.apache.hadoop.mapreduce.lib.input.
              LineRecordReader.MAX_LINE_LENGTH, MAXLINE);
  conf.setInt("io.file.buffer.size", BUF); // used by LRR
  // test another constructor 
   LineRecordReader lrr = new LineRecordReader(infNull, 0, MAXPOS, conf);
  assertFalse("Read a line from null", lrr.next(key, val));
  infNull.reset();
   lrr = new LineRecordReader(infNull, 0L, MAXLINE, MAXPOS);
  assertFalse("Read a line from null", lrr.next(key, val));
  
  
}
 
Example 11
Project: letv   File: BaseImageDecoder.java   View Source Code Vote up 5 votes
protected InputStream resetStream(InputStream imageStream, ImageDecodingInfo decodingInfo) throws IOException {
    try {
        imageStream.reset();
        return imageStream;
    } catch (IOException e) {
        IoUtils.closeSilently(imageStream);
        return getImageStream(decodingInfo);
    }
}
 
Example 12
Project: OpenJSharp   File: WaveFloatFileReader.java   View Source Code Vote up 5 votes
public AudioFileFormat getAudioFileFormat(InputStream stream)
        throws UnsupportedAudioFileException, IOException {

    stream.mark(200);
    AudioFileFormat format;
    try {
        format = internal_getAudioFileFormat(stream);
    } finally {
        stream.reset();
    }
    return format;
}
 
Example 13
Project: boohee_v5.6   File: BaseImageDecoder.java   View Source Code Vote up 5 votes
protected InputStream resetStream(InputStream imageStream, ImageDecodingInfo decodingInfo)
        throws IOException {
    if (imageStream.markSupported()) {
        try {
            imageStream.reset();
            return imageStream;
        } catch (IOException e) {
        }
    }
    IoUtils.closeSilently(imageStream);
    return getImageStream(decodingInfo);
}
 
Example 14
Project: NioSmtpClient   File: InputStreamMessageContent.java   View Source Code Vote up 5 votes
@Override
public float get8bitCharacterProportion() {
  if (eightBitCharProportion != UNCOUNTED) {
    return eightBitCharProportion;
  }

  int eightBitCharCount = 0;

  InputStream inputStream = getStream();

  if (!inputStream.markSupported()) {
    // if we can't examine the stream non-destructively,
    // assume it has some 8 bit characters, but not enough
    // to require encoding the body as base64
    eightBitCharProportion = DEFAULT_8BIT_PROPORTION;
    return eightBitCharProportion;
  }

  inputStream.mark(READ_LIMIT);

  try {
    int c, bytesRead = 0;

    while (bytesRead < READ_LIMIT && (c = inputStream.read()) != -1) {
      if (0 != (c & 0x80)) {
        eightBitCharCount++;
      }

      bytesRead++;
    }

    inputStream.reset();
    eightBitCharProportion = 1.0F * eightBitCharCount / bytesRead;

  } catch (IOException e) {
    throw new RuntimeException(e);
  }

  return eightBitCharProportion;
}
 
Example 15
Project: JNomad-Plugin   File: JNomadInspection.java   View Source Code Vote up 5 votes
private static synchronized List<EnvFileFullReport> getFileFullReports(CharSequence charSequence) {
    List<EnvFileFullReport> fileReports = new ArrayList<>();
    try {
        InputStream virtualFile = IOUtils.toInputStream(charSequence, "UTF-8");
        String md5Hash = ByteSource.wrap(ByteStreams.toByteArray(virtualFile)).hash(Hashing.md5()).toString();
        fileReports = fileReportCache.getIfPresent(md5Hash);
        virtualFile.reset();

        if (fileReports == null && JNomadInspection.jnomad != null) { //no cache; load file from disk
            fileReports = new ArrayList<>();
            QueryLiteralExtractor.isDisabled = false;
            SourceCodeExtract extract = JNomadInspection.jnomad.scanSingleFile(virtualFile);
            if (extract.getQueryLiteralExtractor().getQueryFound()) {
                List<SourceCodeExtract> scanList = Collections.singletonList(extract);
                queryParser.run(scanList);

                for (JNomadPluginConfiguration.DBEnvironment env : pluginConfiguration.getEnvironmentList()) {
                    for (JNomadPluginConfiguration.DBConnection conn : env.getConnectionList()) {
                        EnvFileFullReport envReport = new EnvFileFullReport(null, JNomadInspection.jnomad, conn.getDataType(), queryParser.getAliasMap(), scanList, conn.toConnection());
                        envReport.setEnvironment(env);
                        fileReports.add(envReport);
                    }
                }
                fileReportCache.put(md5Hash, fileReports);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return fileReports;
}
 
Example 16
Project: GitHub   File: Downsampler.java   View Source Code Vote up 4 votes
private static Bitmap decodeStream(InputStream is, BitmapFactory.Options options,
    DecodeCallbacks callbacks, BitmapPool bitmapPool) throws IOException {
  if (options.inJustDecodeBounds) {
    is.mark(MARK_POSITION);
  } else {
    // Once we've read the image header, we no longer need to allow the buffer to expand in
    // size. To avoid unnecessary allocations reading image data, we fix the mark limit so that it
    // is no larger than our current buffer size here. We need to do so immediately before
    // decoding the full image to avoid having our mark limit overridden by other calls to
    // mark and reset. See issue #225.
    callbacks.onObtainBounds();
  }
  // BitmapFactory.Options out* variables are reset by most calls to decodeStream, successful or
  // otherwise, so capture here in case we log below.
  int sourceWidth = options.outWidth;
  int sourceHeight = options.outHeight;
  String outMimeType = options.outMimeType;
  final Bitmap result;
  TransformationUtils.getBitmapDrawableLock().lock();
  try {
    result = BitmapFactory.decodeStream(is, null, options);
  } catch (IllegalArgumentException e) {
    IOException bitmapAssertionException =
        newIoExceptionForInBitmapAssertion(e, sourceWidth, sourceHeight, outMimeType, options);
    if (Log.isLoggable(TAG, Log.DEBUG)) {
      Log.d(TAG, "Failed to decode with inBitmap, trying again without Bitmap re-use",
          bitmapAssertionException);
    }
    if (options.inBitmap != null) {
      try {
        is.reset();
        bitmapPool.put(options.inBitmap);
        options.inBitmap = null;
        return decodeStream(is, options, callbacks, bitmapPool);
      } catch (IOException resetException) {
        throw bitmapAssertionException;
      }
    }
    throw bitmapAssertionException;
  } finally {
    TransformationUtils.getBitmapDrawableLock().unlock();
  }

  if (options.inJustDecodeBounds) {
    is.reset();

  }
  return result;
}
 
Example 17
Project: microbit   File: HexInputStream.java   View Source Code Vote up 4 votes
private int calculateBinSizeAlternative() throws IOException {
    int binSize = 0;
    final InputStream in = this.in;
    in.mark(in.available());

    int b, lineSize, offset, type;
    int lastBaseAddress = 0; // last Base Address, default 0
    int lastAddress;
    try {
        b = in.read();
        while (true) {
            checkComma(b);

            lineSize = readByte(in); // reading the length of the data in this line
            offset = readAddress(in);// reading the offset
            type = readByte(in); // reading the line type
            switch (type) {
                case 0x01:
                    // end of file
                    return binSize;
                case 0x04: {
                    // extended linear address record
	/*
	 * The HEX file may contain jump to different addresses. The MSB of LBA (Linear Base Address) is given using the line type 4.
	 * We only support files where bytes are located together, no jumps are allowed. Therefore the newULBA may be only lastULBA + 1 (or any, if this is the first line of the HEX)
	 */
                    final int newULBA = readAddress(in);
                    if (binSize > 0 && newULBA != (lastBaseAddress >> 16) + 1)
                        return binSize;
                    lastBaseAddress = newULBA << 16;
		skip(in, 2 /* check sum */);
                    break;
                }
                case 0x02: {
                    // extended segment address record
                    final int newSBA = readAddress(in) << 4;
                    if (binSize > 0 && (newSBA >> 16) != (lastBaseAddress >> 16) + 1)
                        return binSize;
                    lastBaseAddress = newSBA;
                    skip(in, 2 /* check sum */);
                    break;
                }
                case 0x00:
                    // data type line
                    lastAddress = lastBaseAddress + offset;
                    if (lastAddress >= DfuSettingsConstants.APP_CODE_BASE_START && lastAddress < DfuSettingsConstants.APP_CODE_BASE_END)
                    {
                        //Log.d("HexInputStrem", "Found FOTA Start address");
                        binSize += lineSize;
                    }
                    // no break!
                default:
                    skip(in, lineSize * 2 /* 2 hex per one byte */+ 2 /* check sum */);
                    break;
            }
            // skip end of line
            while (true) {
                b = in.read();

                if (b != '\n' && b != '\r') {
                    break;
                }
            }
        }
    } finally {
        in.reset();
    }
}
 
Example 18
Project: jdk8u-jdk   File: BandStructure.java   View Source Code Vote up 4 votes
@Override
protected void readDataFrom(InputStream in) throws IOException {
    length = valuesExpected();
    if (length == 0)  return;  // nothing to read
    if (verbose > 1)
        Utils.log.fine("Reading band "+this);
    if (!canVaryCoding()) {
        bandCoding = regularCoding;
        metaCoding = noMetaCoding;
    } else {
        assert(in.markSupported());  // input must be buffered
        in.mark(Coding.B_MAX);
        int X = regularCoding.setD(0).readFrom(in);
        int XB = decodeEscapeValue(X, regularCoding);
        if (XB < 0) {
            // Do not consume this value.  No alternate coding.
            in.reset();
            bandCoding = regularCoding;
            metaCoding = noMetaCoding;
        } else if (XB == _meta_default) {
            bandCoding = regularCoding;
            metaCoding = defaultMetaCoding;
        } else {
            if (verbose > 2)
                Utils.log.fine("found X="+X+" => XB="+XB);
            bandCoding = getBandHeader(XB, regularCoding);
            // This is really used only by dumpBands.
            int p0 = bandHeaderBytePos0;
            int p1 = bandHeaderBytePos;
            metaCoding = new byte[p1-p0];
            System.arraycopy(bandHeaderBytes, p0,
                             metaCoding, 0, metaCoding.length);
        }
    }
    if (bandCoding != regularCoding) {
        if (verbose > 1)
            Utils.log.fine(name()+": irregular coding "+bandCoding);
    }
    bandCoding.readArrayFrom(in, values, 0, length);
    if (optDumpBands)  dumpBand();
}
 
Example 19
Project: elasticsearch_my   File: MockAmazonS3.java   View Source Code Vote up 4 votes
private int getSize(InputStream stream) throws IOException {
    int size = stream.read(byteCounter);
    stream.reset(); // in case we ever need the size again
    return size;
}
 
Example 20
Project: OpenJSharp   File: AiffFileReader.java   View Source Code Vote up 3 votes
/**
 * Obtains the audio file format of the input stream provided.  The stream must
 * point to valid audio file data.  In general, audio file providers may
 * need to read some data from the stream before determining whether they
 * support it.  These parsers must
 * be able to mark the stream, read enough data to determine whether they
 * support the stream, and, if not, reset the stream's read pointer to its original
 * position.  If the input stream does not support this, this method may fail
 * with an IOException.
 * @param stream the input stream from which file format information should be
 * extracted
 * @return an <code>AudioFileFormat</code> object describing the audio file format
 * @throws UnsupportedAudioFileException if the stream does not point to valid audio
 * file data recognized by the system
 * @throws IOException if an I/O exception occurs
 * @see InputStream#markSupported
 * @see InputStream#mark
 */
public AudioFileFormat getAudioFileFormat(InputStream stream) throws UnsupportedAudioFileException, IOException {
    // fix for 4489272: AudioSystem.getAudioFileFormat() fails for InputStream, but works for URL
    AudioFileFormat aff = getCOMM(stream, true);
    // the following is not strictly necessary - but was implemented like that in 1.3.0 - 1.4.1
    // so I leave it as it was. May remove this for 1.5.0
    stream.reset();
    return aff;
}