Example usage for java.io InputStream mark

List of usage examples for java.io InputStream mark

Introduction

In this page you can find the example usage for java.io InputStream mark.

Prototype

public synchronized void mark(int readlimit) 

Source Link

Document

Marks the current position in this input stream.

Usage

From source file:com.akalizakeza.apps.ishusho.activity.NewPostUploadTaskFragment.java

public Bitmap decodeSampledBitmapFromUri(Uri fileUri, int reqWidth, int reqHeight) throws IOException {
    InputStream stream = new BufferedInputStream(
            mApplicationContext.getContentResolver().openInputStream(fileUri));
    stream.mark(stream.available());
    BitmapFactory.Options options = new BitmapFactory.Options();
    // First decode with inJustDecodeBounds=true to check dimensions
    options.inJustDecodeBounds = true;//from   w w w  .j  a v a2 s . co  m
    BitmapFactory.decodeStream(stream, null, options);
    stream.reset();
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    BitmapFactory.decodeStream(stream, null, options);
    // Decode bitmap with inSampleSize set
    stream.reset();
    return BitmapFactory.decodeStream(stream, null, options);
}

From source file:cn.ctyun.amazonaws.services.s3.transfer.internal.UploadCallable.java

/**
 * Uploads all parts in the request in serial in this thread, then completes
 * the upload and returns the result./*www . jav  a 2s. co m*/
 */
private UploadResult uploadPartsInSeries(UploadPartRequestFactory requestFactory) {

    final List<PartETag> partETags = new ArrayList<PartETag>();

    while (requestFactory.hasMoreRequests()) {
        if (threadPool.isShutdown())
            throw new CancellationException("TransferManager has been shutdown");
        UploadPartRequest uploadPartRequest = requestFactory.getNextUploadPartRequest();
        // Mark the stream in case we need to reset it
        InputStream inputStream = uploadPartRequest.getInputStream();
        if (inputStream != null && inputStream.markSupported()) {
            if (uploadPartRequest.getPartSize() >= Integer.MAX_VALUE) {
                inputStream.mark(Integer.MAX_VALUE);
            } else {
                inputStream.mark((int) uploadPartRequest.getPartSize());
            }
        }
        partETags.add(s3.uploadPart(uploadPartRequest).getPartETag());
    }

    CompleteMultipartUploadResult completeMultipartUploadResult = s3
            .completeMultipartUpload(new CompleteMultipartUploadRequest(putObjectRequest.getBucketName(),
                    putObjectRequest.getKey(), multipartUploadId, partETags));

    fireProgressEvent(ProgressEvent.COMPLETED_EVENT_CODE);

    UploadResult uploadResult = new UploadResult();
    uploadResult.setBucketName(completeMultipartUploadResult.getBucketName());
    uploadResult.setKey(completeMultipartUploadResult.getKey());
    uploadResult.setETag(completeMultipartUploadResult.getETag());
    uploadResult.setVersionId(completeMultipartUploadResult.getVersionId());
    return uploadResult;
}

From source file:com.examples.with.different.packagename.coverage.BOMInputStreamTest.java

public void testMarkResetBeforeReadWithBOM() throws Exception {
    byte[] data = new byte[] { 'A', 'B', 'C', 'D' };
    InputStream in = new BOMInputStream(createDataStream(data, true));
    assertTrue(in.markSupported());//from  w ww  . j av  a2  s  .  c  om

    in.mark(10);

    in.read();
    in.read();
    in.reset();
    assertEquals('A', in.read());
}

From source file:com.examples.with.different.packagename.coverage.BOMInputStreamTest.java

public void testMarkResetBeforeReadWithoutBOM() throws Exception {
    byte[] data = new byte[] { 'A', 'B', 'C', 'D' };
    InputStream in = new BOMInputStream(createDataStream(data, false));
    assertTrue(in.markSupported());//from  ww  w  . ja  v a  2s. c o m

    in.mark(10);

    in.read();
    in.read();
    in.reset();
    assertEquals('A', in.read());
}

From source file:com.sina.cloudstorage.services.scs.transfer.internal.UploadCallable.java

