Example usage for java.io InputStream markSupported

List of usage examples for java.io InputStream markSupported

Introduction

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

Prototype

public boolean markSupported() 

Source Link

Document

Tests if this input stream supports the mark and reset methods.

Usage

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

public String getJsonString(Event event) {
    if (event == null) {
        return "";
    }//  www  . jav a2 s.  c om
    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.amazonaws.mobileconnectors.s3.transfermanager.internal.UploadCallable.java

/**
 * Uploads all parts in the request in serial in this thread, then completes
 * the upload and returns the result./*  w  w  w.  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;
}

From source file:org.bndtools.rt.repository.server.RepositoryResourceComponent.java

@POST
@Path("bundles")
@Consumes({ MediaType.APPLICATION_OCTET_STREAM, ProvisioningService.MIME_BUNDLE })
public Response uploadBundle(@Context UriInfo uriInfo, InputStream stream) throws Exception {
    if (!repo.canWrite())
        return Response.status(Status.BAD_REQUEST).entity("Repository is not writeable").build();

    InputStream bufferedStream = stream.markSupported() ? stream : new BufferedInputStream(stream);
    Manifest manifest = readManifest(bufferedStream);

    Attributes mainAttribs = manifest.getMainAttributes();
    String bsn = mainAttribs.getValue(Constants.BUNDLE_SYMBOLICNAME);
    if (bsn == null)
        return Response.status(Status.BAD_REQUEST).entity("not a bundle").build();
    String versionStr = mainAttribs.getValue(Constants.BUNDLE_VERSION);
    Version version = versionStr != null ? new Version(versionStr) : Version.emptyVersion;

    URI bundleLocation = uriInfo.getAbsolutePathBuilder().path("{bsn}/{version}").build(bsn, version);

    repo.put(bufferedStream, RepositoryPlugin.DEFAULTOPTIONS);
    return Response.created(bundleLocation).build();
}

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());

    in.mark(10);/* ww  w .  j a  va  2  s  . co  m*/

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

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());

    in.read();//from w w  w . jav  a  2 s.  c  o m
    in.mark(10);

    in.read();
    in.read();
    in.reset();
    assertEquals('B', 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());

    in.mark(10);/*from w w  w  .ja va  2 s .  com*/

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

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());

    in.read();/*from   w ww  .ja  v a2  s.c o m*/
    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);
    }/*w ww.ja  v  a  2 s .  co 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:org.dataconservancy.packaging.impl.OpenPackageService.java

/**
 * Extract contents of an archive./*w  w  w  .  j  av a2 s  . c o m*/
 *
 * @param dest_dir Destination to write archive content.
 * @param is Archive file.
 * @return Name of package base directory in dest_dir
 * @throws ArchiveException if there is an error creating the ArchiveInputStream
 * @throws IOException if there is more than one package root
 */
private String extract(final File dest_dir, final InputStream i) throws ArchiveException, IOException {
    // Apache commons compress requires buffered input streams

    InputStream is;

    try {
        is = new CompressorStreamFactory().createCompressorInputStream(new BufferedInputStream(i));
    } catch (final CompressorException e) {
        throw new IOException("Could not create compressed input stream", e);
    }

    // Extract entries from archive

    if (!is.markSupported()) {
        is = new BufferedInputStream(is);
    }

    String archive_base = null;

    final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(is);
    ArchiveEntry entry;

    while ((entry = ais.getNextEntry()) != null) {

        final File file = extract(dest_dir, entry, ais);

        final String root = get_root_file_name(file);

        if (archive_base == null) {
            archive_base = root;
        } else if (!archive_base.equals(root)) {
            throw new IOException("Package has more than one base directory.");
        }
    }

    return archive_base;
}

From source file:org.apache.ivory.resource.AbstractEntityManager.java

protected Entity deserializeEntity(HttpServletRequest request, EntityType entityType)
        throws IOException, IvoryException {

    EntityParser<?> entityParser = EntityParserFactory.getParser(entityType);
    InputStream xmlStream = request.getInputStream();
    if (xmlStream.markSupported()) {
        xmlStream.mark(XML_DEBUG_LEN); // mark up to debug len
    }//from   ww  w .  ja  v a 2s  . com
    try {
        return entityParser.parse(xmlStream);
    } catch (IvoryException e) {
        if (LOG.isDebugEnabled() && xmlStream.markSupported()) {
            try {
                xmlStream.reset();
                String xmlData = getAsString(xmlStream);
                LOG.debug("XML DUMP for (" + entityType + "): " + xmlData, e);
            } catch (IOException ignore) {
            }
        }
        throw e;
    }
}