下面列出了java.io.InputStream#markSupported ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Reset the input stream of the request before a retry.
*
* @param request Request containing input stream to reset
* @param retriedException
* @throws ResetException If Input Stream can't be reset which means the request can't be
* retried
*/
private void resetRequestInputStream(final Request<?> request, SdkBaseException retriedException)
throws ResetException {
InputStream requestInputStream = request.getContent();
if (requestInputStream != null) {
if (requestInputStream.markSupported()) {
try {
requestInputStream.reset();
} catch (IOException ex) {
ResetException resetException = new ResetException(
"The request to the service failed with a retryable reason, but resetting the request input " +
"stream has failed. See exception.getExtraInfo or debug-level logging for the original failure " +
"that caused this retry.",
ex);
resetException.setExtraInfo(retriedException.getMessage());
throw resetException;
}
}
}
}
public EmptyBodyCheckingHttpInputMessage(HttpInputMessage inputMessage) throws IOException {
this.headers = inputMessage.getHeaders();
InputStream inputStream = inputMessage.getBody();
if (inputStream.markSupported()) {
inputStream.mark(1);
this.body = (inputStream.read() != -1 ? inputStream : null);
inputStream.reset();
}
else {
PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream);
int b = pushbackInputStream.read();
if (b == -1) {
this.body = null;
}
else {
this.body = pushbackInputStream;
pushbackInputStream.unread(b);
}
}
}
/**
* Reads up to MAX_HEADER_LENGTH bytes from is InputStream. If mark is supported by is, it is
* used to restore content of the stream after appropriate amount of data is read.
* Read bytes are stored in imageHeaderBytes, which should be capable of storing
* MAX_HEADER_LENGTH bytes.
* @param is
* @param imageHeaderBytes
* @return number of bytes read from is
* @throws IOException
*/
private static int readHeaderFromStream(
final InputStream is,
final byte[] imageHeaderBytes)
throws IOException {
Preconditions.checkNotNull(is);
Preconditions.checkNotNull(imageHeaderBytes);
Preconditions.checkArgument(imageHeaderBytes.length >= MAX_HEADER_LENGTH);
// If mark is supported by the stream, use it to let the owner of the stream re-read the same
// data. Otherwise, just consume some data.
if (is.markSupported()) {
try {
is.mark(MAX_HEADER_LENGTH);
return ByteStreams.read(is, imageHeaderBytes, 0, MAX_HEADER_LENGTH);
} finally {
is.reset();
}
} else {
return ByteStreams.read(is, imageHeaderBytes, 0, MAX_HEADER_LENGTH);
}
}
/**
* Reads up to maxHeaderLength bytes from is InputStream. If mark is supported by is, it is used
* to restore content of the stream after appropriate amount of data is read. Read bytes are
* stored in imageHeaderBytes, which should be capable of storing maxHeaderLength bytes.
*
* @param maxHeaderLength the maximum header length
* @param is
* @param imageHeaderBytes
* @return number of bytes read from is
* @throws IOException
*/
private static int readHeaderFromStream(
int maxHeaderLength, final InputStream is, final byte[] imageHeaderBytes) throws IOException {
Preconditions.checkNotNull(is);
Preconditions.checkNotNull(imageHeaderBytes);
Preconditions.checkArgument(imageHeaderBytes.length >= maxHeaderLength);
// If mark is supported by the stream, use it to let the owner of the stream re-read the same
// data. Otherwise, just consume some data.
if (is.markSupported()) {
try {
is.mark(maxHeaderLength);
return ByteStreams.read(is, imageHeaderBytes, 0, maxHeaderLength);
} finally {
is.reset();
}
} else {
return ByteStreams.read(is, imageHeaderBytes, 0, maxHeaderLength);
}
}
/**
* 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.
*/
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);
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;
}
protected InputStream resetStream(InputStream imageStream, String url) throws IOException
{
if (imageStream.markSupported())
{
try
{
imageStream.reset();
return imageStream;
} catch (IOException ignored)
{
}
}
IoUtils.closeSilently(imageStream);
return getImageStream(url);
}
private void parseWatchfaceFile(InputStream fwFileStream) throws Exception {
if (d)
UserError.Log.d(TAG, "Reading header");
BufferedInputStream stream = new BufferedInputStream(fwFileStream);
header = Header.readFrom(stream);
if (d) {
UserError.Log.d(TAG, "Header was read:");
UserError.Log.d(TAG, String.format("Signature: %s, Unknown param: %d, ParametersSize: %d isValid: %s", header.getSignature(), header.getUnknown(), header.getParametersSize(), header.isValid()));
}
if (!header.isValid())
throw new Exception("Wrong watchface format");
if (d)
UserError.Log.d(TAG, "Reading parameter offsets...");
byte[] bytes = new byte[header.getParametersSize()];
stream.read(bytes, 0, bytes.length);
InputStream parameterStream = new ByteArrayInputStream(bytes);
mainParam = Parameter.readFrom(parameterStream, 0);
if (d)
UserError.Log.d(TAG, "Parameters descriptor was read");
parametersTableLength = (int) mainParam.getChildren().get(0).getValue();
int imagesCount = (int) mainParam.getChildren().get(1).getValue();
if (d)
UserError.Log.d(TAG, "parametersTableLength: " + parametersTableLength + ", imagesCount: " + imagesCount);
bytes = new byte[parametersTableLength];
stream.read(bytes, 0, bytes.length);
if (d)
UserError.Log.d(TAG, "Reading images offsets...");
bytes = new byte[imagesCount * 4];
stream.read(bytes, 0, bytes.length);
ByteBuffer b = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
imageOffsets = new ArrayList<>();
while (b.hasRemaining()) {
imageOffsets.add(b.getInt());
}
if (d)
UserError.Log.d(TAG, "Image offsets were read");
if (fwFileStream.markSupported())
fwFileStream.reset();
}
public Document loadSwingDocument(InputStream in) throws IOException, BadLocationException {
BaseDocument sd = new BaseDocument(true, "text/xml"); //NOI18N
String encoding = in.markSupported() ? EncodingUtil.detectEncoding(in) : null;
Reader r = encoding == null ? new InputStreamReader(in) : new InputStreamReader(in, encoding);
sd.read(r, 0);
return sd;
}
public static DexBackedOdexFile fromInputStream(@Nonnull Opcodes opcodes,
@Nonnull InputStream is) throws IOException {
if (!is.markSupported()) {
throw new IllegalArgumentException("InputStream must support mark");
}
is.mark(8);
byte[] partialHeader = new byte[8];
try {
ByteStreams.readFully(is, partialHeader);
} catch (EOFException ex) {
throw new NotADexFile("File is too short");
} finally {
is.reset();
}
verifyMagic(partialHeader);
is.reset();
byte[] odexBuf = new byte[OdexHeaderItem.ITEM_SIZE];
ByteStreams.readFully(is, odexBuf);
int dexOffset = OdexHeaderItem.getDexOffset(odexBuf);
if (dexOffset > OdexHeaderItem.ITEM_SIZE) {
ByteStreams.skipFully(is, dexOffset - OdexHeaderItem.ITEM_SIZE);
}
byte[] dexBuf = ByteStreams.toByteArray(is);
return new DexBackedOdexFile(opcodes, odexBuf, dexBuf);
}
private boolean reset(InputStream in) throws IOException {
if (in.markSupported()) {
in.reset();
return true;
}
if (in instanceof FileInputStream) {
// FileInputStream does not support reset().
((FileInputStream) in).getChannel().position(0);
return true;
}
return false;
}
protected InputStream getBinaryRequestPayloadStreamWithoutQueryParams(BasicGalaxyRequest basicgalaxyrequest)
{
InputStream inputstream;
try
{
inputstream = basicgalaxyrequest.getContent();
}
catch (Exception exception)
{
throw new GalaxyClientException(ReturnCode.SIGNATURE_FAILED, (new StringBuilder()).append("Unable to read request payload to sign request: ").append(exception.getMessage()).toString(), exception);
}
if (inputstream != null)
{
break MISSING_BLOCK_LABEL_20;
}
return new ByteArrayInputStream(new byte[0]);
if (inputstream instanceof StringInputStream)
{
break MISSING_BLOCK_LABEL_91;
}
if (!inputstream.markSupported())
{
throw new GalaxyClientException(ReturnCode.SIGNATURE_FAILED, "Unable to read request payload to sign request.");
}
InputStream inputstream1 = basicgalaxyrequest.getContent();
inputstream = inputstream1;
return inputstream;
}
/**
* Used to perform a last reset on the content input stream (if mark-supported); this is so
* that, for backward compatibility reason, any "blind" retry (ie without calling reset) by
* user of this library with the same input stream (such as ByteArrayInputStream) could
* still succeed.
*
* @param t the failure
* @return the failure as given
*/
private <T extends Throwable> T lastReset(final T t) {
try {
InputStream content = request.getContent();
if (content != null) {
if (content.markSupported()) {
content.reset();
}
}
} catch (Exception ex) {
log.debug("FYI: failed to reset content inputstream before throwing up", ex);
}
return t;
}
public static PrivateKey loadPrivateKeyFromPemStream(InputStream inStream) throws KeyManagementException {
PrivateKey privateKey = null;
if (inStream == null) {
return privateKey;
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inStream))) {
if (inStream.markSupported()) {
inStream.reset();
}
StringBuilder sb = new StringBuilder();
String currentLine = null;
// Jump to the first line after -----BEGIN [RSA] PRIVATE KEY-----
while (!reader.readLine().startsWith("-----BEGIN")) {
reader.readLine();
}
// Stop (and skip) at the last line that has, say, -----END [RSA] PRIVATE KEY-----
while ((currentLine = reader.readLine()) != null && !currentLine.startsWith("-----END")) {
sb.append(currentLine);
}
KeyFactory kf = KeyFactory.getInstance("RSA");
KeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(sb.toString()));
privateKey = kf.generatePrivate(keySpec);
} catch (GeneralSecurityException | IOException e) {
throw new KeyManagementException("Private key loading error", e);
}
return privateKey;
}
/**
* Creates drawable from InputStream.
* InputStream must support marking, IllegalArgumentException will be thrown otherwise.
*
* @param stream stream to read from
* @throws IOException when opening failed
* @throws IllegalArgumentException if stream does not support marking
* @throws NullPointerException if stream is null
*/
public GifDrawable(InputStream stream) throws IOException {
if (stream == null)
throw new NullPointerException("Source is null");
if (!stream.markSupported())
throw new IllegalArgumentException("InputStream does not support marking");
mGifInfoPtr = openStream(mMetaData, stream, false);
mColors = new int[mMetaData[0] * mMetaData[1]];
mInputSourceLength = -1L;
}
public static DexBackedOdexFile fromInputStream(@Nonnull Opcodes opcodes,
@Nonnull InputStream is) throws IOException {
if (!is.markSupported()) {
throw new IllegalArgumentException("InputStream must support mark");
}
is.mark(8);
byte[] partialHeader = new byte[8];
try {
ByteStreams.readFully(is, partialHeader);
} catch (EOFException ex) {
throw new NotADexFile("File is too short");
} finally {
is.reset();
}
verifyMagic(partialHeader);
is.reset();
byte[] odexBuf = new byte[OdexHeaderItem.ITEM_SIZE];
ByteStreams.readFully(is, odexBuf);
int dexOffset = OdexHeaderItem.getDexOffset(odexBuf);
if (dexOffset > OdexHeaderItem.ITEM_SIZE) {
ByteStreams.skipFully(is, dexOffset - OdexHeaderItem.ITEM_SIZE);
}
byte[] dexBuf = ByteStreams.toByteArray(is);
return new DexBackedOdexFile(opcodes, odexBuf, dexBuf);
}
@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]) {
L.d("readFrom(): 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);
}
}
}
public Element parse(InputStream stream) throws FHIRFormatError, DefinitionException, FHIRException, IOException {
Document doc = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// xxe protection
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
factory.setNamespaceAware(true);
if (policy == ValidationPolicy.EVERYTHING) {
// The SAX interface appears to not work when reporting the correct version/encoding.
// if we can, we'll inspect the header/encoding ourselves
if (stream.markSupported()) {
stream.mark(1024);
version = checkHeader(stream);
stream.reset();
}
// use a slower parser that keeps location data
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer nullTransformer = transformerFactory.newTransformer();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
doc = docBuilder.newDocument();
DOMResult domResult = new DOMResult(doc);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(false);
// xxe protection
spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
// xxe protection
xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
XmlLocationAnnotator locationAnnotator = new XmlLocationAnnotator(xmlReader, doc);
InputSource inputSource = new InputSource(stream);
SAXSource saxSource = new SAXSource(locationAnnotator, inputSource);
nullTransformer.transform(saxSource, domResult);
} else {
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(stream);
}
} catch (Exception e) {
logError(0, 0, "(syntax)", IssueType.INVALID, e.getMessage(), IssueSeverity.FATAL);
doc = null;
}
if (doc == null)
return null;
else
return parse(doc);
}
/**
* {@inheritDoc}
* <p>
* The input stream is checked to ensure that it supports marks, after which
* a buffer is extracted, leaving the stream in its original state.
*/
public final Charset detectCharset(InputStream is)
{
// Only support marking streams
if (!is.markSupported())
{
throw new IllegalArgumentException("The InputStream must support marks. Wrap the stream in a BufferedInputStream.");
}
try
{
int bufferSize = getBufferSize();
if (bufferSize < 0)
{
throw new RuntimeException("The required buffer size may not be negative: " + bufferSize);
}
// Mark the stream for just a few more than we actually will need
is.mark(bufferSize);
// Create a buffer to hold the data
byte[] buffer = new byte[bufferSize];
// Fill it
int read = is.read(buffer);
// Create an appropriately sized buffer
if (read > -1 && read < buffer.length)
{
byte[] copyBuffer = new byte[read];
System.arraycopy(buffer, 0, copyBuffer, 0, read);
buffer = copyBuffer;
}
// Detect
return detectCharset(buffer);
}
catch (IOException e)
{
// Attempt a reset
throw new AlfrescoRuntimeException("IOException while attempting to detect charset encoding.", e);
}
finally
{
try { is.reset(); } catch (Throwable ee) {}
}
}
private static InputStream wrappedStream(InputStream in) {
return in.markSupported() ? in : new BufferedInputStream(in);
}
static GifInfoHandle openMarkableInputStream(InputStream stream, boolean justDecodeMetaData) throws GifIOException {
if (!stream.markSupported()) {
throw new IllegalArgumentException("InputStream does not support marking");
}
return openStream(stream, justDecodeMetaData);
}