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

The following are Jave code examples for showing how to use mark() 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: guava-mock   File: ByteStreamsTest.java   View Source Code Vote up 6 votes
public void testLimit_skip() throws Exception {
  byte[] big = newPreFilledByteArray(5);
  InputStream bin = new ByteArrayInputStream(big);
  InputStream lin = ByteStreams.limit(bin, 2);

  // also test available
  lin.mark(2);
  assertEquals(2, lin.available());
  lin.skip(1);
  assertEquals(1, lin.available());

  lin.reset();
  assertEquals(2, lin.available());
  lin.skip(3);
  assertEquals(0, lin.available());
}
 
Example 2
Project: Hubs   File: Globals.java   View Source Code Vote up 6 votes
/** Load lua source or lua binary from an input stream into a Prototype. 
 * The InputStream is either a binary lua chunk starting with the lua binary chunk signature, 
 * or a text input file.  If it is a text input file, it is interpreted as a UTF-8 byte sequence.  
 * @param is Input stream containing a lua script or compiled lua"
 * @param chunkname Name that will be used within the chunk as the source.
 * @param mode String containing 'b' or 't' or both to control loading as binary or text or either.
 */
public Prototype loadPrototype(InputStream is, String chunkname, String mode) throws IOException {
	if (mode.indexOf('b') >= 0) {
		if (undumper == null)
			error("No undumper.");
		if (!is.markSupported())
			is = new BufferedStream(is);
		is.mark(4);
		final Prototype p = undumper.undump(is, chunkname);
		if (p != null)
			return p;
		is.reset();
	}
	if (mode.indexOf('t') >= 0) {
		return compilePrototype(is, chunkname);
	}
	error("Failed to load prototype "+chunkname+" using mode '"+mode+"'");
	return null;
}
 
Example 3
Project: GitHub   File: URLConnectionTest.java   View Source Code Vote up 6 votes
private void testMarkAndReset(TransferKind transferKind) throws IOException {
  MockResponse response = new MockResponse();
  transferKind.setBody(response, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1024);
  server.enqueue(response);
  server.enqueue(response);

  InputStream in = urlFactory.open(server.url("/").url()).getInputStream();
  assertFalse("This implementation claims to support mark().", in.markSupported());
  in.mark(5);
  assertEquals("ABCDE", readAscii(in, 5));
  try {
    in.reset();
    fail();
  } catch (IOException expected) {
  }
  assertEquals("FGHIJKLMNOPQRSTUVWXYZ", readAscii(in, Integer.MAX_VALUE));
  in.close();
  assertContent("ABCDEFGHIJKLMNOPQRSTUVWXYZ", urlFactory.open(server.url("/").url()));
}
 
Example 4
Project: javaide   File: AddonsListFetcher.java   View Source Code Vote up 6 votes
/**
 * Fetches the document at the given URL and returns it as a stream. Returns
 * null if anything wrong happens.
 *
 * @param urlString The URL to load, as a string.
 * @param monitor {@link ITaskMonitor} related to this URL.
 * @param outException If non null, where to store any exception that
 *            happens during the fetch.
 * @see UrlOpener UrlOpener, which handles all URL logic.
 */
private InputStream fetchXmlUrl(String urlString,
        DownloadCache cache,
        ITaskMonitor monitor,
        Exception[] outException) {
    try {
        InputStream xml = cache.openCachedUrl(urlString, monitor);
        if (xml != null) {
            xml.mark(500000);
            xml = new NonClosingInputStream(xml);
            ((NonClosingInputStream) xml).setCloseBehavior(CloseBehavior.RESET);
        }
        return xml;
    } catch (Exception e) {
        if (outException != null) {
            outException[0] = e;
        }
    }

    return null;
}
 
Example 5
Project: okwallet   File: WalletUtils.java   View Source Code Vote up 6 votes
public static Wallet restoreWalletFromProtobufOrBase58(final InputStream is,
        final NetworkParameters expectedNetworkParameters) throws IOException {
    is.mark((int) Constants.BACKUP_MAX_CHARS);

    try {
        return restoreWalletFromProtobuf(is, expectedNetworkParameters);
    } catch (final IOException x) {
        try {
            is.reset();
            return restorePrivateKeysFromBase58(is, expectedNetworkParameters);
        } catch (final IOException x2) {
            throw new IOException(
                    "cannot read protobuf (" + x.getMessage() + ") or base58 (" + x2.getMessage() + ")", x);
        }
    }
}
 
