Java Code Examples for java.io.BufferedInputStream#mark()

The following examples show how to use java.io.BufferedInputStream#mark() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ICC_Profile.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static byte[] getProfileDataFromStream(InputStream s) throws IOException {

        BufferedInputStream bis = new BufferedInputStream(s);
        bis.mark(128);

        byte[] header = IOUtils.readNBytes(bis, 128);
        if (header[36] != 0x61 || header[37] != 0x63 ||
            header[38] != 0x73 || header[39] != 0x70) {
            return null;   /* not a valid profile */
        }
        int profileSize = ((header[0] & 0xff) << 24) |
                          ((header[1] & 0xff) << 16) |
                          ((header[2] & 0xff) << 8) |
                          (header[3] & 0xff);
        bis.reset();
        try {
            return IOUtils.readNBytes(bis, profileSize);
        } catch (OutOfMemoryError e) {
            throw new IOException("Color profile is too big");
        }
    }
 
Example 2
Source File: BufferedInputStreamResetTest.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
private void testNegative(final int readLimit) throws IOException {
    byte[] bytes = new byte[100];
    for (int i=0; i < bytes.length; i++)
        bytes[i] = (byte)i;
    // buffer of 10 bytes
    BufferedInputStream bis =
        new BufferedInputStream(new ByteArrayInputStream(bytes), 10);
    // skip 10 bytes
    bis.skip(10);
    bis.mark(readLimit);   // 1 byte short in buffer size
    // read 30 bytes in total, with internal buffer incread to 20
    bis.read(new byte[20]);
    try {
        bis.reset();
        fail();
    } catch(IOException ex) {
        assertEquals("Resetting to invalid mark", ex.getMessage());
    }
}
 
Example 3
Source File: ImageUtil.java    From DesignOverlay-Android with Apache License 2.0 6 votes vote down vote up
public static Bitmap decodeSampledBitmapFromStream(InputStream inputStream,
                                                     int reqWidth, int reqHeight) {
    final BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
    bufferedInputStream.mark(Integer.MAX_VALUE);

    // First decode with inJustDecodeBounds = true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(bufferedInputStream, null, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    try {
        bufferedInputStream.reset();
    } catch (IOException e) {
        Timber.w("Could not reposition the stream:" + e);
    }

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeStream(bufferedInputStream, null, options);
}
 
Example 4
Source File: RequestUtils.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Wraps an xml input xstream in a buffered reader specifying a lookahead that can be used to
 * preparse some of the xml document, resetting it back to its original state for actual
 * parsing.
 *
 * @param stream The original xml stream.
 * @param xmlLookahead The number of bytes to support for parse. If more than this number of
 *     bytes are preparsed the stream can not be properly reset.
 * @return The buffered reader.
 */
public static BufferedReader getBufferedXMLReader(InputStream stream, int xmlLookahead)
        throws IOException {

    // create a buffer so we can reset the input stream
    BufferedInputStream input = new BufferedInputStream(stream);
    input.mark(xmlLookahead);

    // create object to hold encoding info
    EncodingInfo encoding = new EncodingInfo();

    // call this method to set the encoding info
    XmlCharsetDetector.getCharsetAwareReader(input, encoding);

    // call this method to create the reader
    Reader reader = XmlCharsetDetector.createReader(input, encoding);

    // rest the input
    input.reset();

    return getBufferedXMLReader(reader, xmlLookahead);
}
 
Example 5
Source File: BufferedInputStreamResetTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void testPositive(final int readLimit) throws IOException {
    byte[] bytes = new byte[100];
    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = (byte) i;
    }
    // buffer of 10 bytes
    BufferedInputStream bis =
            new BufferedInputStream(new ByteArrayInputStream(bytes), 10);
    // skip 10 bytes
    bis.skip(10);
    bis.mark(readLimit);   // buffer size would increase up to readLimit
    // read 30 bytes in total, with internal buffer increased to 20
    bis.read(new byte[20]);
    bis.reset();
    assert (bis.read() == 10);
}
 
Example 6
Source File: JavaSoundAudioClip.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public JavaSoundAudioClip(InputStream in) throws IOException {
    if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.<init>");

    BufferedInputStream bis = new BufferedInputStream(in, STREAM_BUFFER_SIZE);
    bis.mark(STREAM_BUFFER_SIZE);
    boolean success = false;
    try {
        AudioInputStream as = AudioSystem.getAudioInputStream(bis);
        // load the stream data into memory
        success = loadAudioData(as);

        if (success) {
            success = false;
            if (loadedAudioByteLength < CLIP_THRESHOLD) {
                success = createClip();
            }
            if (!success) {
                success = createSourceDataLine();
            }
        }
    } catch (UnsupportedAudioFileException e) {
        // not an audio file
        try {
            MidiFileFormat mff = MidiSystem.getMidiFileFormat(bis);
            success = createSequencer(bis);
        } catch (InvalidMidiDataException e1) {
            success = false;
        }
    }
    if (!success) {
        throw new IOException("Unable to create AudioClip from input stream");
    }
}
 