/**
 * Uploads all parts in the request in serial in this thread, then completes
 * the upload and returns the result.//www.  j a  v a  2  s  .  c  om
 */
private UploadResult uploadPartsInSeries(UploadPartRequestFactory requestFactory) {

    final List<PartETag> partETags = new ArrayList<PartETag>();

    while (requestFactory.hasMoreRequests()) {
        if (threadPool.isShutdown())
            throw new CancellationException("TransferManager has been shutdown");
        UploadPartRequest uploadPartRequest = requestFactory.getNextUploadPartRequest();
        // Mark the stream in case we need to reset it
        InputStream inputStream = uploadPartRequest.getInputStream();
        if (inputStream != null && inputStream.markSupported()) {
            if (uploadPartRequest.getPartSize() >= Integer.MAX_VALUE) {
                inputStream.mark(Integer.MAX_VALUE);
            } else {
                inputStream.mark((int) uploadPartRequest.getPartSize());
            }
        }
        partETags.add(s3.uploadPart(uploadPartRequest).getPartETag());
    }

    //        CompleteMultipartUploadResult completeMultipartUploadResult = s3
    //                .completeMultipartUpload(new CompleteMultipartUploadRequest(putObjectRequest.getBucketName(),
    //                        putObjectRequest.getKey(), multipartUploadId, partETags));
    //        UploadResult uploadResult = new UploadResult();
    //        uploadResult.setBucketName(completeMultipartUploadResult.getBucketName());
    //        uploadResult.setKey(completeMultipartUploadResult.getKey());
    //        uploadResult.setETag(completeMultipartUploadResult.getETag());
    //        uploadResult.setVersionId(completeMultipartUploadResult.getVersionId());
    //        return uploadResult;

    s3.completeMultipartUpload(new CompleteMultipartUploadRequest(putObjectRequest.getBucketName(),
            putObjectRequest.getKey(), multipartUploadId, partETags));

    UploadResult uploadResult = new UploadResult();
    //        uploadResult.setBucketName(completeMultipartUploadResult.getBucketName());
    //        uploadResult.setKey(completeMultipartUploadResult.getKey());
    //        uploadResult.setETag(completeMultipartUploadResult.getETag());
    //        uploadResult.setVersionId(completeMultipartUploadResult.getVersionId());
    return uploadResult;
}

From source file:com.smartitengineering.event.hub.common.EventJsonProvider.java

public String getJsonString(Event event) {
    if (event == null) {
        return "";
    }//from   w  w w .  j  av  a  2 s . c o m
    Map<String, String> jsonMap = new LinkedHashMap<String, String>();
    if (StringUtils.isNotBlank(event.getPlaceholderId())) {
        jsonMap.put(PLACEHOLDER_ID, event.getPlaceholderId());
    }
    if (StringUtils.isNotBlank(event.getUniversallyUniqueID())) {
        jsonMap.put(UNIVERSAL_UNIQUE_ID, event.getUniversallyUniqueID());
    }
    if (StringUtils.isNotBlank(event.getEventContent().getContentType())) {
        jsonMap.put(CONTENT_TYPE, event.getEventContent().getContentType());
    }
    InputStream contentStream = event.getEventContent().getContent();
    if (contentStream != null) {
        String contentAsString = "";
        if (contentCache.containsKey(event)) {
            contentAsString = contentCache.get(event);
        } else {
            try {
                if (contentStream.markSupported()) {
                    contentStream.mark(Integer.MAX_VALUE);
                }
                contentAsString = IOUtils.toString(contentStream);
                contentCache.put(event, contentAsString);
                if (contentStream.markSupported()) {
                    contentStream.reset();
                }
            } catch (IOException ex) {
            }
        }
        jsonMap.put(CONTENT_AS_STRING, contentAsString);
    }
    Date creationDate = event.getCreationDate();
    if (creationDate != null) {
        jsonMap.put(CREATION_DATE, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(creationDate));
    }
    try {
        return mapper.writeValueAsString(jsonMap);
    } catch (Exception ex) {
        return "";
    }
}

From source file:com.examples.with.different.packagename.coverage.BOMInputStreamTest.java

