List of usage examples for java.io InputStream reset
public synchronized void reset() throws IOException
mark
method was last called on this input stream. From source file:org.openspotlight.storage.test.AbstractStorageSessionTest.java
@Test public void shouldWorkWithInputStreamPropertiesOnAutoFlush() throws Exception { final StorageSession session = autoFlushInjector.getInstance(StorageSession.class); final StorageNode newNode = session.withPartition(ExamplePartition.DEFAULT).createNodeWithType("newNode1") .withSimpleKey("sequence", "1").withSimpleKey("name", "name").andCreate(); final InputStream stream = new ByteArrayInputStream("streamValue".getBytes()); newNode.setSimpleProperty(session, "streamProperty", stream); final StorageNode loadedNode = session.withPartition(ExamplePartition.DEFAULT).createCriteria() .withNodeType("newNode1").withProperty("sequence").equalsTo("1").withProperty("name") .equalsTo("name").buildCriteria().andSearchUnique(session); stream.reset(); assertThat(IOUtils.contentEquals(newNode.getPropertyValueAsStream(session, "streamProperty"), stream), is(true));//from w w w .j ava2 s . c o m final InputStream loaded1 = loadedNode.getPropertyValueAsStream(session, "streamProperty"); final ByteArrayOutputStream temporary1 = new ByteArrayOutputStream(); IOUtils.copy(loaded1, temporary1); final String asString1 = new String(temporary1.toByteArray()); final ByteArrayOutputStream temporary2 = new ByteArrayOutputStream(); final InputStream loaded2 = loadedNode.getPropertyValueAsStream(session, "streamProperty"); IOUtils.copy(loaded2, temporary2); final String asString2 = new String(temporary2.toByteArray()); assertThat(asString1, is("streamValue")); assertThat(asString2, is("streamValue")); }
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 av a 2s .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:org.opentox.toxotis.client.https.PostHttpsClient.java
private void postMultiPart() throws ServiceInvocationException { String charset = "UTF-8"; String LINE_FEED = "\r\n"; InputStream is; try {//from w w w.ja v a 2s. c o m getPostLock().lock(); // LOCK is = new FileInputStream(fileContentToPost); // creates a unique boundary based on time stamp long boundaryTs = System.currentTimeMillis(); String boundary = "===" + boundaryTs + "==="; HttpURLConnection httpConn = connect(getUri().toURI()); httpConn.setUseCaches(false); httpConn.setDoOutput(true); // indicates POST method httpConn.setDoInput(true); httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=\"" + boundary + "\""); httpConn.setRequestProperty("User-Agent", "CodeJava Agent"); httpConn.setRequestProperty("Test", "Bonjour"); OutputStream outputStream = httpConn.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); final int nParams = postParameters.size(); if (nParams > 0) { for (Map.Entry<String, String> e : postParameters.entrySet()) { writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + e.getKey() + "\"").append(LINE_FEED); writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED); writer.append(LINE_FEED); writer.append(e.getValue()).append(LINE_FEED); writer.flush(); } } if (is.read() > 0) { is.reset(); writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + fileUploadFieldName + "\"; filename=\"" + fileUploadFilename + "\"").append(LINE_FEED); writer.append( "Content-Type: " + java.net.URLConnection.guessContentTypeFromName(fileUploadFilename)) .append(LINE_FEED); writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); writer.append(LINE_FEED); writer.flush(); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = is.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); is.close(); writer.append(LINE_FEED); writer.flush(); writer.append(LINE_FEED).flush(); } writer.append("--" + boundary + "--").append(LINE_FEED); writer.close(); } catch (final IOException ex) { ConnectionException postException = new ConnectionException( "Exception caught while posting the parameters to the " + "remote web service located at '" + getUri() + "'", ex); postException.setActor(getUri() != null ? getUri().toString() : "N/A"); throw postException; } finally { getPostLock().unlock(); // UNLOCK } }
From source file:org.codice.ddf.endpoints.rest.RESTEndpoint.java
@POST @Path("/metacard") public Response createMetacard(MultipartBody multipartBody, @Context UriInfo requestUriInfo, @QueryParam("transform") String transformerParam) { LOGGER.trace("ENTERING: createMetacard"); String contentUri = multipartBody.getAttachmentObject("contentUri", String.class); LOGGER.debug("contentUri = {}", contentUri); InputStream stream = null; String filename = null;/*from www . j a va2s . c o m*/ String contentType = null; Response response = null; String transformer = DEFAULT_METACARD_TRANSFORMER; if (transformerParam != null) { transformer = transformerParam; } Attachment contentPart = multipartBody.getAttachment(FILE_ATTACHMENT_CONTENT_ID); if (contentPart != null) { // Example Content-Type header: // Content-Type: application/json;id=geojson if (contentPart.getContentType() != null) { contentType = contentPart.getContentType().toString(); } // Get the file contents as an InputStream and ensure the stream is positioned // at the beginning try { stream = contentPart.getDataHandler().getInputStream(); if (stream != null && stream.available() == 0) { stream.reset(); } } catch (IOException e) { LOGGER.warn("IOException reading stream from file attachment in multipart body", e); } } else { LOGGER.debug("No file contents attachment found"); } MimeType mimeType = null; if (contentType != null) { try { mimeType = new MimeType(contentType); } catch (MimeTypeParseException e) { LOGGER.debug("Unable to create MimeType from raw data {}", contentType); } } else { LOGGER.debug("No content type specified in request"); } try { Metacard metacard = generateMetacard(mimeType, "assigned-when-ingested", stream); String metacardId = metacard.getId(); LOGGER.debug("Metacard {} created", metacardId); LOGGER.debug("Transforming metacard {} to {} to be able to return it to client", metacardId, transformer); final BinaryContent content = catalogFramework.transform(metacard, transformer, null); LOGGER.debug("Metacard to {} transform complete for {}, preparing response.", transformer, metacardId); Response.ResponseBuilder responseBuilder = Response.ok(content.getInputStream(), content.getMimeTypeValue()); response = responseBuilder.build(); } catch (MetacardCreationException | CatalogTransformerException e) { throw new ServerErrorException("Unable to create metacard", Status.BAD_REQUEST); } LOGGER.trace("EXITING: createMetacard"); return response; }
From source file:com.microsoft.azure.storage.core.Utility.java
/** * Encrypts an input stream up to a given length. * Exits early if the encrypted data is longer than the abandon length. * /* w ww . j av a 2 s . c o m*/ * @param sourceStream * A <code>InputStream</code> object that represents the stream to measure. * @param targetStream * A <code>ByteArrayOutputStream</code> object that represents the stream to write the encrypted data. * @param cipher * The <code>Cipher</code> to use to encrypt the data. * @param writeLength * The number of bytes to read and encrypt from the sourceStream. * @param abandonLength * The number of bytes to read before the analysis is abandoned. Set this value to <code>-1</code> to * force the entire stream to be read. This parameter is provided to support upload thresholds. * @return * The size of the encrypted stream, or -1 if the encrypted stream would be over the abandonLength. * @throws IOException * If an I/O error occurs. */ public static long encryptStreamIfUnderThreshold(final InputStream sourceStream, final ByteArrayOutputStream targetStream, Cipher cipher, long writeLength, long abandonLength) throws IOException { if (abandonLength < 0) { abandonLength = Long.MAX_VALUE; } if (!sourceStream.markSupported()) { throw new IllegalArgumentException(SR.INPUT_STREAM_SHOULD_BE_MARKABLE); } sourceStream.mark(Constants.MAX_MARK_LENGTH); if (writeLength < 0) { writeLength = Long.MAX_VALUE; } CipherOutputStream encryptStream = new CipherOutputStream(targetStream, cipher); int count = -1; long totalEncryptedLength = targetStream.size(); final byte[] retrievedBuff = new byte[Constants.BUFFER_COPY_LENGTH]; int nextCopy = (int) Math.min(retrievedBuff.length, writeLength - totalEncryptedLength); count = sourceStream.read(retrievedBuff, 0, nextCopy); while (nextCopy > 0 && count != -1) { // Note: We are flushing the CryptoStream on every write here. This way, we don't end up encrypting more data than we intend here, if // we go over the abandonLength. encryptStream.write(retrievedBuff, 0, count); encryptStream.flush(); totalEncryptedLength = targetStream.size(); if (totalEncryptedLength > abandonLength) { // Abandon operation break; } nextCopy = (int) Math.min(retrievedBuff.length, writeLength - totalEncryptedLength); count = sourceStream.read(retrievedBuff, 0, nextCopy); } sourceStream.reset(); sourceStream.mark(Constants.MAX_MARK_LENGTH); encryptStream.close(); totalEncryptedLength = targetStream.size(); if (totalEncryptedLength > abandonLength) { totalEncryptedLength = -1; } return totalEncryptedLength; }
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 .j a v a2s. 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:org.exist.collections.MutableCollection.java
@Override public void store(final Txn transaction, final DBBroker broker, final IndexInfo info, final InputSource source) throws EXistException, PermissionDeniedException, TriggerException, SAXException, LockException { storeXMLInternal(transaction, broker, info, storeInfo -> { try {/*from www. j a v a 2s . c o m*/ final InputStream is = source.getByteStream(); if (is != null && is.markSupported()) { is.reset(); } else { final Reader cs = source.getCharacterStream(); if (cs != null && cs.markSupported()) { cs.reset(); } } } catch (final IOException e) { // mark is not supported: exception is expected, do nothing LOG.debug( "InputStream or CharacterStream underlying the InputSource does not support marking and therefore cannot be re-read."); } final XMLReader reader = getReader(broker, false, storeInfo.getCollectionConfig()); storeInfo.setReader(reader, null); try { reader.parse(source); } catch (final IOException e) { throw new EXistException(e); } finally { releaseReader(broker, storeInfo, reader); } }); }
From source file:org.rssowl.core.internal.connection.DefaultProtocolHandler.java
private InputStream pipeStream(InputStream inputStream, HttpMethodBase method) throws IOException { Assert.isNotNull(inputStream);/*from ww w .jav a 2s.com*/ /* Retrieve the Content Encoding */ String contentEncoding = method.getResponseHeader(HEADER_RESPONSE_CONTENT_ENCODING) != null ? method.getResponseHeader(HEADER_RESPONSE_CONTENT_ENCODING).getValue() : null; boolean isGzipStream = false; /* * Return in case the Content Encoding is not given and the InputStream does * not support mark() and reset() */ if ((contentEncoding == null || !contentEncoding.equals("gzip")) && !inputStream.markSupported()) //$NON-NLS-1$ return inputStream; /* Content Encoding is set to gzip, so use the GZipInputStream */ if (contentEncoding != null && contentEncoding.equals("gzip")) { //$NON-NLS-1$ isGzipStream = true; } /* Detect if the Stream is gzip encoded */ else if (inputStream.markSupported()) { inputStream.mark(2); int id1 = inputStream.read(); int id2 = inputStream.read(); inputStream.reset(); /* Check for GZip Magic Numbers (See RFC 1952) */ if (id1 == 0x1F && id2 == 0x8B) isGzipStream = true; } /* Create the GZipInputStream then */ if (isGzipStream) { try { return new GZIPInputStream(inputStream); } catch (IOException e) { return inputStream; } } return inputStream; }