Example 7
Source File: BitmapAsyncTask.java    From ShareSDK with MIT License 5 votes vote down vote up
private Bitmap getSampleBitmap(InputStream is, int width, int height) {

        BufferedInputStream stream = new BufferedInputStream(is);
        stream.mark(4 * 1024);
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(stream, null, options);
        calculateInSampleSize(width, height, options, true);
        try {
            stream.reset();
        } catch (IOException e) {
        }
        return BitmapFactory.decodeStream(stream, null, options);
    }
 
Example 8
Source File: Asn1StreamParser.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected static byte[] readBlock(int expectedTag, BufferedInputStream instream, String name)
    throws IOException {
  instream.mark(10);
  int tag = instream.read();
  assertTag(expectedTag, tag, name);

  return readBlock(instream, name);
}
 
Example 9
Source File: HttpService.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private InputStream buildInputStream(ResponseBody responseBody) throws IOException {
    InputStream inputStream = responseBody.byteStream();

    if (includeRawResponse) {
        // we have to buffer the entire input payload, so that after processing
        // it can be re-read and used to populate the rawResponse field.

        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body
        Buffer buffer = source.buffer();

        long size = buffer.size();
        if (size > Integer.MAX_VALUE) {
            throw new UnsupportedOperationException(
                    "Non-integer input buffer size specified: " + size);
        }

        int bufferSize = (int) size;
        BufferedInputStream bufferedinputStream =
                new BufferedInputStream(inputStream, bufferSize);

        bufferedinputStream.mark(inputStream.available());
        return bufferedinputStream;

    } else {
        return inputStream;
    }
}
 
Example 10
Source File: Connection.java    From CordovaYoutubeVideoPlayer with MIT License 5 votes vote down vote up
/**
 * Returns true if we are confident that we can read data from this
 * connection. This is more expensive and more accurate than {@link
 * #isAlive()}; callers should check {@link #isAlive()} first.
 */
public boolean isReadable() {
  if (!(in instanceof BufferedInputStream)) {
    return true; // Optimistic.
  }
  if (isSpdy()) {
    return true; // Optimistic. We can't test SPDY because its streams are in use.
  }
  BufferedInputStream bufferedInputStream = (BufferedInputStream) in;
  try {
    int readTimeout = socket.getSoTimeout();
    try {
      socket.setSoTimeout(1);
      bufferedInputStream.mark(1);
      if (bufferedInputStream.read() == -1) {
        return false; // Stream is exhausted; socket is closed.
      }
      bufferedInputStream.reset();
      return true;
    } finally {
      socket.setSoTimeout(readTimeout);
    }
  } catch (SocketTimeoutException ignored) {
    return true; // Read timed out; socket is good.
  } catch (IOException e) {
    return false; // Couldn't read; socket is closed.
  }
}
 
Example 11
Source File: Request.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private static boolean peekStream( BufferedInputStream in ) 
    throws IOException {
    
    in.mark( 1 );
    boolean notYet =  in.read() > -1;
    in.reset();
    return notYet;
    
}
 
Example 12
Source File: CompositeImageData.java    From slick2d-maven with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @see org.newdawn.slick.opengl.LoadableImageData#loadImage(java.io.InputStream, boolean, boolean, int[])
 */
public ByteBuffer loadImage(InputStream is, boolean flipped, boolean forceAlpha, int[] transparent) throws IOException {
	CompositeIOException exception = new CompositeIOException();
	ByteBuffer buffer = null;
	
	BufferedInputStream in = new BufferedInputStream(is, is.available());
	in.mark(is.available());
	
	// cycle through our source until one of them works
	for (int i=0;i<sources.size();i++) {
		in.reset();
		try {
			LoadableImageData data = (LoadableImageData) sources.get(i);
			
			buffer = data.loadImage(in, flipped, forceAlpha, transparent);
			picked = data;
			break;
		} catch (Exception e) {
			Log.warn(sources.get(i).getClass()+" failed to read the data", e);
			exception.addException(e);
		}
	}
	
	if (picked == null) {
		throw exception;
	}
	
	return buffer;
}
 