Example 6
Project: rtmp-rtsp-stream-client-java   File: AmfObject.java   View Source Code Vote up 5 votes
@Override
public void readFrom(InputStream in) throws IOException {
    // Skip data type byte (we assume it's already read)       
    size = 1;
    InputStream markInputStream = in.markSupported() ? in : new BufferedInputStream(in);

    while (true) {
        // Look for the 3-byte object end marker [0x00 0x00 0x09]
        markInputStream.mark(3);
        byte[] endMarker = new byte[3];
        markInputStream.read(endMarker);

        if (endMarker[0] == OBJECT_END_MARKER[0] && endMarker[1] == OBJECT_END_MARKER[1] && endMarker[2] == OBJECT_END_MARKER[2]) {
            // End marker found
            size += 3;
            return;
        } else {
            // End marker not found; reset the stream to the marked position and read an AMF property
            markInputStream.reset();
            // Read the property key...
            String key = AmfString.readStringFrom(in, true);
            size += AmfString.sizeOf(key, true);
            // ...and the property value
            AmfData value = AmfDecoder.readFrom(markInputStream);
            size += value.getSize();
            properties.put(key, value);
        }
    }
}
 
Example 7
Project: Cubes_2   File: AssetFinder.java   View Source Code Vote up 5 votes
private static InputStream getInputStream(URL jar) throws IOException {
	// to fix offset caused by launch4j
	try {
		InputStream is = jar.openStream();
		Log.debug("Scanning for jar...");
		long offset = 0;
		boolean found = false;
		try {
			while (true) {
				if (getUnsignedInt(is) == 0x04034b50L) {
					found = true;
					break;
				}
				offset += 4;
			}
		} catch (IOException ignored) {
		}
		is.close();

		InputStream finalIS = jar.openStream();
		if (!found) {
			Log.debug("Failed to find start");
		} else {
			Log.debug("Skipping " + offset + " bytes until start of jar [" + finalIS.skip(offset) + "]");
			if (finalIS.markSupported())
				finalIS.mark(Integer.MAX_VALUE);
		}
		return finalIS;
	} catch (SSLException ssle) {
		Log.error("SSL Exception", ssle);
	}
}
 
Example 8
Project: OpenJSharp   File: DLSSoundbankReader.java   View Source Code Vote up 5 votes
public Soundbank getSoundbank(InputStream stream)
        throws InvalidMidiDataException, IOException {
    try {
        stream.mark(512);
        return new DLSSoundbank(stream);
    } catch (RIFFInvalidFormatException e) {
        stream.reset();
        return null;
    }
}
 
Example 9
Project: openjdk-jdk10   File: SF2SoundbankReader.java   View Source Code Vote up 5 votes
@Override
public Soundbank getSoundbank(InputStream stream)
        throws InvalidMidiDataException, IOException {
    try {
        stream.mark(512);
        return new SF2Soundbank(stream);
    } catch (RIFFInvalidFormatException e) {
        stream.reset();
        return null;
    }
}
 
Example 10
Project: libRtmp   File: AmfObject.java   View Source Code Vote up 5 votes
@Override
public void readFrom(InputStream in) throws IOException {
    // Skip data type byte (we assume it's already read)
    size = 1;
    InputStream markInputStream = in.markSupported() ? in : new BufferedInputStream(in);

    while (true) {
        // Look for the 3-byte object end marker [0x00 0x00 0x09]
        markInputStream.mark(3);
        byte[] endMarker = new byte[3];
        markInputStream.read(endMarker);

        if (endMarker[0] == OBJECT_END_MARKER[0] && endMarker[1] == OBJECT_END_MARKER[1] && endMarker[2] == OBJECT_END_MARKER[2]) {
            // End marker found
            size += 3;
            return;
        } else {
            // End marker not found; reset the stream to the marked position and read an AMF property
            markInputStream.reset();
            // Read the property key...
            String key = AmfString.readStringFrom(in, true);
            size += AmfString.sizeOf(key, true);
            // ...and the property value
            AmfData value = AmfDecoder.readFrom(markInputStream);
            size += value.getSize();
            properties.put(key, value);
        }
    }
}
 
Example 11
Project: fdk-java   File: ReadOnceInputEvent.java   View Source Code Vote up 5 votes
public ReadOnceInputEvent(String appName, String route, String requestUrl, String method, InputStream body, Headers headers, QueryParameters parameters) {
    this.appName = Objects.requireNonNull(appName);
    this.route = Objects.requireNonNull(route);
    this.requestUrl = Objects.requireNonNull(requestUrl);
    this.method = Objects.requireNonNull(method).toUpperCase();
    this.body = new BufferedInputStream(Objects.requireNonNull(body));
    this.headers = Objects.requireNonNull(headers);
    this.queryParameters = Objects.requireNonNull(parameters);
    body.mark(Integer.MAX_VALUE);
}
 
Example 12
Project: openjdk-jdk10   File: DLSSoundbankReader.java   View Source Code Vote up 5 votes
@Override
public Soundbank getSoundbank(InputStream stream)
        throws InvalidMidiDataException, IOException {
    try {
        stream.mark(512);
        return new DLSSoundbank(stream);
    } catch (RIFFInvalidFormatException e) {
        stream.reset();
        return null;
    }
}
 
