List of usage examples for java.io InputStream mark
public synchronized void mark(int readlimit)
From source file:de.micromata.genome.test.web.SimHttpServletRequest.java
protected void setInputStream(final InputStream servletIs) { this.servletIs = new ServletInputStream() { public int available() throws IOException { return servletIs.available(); }//from w w w. jav a2s . c om public void close() throws IOException { servletIs.close(); } public boolean equals(Object obj) { return servletIs.equals(obj); } public int hashCode() { return servletIs.hashCode(); } public void mark(int readlimit) { servletIs.mark(readlimit); } public boolean markSupported() { return servletIs.markSupported(); } public int read(byte[] b, int off, int len) throws IOException { return servletIs.read(b, off, len); } public int read(byte[] b) throws IOException { return servletIs.read(b); } public void reset() throws IOException { servletIs.reset(); } public long skip(long n) throws IOException { return servletIs.skip(n); } public String toString() { return servletIs.toString(); } @Override public int read() throws IOException { throw new UnsupportedOperationException(); } }; }
From source file:com.amazonaws.client.service.AmazonHttpClient.java
/** * Internal method to execute the HTTP method given. * * @see AmazonHttpClient#execute(Request, HttpResponseHandler, HttpResponseHandler) * @see AmazonHttpClient#execute(Request, HttpResponseHandler, HttpResponseHandler, ExecutionContext) *//*from ww w. j a v a 2s.c om*/ private <T> Response<T> executeHelper(final Request<?> request, HttpResponseHandler<AmazonWebServiceResponse<T>> responseHandler, HttpResponseHandler<AmazonServiceException> errorResponseHandler, ExecutionContext executionContext) throws AmazonClientException, AmazonServiceException { /* * Depending on which response handler we end up choosing to handle the * HTTP response, it might require us to leave the underlying HTTP * connection open, depending on whether or not it reads the complete * HTTP response stream from the HTTP connection, or if delays reading * any of the content until after a response is returned to the caller. */ boolean leaveHttpConnectionOpen = false; /* add the service endpoint to the logs. You can infer service name from service endpoint */ AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics() .addPropertyWith(ServiceName, request.getServiceName()) .addPropertyWith(ServiceEndpoint, request.getEndpoint()); // Apply whatever request options we know how to handle, such as user-agent. setUserAgent(request); int requestCount = 0; URI redirectedURI = null; HttpEntity entity = null; AmazonClientException retriedException = null; // Make a copy of the original request params and headers so that we can // permute it in this loop and start over with the original every time. Map<String, String> originalParameters = new LinkedHashMap<String, String>(); originalParameters.putAll(request.getParameters()); Map<String, String> originalHeaders = new HashMap<String, String>(); originalHeaders.putAll(request.getHeaders()); final AWSCredentials credentials = executionContext.getCredentials(); AmazonWebServiceRequest awsreq = request.getOriginalRequest(); ProgressListener listener = awsreq.getGeneralProgressListener(); Signer signer = null; while (true) { ++requestCount; awsRequestMetrics.setCounter(RequestCount, requestCount); if (requestCount > 1) { // retry request.setParameters(originalParameters); request.setHeaders(originalHeaders); } HttpRequestBase httpRequest = null; org.apache.http.HttpResponse apacheResponse = null; try { // Sign the request if a signer was provided if (signer == null) signer = executionContext.getSignerByURI(request.getEndpoint()); if (signer != null && credentials != null) { awsRequestMetrics.startEvent(RequestSigningTime); try { signer.sign(request, credentials); } finally { awsRequestMetrics.endEvent(RequestSigningTime); } } if (requestLog.isDebugEnabled()) { requestLog.debug("Sending Request: " + request.toString()); } httpRequest = httpRequestFactory.createHttpRequest(request, config, executionContext); if (httpRequest instanceof HttpEntityEnclosingRequest) { entity = ((HttpEntityEnclosingRequest) httpRequest).getEntity(); } if (redirectedURI != null) { httpRequest.setURI(redirectedURI); } if (requestCount > 1) { // retry // Notify the progress listener of the retry publishProgress(listener, ProgressEventType.CLIENT_REQUEST_RETRY_EVENT); awsRequestMetrics.startEvent(RetryPauseTime); try { pauseBeforeNextRetry(request.getOriginalRequest(), retriedException, requestCount, config.getRetryPolicy()); } finally { awsRequestMetrics.endEvent(RetryPauseTime); } } if (entity != null) { InputStream content = entity.getContent(); if (requestCount > 1) { // retry if (content.markSupported()) { content.reset(); content.mark(-1); } } else { if (content.markSupported()) { content.mark(-1); } } } captureConnectionPoolMetrics(httpClient.getConnectionManager(), awsRequestMetrics); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(AWSRequestMetrics.class.getSimpleName(), awsRequestMetrics); retriedException = null; publishProgress(listener, ProgressEventType.HTTP_REQUEST_STARTED_EVENT); awsRequestMetrics.startEvent(HttpRequestTime); try { apacheResponse = httpClient.execute(httpRequest, httpContext); } finally { awsRequestMetrics.endEvent(HttpRequestTime); } publishProgress(listener, ProgressEventType.HTTP_REQUEST_COMPLETED_EVENT); final StatusLine statusLine = apacheResponse.getStatusLine(); final int statusCode = statusLine == null ? -1 : statusLine.getStatusCode(); if (isRequestSuccessful(apacheResponse)) { awsRequestMetrics.addProperty(StatusCode, statusCode); /* * If we get back any 2xx status code, then we know we should * treat the service call as successful. */ leaveHttpConnectionOpen = responseHandler.needsConnectionLeftOpen(); HttpResponse httpResponse = createResponse(httpRequest, request, apacheResponse); T response = handleResponse(request, responseHandler, httpRequest, httpResponse, apacheResponse, executionContext); return new Response<T>(response, httpResponse); } if (isTemporaryRedirect(apacheResponse)) { /* * S3 sends 307 Temporary Redirects if you try to delete an * EU bucket from the US endpoint. If we get a 307, we'll * point the HTTP method to the redirected location, and let * the next retry deliver the request to the right location. */ Header[] locationHeaders = apacheResponse.getHeaders("location"); String redirectedLocation = locationHeaders[0].getValue(); if (log.isDebugEnabled()) log.debug("Redirecting to: " + redirectedLocation); redirectedURI = URI.create(redirectedLocation); httpRequest.setURI(redirectedURI); awsRequestMetrics.addPropertyWith(StatusCode, statusCode) .addPropertyWith(RedirectLocation, redirectedLocation) .addPropertyWith(AWSRequestID, null); continue; } leaveHttpConnectionOpen = errorResponseHandler.needsConnectionLeftOpen(); final AmazonServiceException ase = handleErrorResponse(request, errorResponseHandler, httpRequest, apacheResponse); awsRequestMetrics.addPropertyWith(AWSRequestID, ase.getRequestId()) .addPropertyWith(AWSErrorCode, ase.getErrorCode()) .addPropertyWith(StatusCode, ase.getStatusCode()); if (!shouldRetry(request.getOriginalRequest(), httpRequest, ase, requestCount, config.getRetryPolicy())) { throw ase; } // Comment out for now. Ref: CR2662349 // Preserve the cause of retry before retrying // awsRequestMetrics.addProperty(RetryCause, ase); if (RetryUtils.isThrottlingException(ase)) { awsRequestMetrics.incrementCounterWith(ThrottleException).addProperty(ThrottleException, ase); } // Cache the retryable exception retriedException = ase; /* * Checking for clock skew error again because we don't want to set the * global time offset for every service exception. */ if (RetryUtils.isClockSkewError(ase)) { int timeOffset = parseClockSkewOffset(apacheResponse, ase); SDKGlobalConfiguration.setGlobalTimeOffset(timeOffset); } resetRequestAfterError(request, ase); } catch (IOException ioe) { if (log.isInfoEnabled()) { log.info("Unable to execute HTTP request: " + ioe.getMessage(), ioe); } captureExceptionMetrics(ioe, awsRequestMetrics); awsRequestMetrics.addProperty(AWSRequestID, null); AmazonClientException ace = new AmazonClientException( "Unable to execute HTTP request: " + ioe.getMessage(), ioe); if (!shouldRetry(request.getOriginalRequest(), httpRequest, ace, requestCount, config.getRetryPolicy())) { throw ace; } // Cache the retryable exception retriedException = ace; resetRequestAfterError(request, ioe); } catch (RuntimeException e) { throw captureExceptionMetrics(e, awsRequestMetrics); } catch (Error e) { throw captureExceptionMetrics(e, awsRequestMetrics); } finally { /* * Some response handlers need to manually manage the HTTP * connection and will take care of releasing the connection on * their own, but if this response handler doesn't need the * connection left open, we go ahead and release the it to free * up resources. */ if (!leaveHttpConnectionOpen) { try { if (apacheResponse != null && apacheResponse.getEntity() != null && apacheResponse.getEntity().getContent() != null) { apacheResponse.getEntity().getContent().close(); } } catch (IOException e) { log.warn("Cannot close the response content.", e); } } } } /* end while (true) */ }
From source file:org.apache.fop.render.pdf.ImageRawJPEGAdapter.java
/** {@inheritDoc} */ public void outputContents(OutputStream out) throws IOException { InputStream in = getImage().createInputStream(); in = ImageUtil.decorateMarkSupported(in); try {//from ww w . j a v a 2 s .c o m JPEGFile jpeg = new JPEGFile(in); DataInput din = jpeg.getDataInput(); //Copy the whole JPEG file except: // - the ICC profile //TODO Thumbnails could safely be skipped, too. //TODO Metadata (XMP, IPTC, EXIF) could safely be skipped, too. while (true) { int reclen; int segID = jpeg.readMarkerSegment(); switch (segID) { case JPEGConstants.SOI: out.write(0xFF); out.write(segID); break; case JPEGConstants.EOI: case JPEGConstants.SOS: out.write(0xFF); out.write(segID); IOUtils.copy(in, out); //Just copy the rest! return; /* case JPEGConstants.APP1: //Metadata case JPEGConstants.APPD: jpeg.skipCurrentMarkerSegment(); break;*/ case JPEGConstants.APP2: //ICC (see ICC1V42.pdf) boolean skipICCProfile = false; in.mark(16); try { reclen = jpeg.readSegmentLength(); // Check for ICC profile byte[] iccString = new byte[11]; din.readFully(iccString); din.skipBytes(1); //string terminator (null byte) if ("ICC_PROFILE".equals(new String(iccString, "US-ASCII"))) { skipICCProfile = (this.image.getICCProfile() != null); } } finally { in.reset(); } if (skipICCProfile) { //ICC profile is skipped as it is already embedded as a PDF object jpeg.skipCurrentMarkerSegment(); break; } default: out.write(0xFF); out.write(segID); reclen = jpeg.readSegmentLength(); //write short out.write((reclen >>> 8) & 0xFF); out.write((reclen >>> 0) & 0xFF); int left = reclen - 2; byte[] buf = new byte[2048]; while (left > 0) { int part = Math.min(buf.length, left); din.readFully(buf, 0, part); out.write(buf, 0, part); left -= part; } } } } finally { IOUtils.closeQuietly(in); } }
From source file:at.ac.tuwien.qse.sepm.dao.repo.impl.JpegSerializer.java
@Override public void update(InputStream is, OutputStream os, PhotoMetadata metadata) throws DAOException { if (is == null) throw new IllegalArgumentException(); if (os == null) throw new IllegalArgumentException(); if (metadata == null) throw new IllegalArgumentException(); LOGGER.debug("updating photo metadata {}", metadata); String tags = "travelimg"; for (Tag element : metadata.getTags()) { tags += "/" + element.getName(); }//from w ww. ja va 2s . c om Rating rating = metadata.getRating(); tags += "/rating|" + rating; Place place = metadata.getPlace(); if (place != null) { tags += "/place|" + place.getCity() + "|" + place.getCountry() + "|" + place.getLatitude() + "|" + place.getLongitude(); } Journey journey = metadata.getJourney(); if (journey != null) { tags += "/journey|" + journey.getName() + "|" + journey.getStartDate().format(DATE_FORMATTER) + "|" + journey.getEndDate().format(DATE_FORMATTER); } Photographer photographer = metadata.getPhotographer(); if (photographer != null) { tags += "/photographer|" + photographer.getName(); } try { is.mark(Integer.MAX_VALUE); ImageMetadata imageData = Imaging.getMetadata(is, null); if (imageData == null) { LOGGER.debug("could not find image metadata"); throw new DAOException("No metadata found."); } if (!(imageData instanceof JpegImageMetadata)) { LOGGER.debug("metadata is of unknown type"); throw new DAOException("Metadata is of unknown type."); } JpegImageMetadata jpegData = (JpegImageMetadata) imageData; TiffOutputSet outputSet = new TiffOutputSet(); TiffImageMetadata exifData = jpegData.getExif(); if (exifData != null) { outputSet = exifData.getOutputSet(); } TiffOutputDirectory exifDirectory = outputSet.getOrCreateExifDirectory(); outputSet.setGPSInDegrees(metadata.getLongitude(), metadata.getLatitude()); exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL); exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL, DATE_FORMATTER.format(metadata.getDatetime())); exifDirectory.removeField(ExifTagConstants.EXIF_TAG_USER_COMMENT); exifDirectory.add(ExifTagConstants.EXIF_TAG_USER_COMMENT, tags); is.reset(); new ExifRewriter().updateExifMetadataLossless(is, os, outputSet); } catch (IOException | ImageReadException | ImageWriteException ex) { LOGGER.warn("failed updating metadata"); throw new DAOException(ex); } LOGGER.debug("updated photo metadata"); }
From source file:org.mifos.customers.client.struts.action.ClientCustAction.java
@TransactionDemarcate(joinToken = true) public ActionForward retrievePicture(ActionMapping mapping, @SuppressWarnings("unused") ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ClientBO clientBO = getClientFromSession(request); ClientPhotoService cps = ApplicationContextProvider.getBean(ClientPhotoService.class); ClientPhoto cp = cps.read(clientBO.getCustomerId().longValue()); InputStream in = null; if (cp != null) { in = new ByteArrayInputStream(cps.getData(cp.getImageInfo().getPath())); response.setContentType(cp.getImageInfo().getContentType()); } else {/* ww w . j a v a 2 s . c o m*/ in = ClientPhotoService.class.getResourceAsStream("/org/mifos/image/nopicture.png"); response.setContentType("image/png"); } in.mark(0); BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); byte[] by = new byte[1024 * 4]; // 4K buffer buf, 0, buf.length int index = in.read(by, 0, 1024 * 4); while (index != -1) { out.write(by, 0, index); index = in.read(by, 0, 1024 * 4); } out.flush(); out.close(); in.reset(); String forward = ClientConstants.CUSTOMER_PICTURE_PAGE; return mapping.findForward(forward); }
From source file:org.apache.tika.gui.TikaGUI.java
private void handleStream(InputStream input, Metadata md) throws Exception { StringWriter htmlBuffer = new StringWriter(); StringWriter textBuffer = new StringWriter(); StringWriter textMainBuffer = new StringWriter(); StringWriter xmlBuffer = new StringWriter(); StringBuilder metadataBuffer = new StringBuilder(); ContentHandler handler = new TeeContentHandler(getHtmlHandler(htmlBuffer), getTextContentHandler(textBuffer), getTextMainContentHandler(textMainBuffer), getXmlContentHandler(xmlBuffer)); context.set(DocumentSelector.class, new ImageDocumentSelector()); input = TikaInputStream.get(new ProgressMonitorInputStream(this, "Parsing stream", input)); if (input.markSupported()) { int mark = -1; if (input instanceof TikaInputStream) { if (((TikaInputStream) input).hasFile()) { mark = (int) ((TikaInputStream) input).getLength(); }/*from ww w . jav a2s .co m*/ } if (mark == -1) { mark = MAX_MARK; } input.mark(mark); } parser.parse(input, handler, md, context); String[] names = md.names(); Arrays.sort(names); for (String name : names) { for (String val : md.getValues(name)) { metadataBuffer.append(name); metadataBuffer.append(": "); metadataBuffer.append(val); metadataBuffer.append("\n"); } } String name = md.get(Metadata.RESOURCE_NAME_KEY); if (name != null && name.length() > 0) { setTitle("Apache Tika: " + name); } else { setTitle("Apache Tika: unnamed document"); } setText(metadata, metadataBuffer.toString()); setText(xml, xmlBuffer.toString()); setText(text, textBuffer.toString()); setText(textMain, textMainBuffer.toString()); setText(html, htmlBuffer.toString()); if (!input.markSupported()) { setText(json, "InputStream does not support mark/reset for Recursive Parsing"); layout.show(cards, "metadata"); return; } boolean isReset = false; try { input.reset(); isReset = true; } catch (IOException e) { setText(json, "Error during stream reset.\n" + "There's a limit of " + MAX_MARK + " bytes for this type of processing in the GUI.\n" + "Try the app with command line argument of -J."); } if (isReset) { RecursiveParserWrapper wrapper = new RecursiveParserWrapper(parser, new BasicContentHandlerFactory(BasicContentHandlerFactory.HANDLER_TYPE.BODY, -1)); wrapper.parse(input, null, new Metadata(), new ParseContext()); StringWriter jsonBuffer = new StringWriter(); JsonMetadataList.setPrettyPrinting(true); JsonMetadataList.toJson(wrapper.getMetadata(), jsonBuffer); setText(json, jsonBuffer.toString()); } layout.show(cards, "metadata"); }
From source file:org.talend.designer.runprocess.java.JavaProcessor.java
/** * Check current stream whether zip stream by check header signature. Zip header signature = 0x504B 0304(big endian) * //from ww w .ja v a2 s . c o m * @param wsdlStream the wsdl stream. <b>Must Support Mark&Reset . Must at beginning of stream.</b> * @return true, if is zip stream. * @throws IOException Signals that an I/O exception has occurred. */ private boolean checkIsZipStream(InputStream wsdlStream) throws IOException { boolean isZip = false; byte[] headerB = new byte[4]; wsdlStream.mark(4); wsdlStream.read(headerB); int header = ByteBuffer.wrap(headerB).getInt(); if (header == 0x504B0304) { isZip = true; } wsdlStream.reset(); return isZip; }
From source file:com.ksc.http.KSCHttpClient.java
/** * Internal method to execute the HTTP method given. *//*from w w w . ja v a2 s. c om*/ private <T> Response<T> executeHelper(final Request<?> request, HttpResponseHandler<KscWebServiceResponse<T>> responseHandler, HttpResponseHandler<KscServiceException> errorResponseHandler, final ExecutionContext executionContext, List<RequestHandler2> requestHandlers) throws InterruptedException { /* * add the service endpoint to the logs. You can infer service name from service endpoint */ final KscRequestMetrics kscRequestMetrics = executionContext.getKscRequestMetrics() .addPropertyWith(Field.ServiceName, request.getServiceName()) .addPropertyWith(Field.ServiceEndpoint, request.getEndpoint()); // Make a copy of the original request params and headers so that we can // permute it in this loop and start over with the original every time. final Map<String, List<String>> originalParameters = new LinkedHashMap<String, List<String>>( request.getParameters()); final Map<String, String> originalHeaders = new HashMap<String, String>(request.getHeaders()); // Always mark the input stream before execution. final ExecOneRequestParams execOneParams = new ExecOneRequestParams(); final InputStream originalContent = request.getContent(); if (originalContent != null && originalContent.markSupported() && !(originalContent instanceof BufferedInputStream)) { // Mark only once for non-BufferedInputStream KscWebServiceRequest kscreq = request.getOriginalRequest(); final int readLimit = kscreq.getRequestClientOptions().getReadLimit(); originalContent.mark(readLimit); } while (true) { checkInterrupted(); if (originalContent instanceof BufferedInputStream && originalContent.markSupported()) { // Mark everytime for BufferedInputStream, since the marker could // have been invalidated KscWebServiceRequest kscreq = request.getOriginalRequest(); final int readLimit = kscreq.getRequestClientOptions().getReadLimit(); originalContent.mark(readLimit); } execOneParams.initPerRetry(); if (execOneParams.redirectedURI != null) { /* * [scheme:][//authority][path][?query][#fragment] */ String scheme = execOneParams.redirectedURI.getScheme(); String beforeAuthority = scheme == null ? "" : scheme + "://"; String authority = execOneParams.redirectedURI.getAuthority(); String path = execOneParams.redirectedURI.getPath(); request.setEndpoint(URI.create(beforeAuthority + authority)); request.setResourcePath(path); } if (execOneParams.authRetryParam != null) { request.setEndpoint(execOneParams.authRetryParam.getEndpointForRetry()); } kscRequestMetrics.setCounter(Field.RequestCount, execOneParams.requestCount); if (execOneParams.isRetry()) { request.setParameters(originalParameters); request.setHeaders(originalHeaders); request.setContent(originalContent); } try { Response<T> response = executeOneRequest(request, responseHandler, errorResponseHandler, executionContext, kscRequestMetrics, execOneParams, requestHandlers); if (response != null) { return response; } } catch (IOException ioe) { if (log.isInfoEnabled()) { log.info("Unable to execute HTTP request: " + ioe.getMessage(), ioe); } captureExceptionMetrics(ioe, kscRequestMetrics); kscRequestMetrics.addProperty(Field.KSCRequestID, null); KscClientException ace = new KscClientException( "Unable to execute HTTP request: " + ioe.getMessage(), ioe); if (!shouldRetry(request.getOriginalRequest(), execOneParams, ace, executionContext)) { throw lastReset(ace, request); } // Cache the retryable exception execOneParams.retriedException = ace; } catch (RuntimeException e) { throw lastReset(captureExceptionMetrics(e, kscRequestMetrics), request); } catch (Error e) { throw lastReset(captureExceptionMetrics(e, kscRequestMetrics), request); } finally { /* * Some response handlers need to manually manage the HTTP connection and will take * care of releasing the connection on their own, but if this response handler * doesn't need the connection left open, we go ahead and release the it to free up * resources. */ if (!execOneParams.leaveHttpConnectionOpen) { if (execOneParams.apacheResponse != null) { HttpEntity entity = execOneParams.apacheResponse.getEntity(); if (entity != null) { try { closeQuietly(entity.getContent(), log); } catch (IOException e) { log.warn("Cannot close the response content.", e); } } } } } } /* end while (true) */ }