Example 13
Source File: JavaSoundAudioClip.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public JavaSoundAudioClip(InputStream in) throws IOException {
    if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.<init>");

    BufferedInputStream bis = new BufferedInputStream(in, STREAM_BUFFER_SIZE);
    bis.mark(STREAM_BUFFER_SIZE);
    boolean success = false;
    try {
        AudioInputStream as = AudioSystem.getAudioInputStream(bis);
        // load the stream data into memory
        success = loadAudioData(as);

        if (success) {
            success = false;
            if (loadedAudioByteLength < CLIP_THRESHOLD) {
                success = createClip();
            }
            if (!success) {
                success = createSourceDataLine();
            }
        }
    } catch (UnsupportedAudioFileException e) {
        // not an audio file
        try {
            MidiFileFormat mff = MidiSystem.getMidiFileFormat(bis);
            success = createSequencer(bis);
        } catch (InvalidMidiDataException e1) {
            success = false;
        }
    }
    if (!success) {
        throw new IOException("Unable to create AudioClip from input stream");
    }
}
 
Example 14
Source File: AstaFileReader.java    From mpxj with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override public ProjectFile read(InputStream inputStream) throws MPXJException
{
   try
   {
      BufferedInputStream is = new BufferedInputStream(inputStream);
      is.mark(100);
      byte[] buffer = new byte[SQLITE_TEXT.length()];
      is.read(buffer);
      is.reset();
      String actualText = new String(buffer);
      ProjectFile result;
      if (SQLITE_TEXT.equals(actualText))
      {
         result = readDatabaseFile(is);
      }
      else
      {
         result = readTextFile(is);
      }
      return result;
   }

   catch (IOException ex)
   {
      throw new MPXJException("Failed to read file", ex);
   }
}
 
Example 15
Source File: JavaSoundAudioClip.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public JavaSoundAudioClip(InputStream in) throws IOException {
    if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.<init>");

    BufferedInputStream bis = new BufferedInputStream(in, STREAM_BUFFER_SIZE);
    bis.mark(STREAM_BUFFER_SIZE);
    boolean success = false;
    try {
        AudioInputStream as = AudioSystem.getAudioInputStream(bis);
        // load the stream data into memory
        success = loadAudioData(as);

        if (success) {
            success = false;
            if (loadedAudioByteLength < CLIP_THRESHOLD) {
                success = createClip();
            }
            if (!success) {
                success = createSourceDataLine();
            }
        }
    } catch (UnsupportedAudioFileException e) {
        // not an audio file
        try {
            MidiFileFormat mff = MidiSystem.getMidiFileFormat(bis);
            success = createSequencer(bis);
        } catch (InvalidMidiDataException e1) {
            success = false;
        }
    }
    if (!success) {
        throw new IOException("Unable to create AudioClip from input stream");
    }
}
 
Example 16
Source File: Utils.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
static byte[] readMagic(BufferedInputStream in) throws IOException {
    in.mark(4);
    byte[] magic = new byte[4];
    for (int i = 0; i < magic.length; i++) {
        // read 1 byte at a time, so we always get 4
        if (1 != in.read(magic, i, 1))
            break;
    }
    in.reset();
    return magic;
}
 
Example 17
Source File: Connection.java    From reader with MIT License 5 votes vote down vote up
/**
 * Returns true if we are confident that we can read data from this
 * connection. This is more expensive and more accurate than {@link
 * #isAlive()}; callers should check {@link #isAlive()} first.
 */
public boolean isReadable() {
  if (!(in instanceof BufferedInputStream)) {
    return true; // Optimistic.
  }
  if (isSpdy()) {
    return true; // Optimistic. We can't test SPDY because its streams are in use.
  }
  BufferedInputStream bufferedInputStream = (BufferedInputStream) in;
  try {
    int readTimeout = socket.getSoTimeout();
    try {
      socket.setSoTimeout(1);
      bufferedInputStream.mark(1);
      if (bufferedInputStream.read() == -1) {
        return false; // Stream is exhausted; socket is closed.
      }
      bufferedInputStream.reset();
      return true;
    } finally {
      socket.setSoTimeout(readTimeout);
    }
  } catch (SocketTimeoutException ignored) {
    return true; // Read timed out; socket is good.
  } catch (IOException e) {
    return false; // Couldn't read; socket is closed.
  }
}
 
Example 18
Source File: AWHttpService.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private InputStream buildInputStream(ResponseBody responseBody) throws IOException {
    InputStream inputStream = responseBody.byteStream();

    if (includeRawResponse) {
        // we have to buffer the entire input payload, so that after processing
        // it can be re-read and used to populate the rawResponse field.

        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body
        Buffer buffer = source.buffer();

        long size = buffer.size();
        if (size > Integer.MAX_VALUE) {
            throw new UnsupportedOperationException(
                    "Non-integer input buffer size specified: " + size);
        }

        int bufferSize = (int) size;
        BufferedInputStream bufferedinputStream =
                new BufferedInputStream(inputStream, bufferSize);

        bufferedinputStream.mark(inputStream.available());
        return bufferedinputStream;

    } else {
        return inputStream;
    }
}
 