Example 13
Project: elasticsearch_my   File: XContentFactory.java   View Source Code Vote up 5 votes
/**
 * Guesses the content type based on the provided input stream without consuming it.
 *
 * @deprecated the content type should not be guessed except for few cases where we effectively don't know the content type.
 * The REST layer should move to reading the Content-Type header instead. There are other places where auto-detection may be needed.
 * This method is deprecated to prevent usages of it from spreading further without specific reasons.
 */
@Deprecated
public static XContentType xContentType(InputStream si) throws IOException {
    if (si.markSupported() == false) {
        throw new IllegalArgumentException("Cannot guess the xcontent type without mark/reset support on " + si.getClass());
    }
    si.mark(GUESS_HEADER_LENGTH);
    try {
        final byte[] firstBytes = new byte[GUESS_HEADER_LENGTH];
        final int read = Streams.readFully(si, firstBytes);
        return xContentType(new BytesArray(firstBytes, 0, read));
    } finally {
        si.reset();
    }
}
 
Example 14
Project: alfresco-repository   File: TikaOfficeDetectParser.java   View Source Code Vote up 5 votes
public void parse(InputStream stream,
      ContentHandler handler, Metadata metadata,
      ParseContext parseContext) throws IOException, SAXException,
      TikaException 
{
   byte[] initial4 = new byte[4];
   InputStream wrapped;
   // Preserve TikaInputStreams as TikaInputStreams as they require less memory to process
   if (stream.markSupported())
   {
      stream.mark(initial4.length);
      IOUtils.readFully(stream, initial4);
      stream.reset();
      wrapped = stream;
   }
   else
   {
      PushbackInputStream inp = new PushbackInputStream(stream, 4);
      IOUtils.readFully(inp, initial4);
      inp.unread(initial4);
      wrapped = inp;
   }
   
   // Which is it?
   if(initial4[0] == POIFSConstants.OOXML_FILE_HEADER[0] &&
      initial4[1] == POIFSConstants.OOXML_FILE_HEADER[1] &&
      initial4[2] == POIFSConstants.OOXML_FILE_HEADER[2] &&
      initial4[3] == POIFSConstants.OOXML_FILE_HEADER[3])
   {
      ooxmlParser.parse(wrapped, handler, metadata, parseContext);
   }
   else
   {
      ole2Parser.parse(wrapped, handler, metadata, parseContext);
   }
}
 
Example 15
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 16
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 17
Project: microbit   File: HexInputStream.java   View Source Code Vote up 4 votes
private int calculateBinSize(final int mbrSize) 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 >= mbrSize) // we must skip all data from below last MBR address (default 0x1000) as those are the MBR. The Soft Device starts at the end of MBR (0x1000), the app and bootloader farther more
					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: 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 19
Project: OpenVertretung   File: PreparedStatement.java   View Source Code Vote up 4 votes
private final byte[] streamToBytes(InputStream in, boolean escape, int streamLength, boolean useLength) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        in.mark(Integer.MAX_VALUE); // we may need to read this same stream several times, so we need to reset it at the end.
        try {
            if (this.streamConvertBuf == null) {
                this.streamConvertBuf = new byte[4096];
            }
            if (streamLength == -1) {
                useLength = false;
            }

            ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();

            int bc = -1;

            if (useLength) {
                bc = readblock(in, this.streamConvertBuf, streamLength);
            } else {
                bc = readblock(in, this.streamConvertBuf);
            }

            int lengthLeftToRead = streamLength - bc;

            if (escape) {
                if (this.connection.versionMeetsMinimum(4, 1, 0)) {
                    bytesOut.write('_');
                    bytesOut.write('b');
                    bytesOut.write('i');
                    bytesOut.write('n');
                    bytesOut.write('a');
                    bytesOut.write('r');
                    bytesOut.write('y');
                }

                bytesOut.write('\'');
            }

            while (bc > 0) {
                if (escape) {
                    escapeblockFast(this.streamConvertBuf, bytesOut, bc);
                } else {
                    bytesOut.write(this.streamConvertBuf, 0, bc);
                }

                if (useLength) {
                    bc = readblock(in, this.streamConvertBuf, lengthLeftToRead);

                    if (bc > 0) {
                        lengthLeftToRead -= bc;
                    }
                } else {
                    bc = readblock(in, this.streamConvertBuf);
                }
            }

            if (escape) {
                bytesOut.write('\'');
            }

            return bytesOut.toByteArray();
        } finally {
            try {
                in.reset();
            } catch (IOException e) {
            }
            if (this.connection.getAutoClosePStmtStreams()) {
                try {
                    in.close();
                } catch (IOException ioEx) {
                }

                in = null;
            }
        }
    }
}
 
Example 20
Project: openjdk-jdk10   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();
}