public void testMarkResetAfterReadWithBOM() throws Exception {
    byte[] data = new byte[] { 'A', 'B', 'C', 'D' };
    InputStream in = new BOMInputStream(createDataStream(data, true));
    assertTrue(in.markSupported());/*from w  w w. j a v a 2  s .c o  m*/

    in.read();
    in.mark(10);

    in.read();
    in.read();
    in.reset();
    assertEquals('B', in.read());
}

From source file:com.aliyun.oss.common.comm.ServiceClient.java

private ResponseMessage sendRequestImpl(RequestMessage request, ExecutionContext context)
        throws ClientException, ServiceException {

    RetryStrategy retryStrategy = context.getRetryStrategy() != null ? context.getRetryStrategy()
            : this.getDefaultRetryStrategy();

    // Sign the request if a signer provided.
    if (context.getSigner() != null && !request.isUseUrlSignature()) {
        context.getSigner().sign(request);
    }//from  w  w  w  . jav  a2  s . c o  m

    InputStream requestContent = request.getContent();
    if (requestContent != null && requestContent.markSupported()) {
        requestContent.mark(OSSConstants.DEFAULT_STREAM_BUFFER_SIZE);
    }

    int retries = 0;
    ResponseMessage response = null;

    while (true) {
        try {
            if (retries > 0) {
                pause(retries, retryStrategy);
                if (requestContent != null && requestContent.markSupported()) {
                    try {
                        requestContent.reset();
                    } catch (IOException ex) {
                        logException("Failed to reset the request input stream: ", ex);
                        throw new ClientException("Failed to reset the request input stream: ", ex);
                    }
                }
            }

            /* The key four steps to send HTTP requests and receive HTTP responses. */

            // Step1. Build HTTP request with specified request parameters and context.
            Request httpRequest = buildRequest(request, context);

            // Step 2. Postprocess HTTP request.
            handleRequest(httpRequest, context.getResquestHandlers());

            // Step 3. Send HTTP request to OSS.
            response = sendRequestCore(httpRequest, context);

            // Step 4. Preprocess HTTP response.
            handleResponse(response, context.getResponseHandlers());

            return response;
        } catch (ServiceException sex) {
            logException("[Server]Unable to execute HTTP request: ", sex);

            // Notice that the response should not be closed in the
            // finally block because if the request is successful,
            // the response should be returned to the callers.
            closeResponseSilently(response);

            if (!shouldRetry(sex, request, response, retries, retryStrategy)) {
                throw sex;
            }
        } catch (ClientException cex) {
            logException("[Client]Unable to execute HTTP request: ", cex);

            closeResponseSilently(response);

            if (!shouldRetry(cex, request, response, retries, retryStrategy)) {
                throw cex;
            }
        } catch (Exception ex) {
            logException("[Unknown]Unable to execute HTTP request: ", ex);

            closeResponseSilently(response);

            throw new ClientException(
                    COMMON_RESOURCE_MANAGER.getFormattedString("ConnectionError", ex.getMessage()), ex);
        } finally {
            retries++;
        }
    }
}

From source file:com.examples.with.different.packagename.coverage.BOMInputStreamTest.java

public void testMarkResetAfterReadWithoutBOM() throws Exception {
    byte[] data = new byte[] { 'A', 'B', 'C', 'D' };
    InputStream in = new BOMInputStream(createDataStream(data, false));
    assertTrue(in.markSupported());//  w w  w  .  j  a v a  2 s  .  c om

    in.read();
    in.mark(10);

    in.read();
    in.read();
    in.reset();
    assertEquals('B', in.read());
}

From source file:cn.ctyun.amazonaws.auth.AbstractAWSSigner.java

/**
 * 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/*w  ww . j a v a 2 s  .  c  o m*/
 *            The request
 * @return The request's payload contents as binary data, not including any
 *         form encoding of query string params.
 */
protected byte[] getBinaryRequestPayloadWithoutQueryParams(Request<?> request) {
    InputStream content = getBinaryRequestPayloadStreamWithoutQueryParams(request);

    try {
        content.mark(-1);
        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 AmazonClientException("Unable to read request payload to sign request: " + e.getMessage(), e);
    }
}