Example 19
Source File: AnalysisXmlConvertConfigDialg.java    From translationstudio8 with GNU General Public License v2.0 4 votes vote down vote up
public static String getEncoding(File file) {
	String charset = "GBK";
	byte[] first3Bytes = new byte[3];
	boolean checked = false;
	try {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
		bis.mark(0);
		int read = bis.read(first3Bytes, 0, 3);
		if (read == -1)
			return charset;
		if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
			charset = "UTF-16LE";
			checked = true;
		}
		else if (first3Bytes[0] == (byte) 0xFE
				&& first3Bytes[1] == (byte) 0xFF) {
			charset = "UTF-16BE";
			checked = true;
		}
		else if (first3Bytes[0] == (byte) 0xEF
				&& first3Bytes[1] == (byte) 0xBB
				&& first3Bytes[2] == (byte) 0xBF) {
			charset = "UTF-8";
			checked = true;
		}
		bis.reset();
		if (!checked) {
			int loc = 0;
			while ((read = bis.read()) != -1) {
				loc++;
				if (read >= 0xF0)
					break;
				if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK
					break;
				if (0xC0 <= read && read <= 0xDF) {
					read = bis.read();
					if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF)// (0x80 - 0xBF),也可能在GB编码内
						continue;
					else
						break;
				}
				else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小
					read = bis.read();
					if (0x80 <= read && read <= 0xBF) {
						read = bis.read();
						if (0x80 <= read && read <= 0xBF) {
							charset = "UTF-8";
							break;
						}
						else
							break;
					}
					else
						break;
				}
			}
		}
		bis.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return charset;
}
 
Example 20
Source File: BibliographyFileReader.java    From citeproc-java with Apache License 2.0 4 votes vote down vote up
/**
 * Reads the first bytes of the given input stream and tries to
 * determine the file format. Resets the input stream to the position
 * it had when the method was called. Reads up to 100 KB and before
 * giving up. Note that you can supply an additional file name to help
 * the method to determine the exact file format. If you don't know the
 * file name you can pass null, but in this case the method's result
 * might be wrong (depending on the input stream's contents).
 * @param bis a buffered input stream that supports the mark and reset
 * methods
 * @param filename the name of the input file (can be null if you don't
 * know the name)
 * @return the file format (or {@link FileFormat#UNKNOWN} if the format
 * could not be determined)
 * @throws IOException if the input stream could not be read
 */
public FileFormat determineFileFormat(BufferedInputStream bis,
        String filename) throws IOException {
    int len = 1024 * 100;

    String ext = "";
    if (filename != null) {
        int dot = filename.lastIndexOf('.');
        if (dot > 0) {
            ext = filename.substring(dot + 1);
        }
    }

    // check the first couple of bytes
    bis.mark(len);
    try {
        byte[] firstCharacters = new byte[6];
        bis.read(firstCharacters);

        // check if the file starts with a %YAML directive
        if (firstCharacters[0] == '%' &&
                firstCharacters[1] == 'Y' &&
                firstCharacters[2] == 'A' &&
                firstCharacters[3] == 'M' &&
                firstCharacters[4] == 'L' &&
                Character.isWhitespace(firstCharacters[5])) {
            return FileFormat.YAML;
        }

        // check if the file starts with an EndNote tag, but
        // also make sure the extension is not 'bib' or 'yml'/'yaml'
        // because BibTeX comments and YAML directives look like
        // EndNote tags
        if (firstCharacters[0] == '%' &&
                Character.isWhitespace(firstCharacters[2]) &&
                !ext.equalsIgnoreCase("bib") &&
                !ext.equalsIgnoreCase("yaml") &&
                !ext.equalsIgnoreCase("yml")) {
            return FileFormat.ENDNOTE;
        }

        // check if the file starts with a RIS type tag
        if (firstCharacters[0] == 'T' && firstCharacters[1] == 'Y' &&
                Character.isWhitespace(firstCharacters[2]) &&
                Character.isWhitespace(firstCharacters[3]) &&
                firstCharacters[4] == '-') {
            return FileFormat.RIS;
        }
    } finally {
        bis.reset();
    }

    // now check if it's json, bibtex or yaml
    bis.mark(len);
    try {
        while (true) {
            int c = bis.read();
            --len;
            if (c < 0 || len < 2) {
                return FileFormat.UNKNOWN;
            }

            if (!Character.isWhitespace(c)) {
                if (c == '[') {
                    return FileFormat.JSON_ARRAY;
                } else if (c == '{') {
                    return FileFormat.JSON_OBJECT;
                }
                if (ext.equalsIgnoreCase("yaml") ||
                        ext.equalsIgnoreCase("yml")) {
                    return FileFormat.YAML;
                }
                return FileFormat.BIBTEX;
            }
        }
    } finally {
        bis.reset();
    }
}