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:cn.ctyun.amazonaws.auth.AWS4Signer.java
/** * Calculate the hash of the request's payload. * Subclass could override this method to provide different values for "x-amz-content-sha256" header * or do any other necessary set-ups on the request headers. * (e.g. aws-chunked uses a pre-defined header value, and needs to change some headers * relating to content-encoding and content-length.) *//*w w w.j av a 2 s. co m*/ protected String calculateContentHash(Request<?> request) { InputStream payloadStream = getBinaryRequestPayloadStream(request); payloadStream.mark(-1); String contentSha256 = BinaryUtils.toHex(hash(payloadStream)); try { payloadStream.reset(); } catch (IOException e) { throw new AmazonClientException("Unable to reset stream after calculating AWS4 signature", e); } return contentSha256; }
From source file:org.codehaus.groovy.grails.web.pages.GroovyPageWritable.java
/** * Writes the Groovy source code attached to the given info object * to the response, prefixing each line with its line number. The * line numbers make it easier to match line numbers in exceptions * to the generated source./*from w ww .ja v a2 s .co m*/ * @param info The meta info for the GSP page that we want to write * the generated source for. * @param out The writer to send the source to. * @throws IOException If there is either a problem with the input * stream for the Groovy source, or the writer. */ protected void writeGroovySourceToResponse(GroovyPageMetaInfo info, Writer out) throws IOException { InputStream in = info.getGroovySource(); if (in == null) return; try { try { in.reset(); } catch (IOException e) { // ignore } BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); int lineNum = 1; int maxPaddingSize = 3; // Prepare the buffer containing the whitespace padding. // The padding is used to right-align the line numbers. StringBuilder paddingBuffer = new StringBuilder(maxPaddingSize); for (int i = 0; i < maxPaddingSize; i++) { paddingBuffer.append(' '); } // Set the initial padding. String padding = paddingBuffer.toString(); // Read the Groovy source line by line and write it to the // response, prefixing each line with the line number. for (String line = reader.readLine(); line != null; line = reader.readLine(), lineNum++) { // Get the current line number as a string. String numberText = String.valueOf(lineNum); // Decrease the padding if the current line number has // more digits than the previous one. if (padding.length() + numberText.length() > 4) { paddingBuffer.deleteCharAt(padding.length() - 1); padding = paddingBuffer.toString(); } // Write out this line. out.write(padding); out.write(numberText); out.write(": "); out.write(line); out.write('\n'); } } finally { out.close(); in.close(); } }
From source file:mj.ocraptor.extraction.tika.parser.iwork.IWorkPackageParser.java
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { ZipArchiveInputStream zip = new ZipArchiveInputStream(stream); ZipArchiveEntry entry = zip.getNextZipEntry(); TikaImageHelper helper = new TikaImageHelper(metadata); XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); IWORKDocumentType type = null;/*from ww w. jav a 2s .c o m*/ try { while (entry != null) { // ------------------------------------------------ // // -- handle image files // ------------------------------------------------ // String entryExtension = null; try { entryExtension = FilenameUtils.getExtension(new File(entry.getName()).getName()); } catch (Exception e) { e.printStackTrace(); } if (entryExtension != null && FileType.isValidImageFileExtension(entryExtension)) { File imageFile = null; try { imageFile = TikaImageHelper.saveZipEntryToTemp(zip, entry); helper.addImage(imageFile); } catch (Exception e) { e.printStackTrace(); } finally { if (imageFile != null) { imageFile.delete(); } } } // ------------------------------------------------ // // -- // ------------------------------------------------ // if (!IWORK_CONTENT_ENTRIES.contains(entry.getName())) { entry = zip.getNextZipEntry(); continue; } InputStream entryStream = new BufferedInputStream(zip, 4096); entryStream.mark(4096); type = IWORKDocumentType.detectType(entryStream); entryStream.reset(); if (type != null) { ContentHandler contentHandler; switch (type) { case KEYNOTE: contentHandler = new KeynoteContentHandler(xhtml, metadata); break; case NUMBERS: contentHandler = new NumbersContentHandler(xhtml, metadata); break; case PAGES: contentHandler = new PagesContentHandler(xhtml, metadata); break; case ENCRYPTED: // We can't do anything for the file right now contentHandler = null; break; default: throw new TikaException("Unhandled iWorks file " + type); } metadata.add(Metadata.CONTENT_TYPE, type.getType().toString()); xhtml.startDocument(); if (contentHandler != null) { context.getSAXParser().parse(new CloseShieldInputStream(entryStream), new OfflineContentHandler(contentHandler)); } } entry = zip.getNextZipEntry(); } helper.addTextToHandler(xhtml); xhtml.endDocument(); } catch (Exception e) { // TODO: logging e.printStackTrace(); } finally { if (zip != null) { zip.close(); } if (helper != null) { helper.close(); } } }
From source file:org.fcrepo.utilities.io.TestByteRangeInputStream.java
@SuppressWarnings("resource") @Test//ww w . ja va 2 s . c o m public void testSkippedBytes() throws IndexOutOfBoundsException, IOException { String data = "1234567890"; String input = "bytes=3-12"; InputStream bytes = new ByteArrayInputStream(data.getBytes(Charset.forName("UTF-8"))); ByteRangeInputStream test = new ByteRangeInputStream(bytes, 10, input); assertEquals("bad offset of " + test.offset + " for " + input, 3, test.offset); assertEquals("bad length of " + test.length + " for " + input, 7, test.length); assertEquals("bytes 3-9/10", test.contentRange); bytes.reset(); test = new ByteRangeInputStream(bytes, 10, "bytes=0-8"); assertEquals("123456789", IOUtils.toString(test)); bytes.reset(); InputStream bytes2 = new ByteArrayInputStream(data.getBytes(Charset.forName("UTF-8"))); test = new ByteRangeInputStream(bytes, 10, "bytes=0-2"); ByteRangeInputStream test2 = new ByteRangeInputStream(bytes2, 10, "bytes=-7"); SequenceInputStream test3 = new SequenceInputStream(test, test2); String actual = IOUtils.toString(test3); assertEquals(data, actual); }
From source file:org.apache.jackrabbit.core.data.DBDataStoreTest.java
public void testDbInputStreamReset() throws Exception { DataRecord record = store.getRecord(identifier); InputStream in = record.getStream(); try {/*www . j av a2s. c om*/ // test whether mark and reset works assertTrue(in.markSupported()); in.mark(data.length); while (-1 != in.read()) { // loop } assertTrue(in.markSupported()); try { in.reset(); } catch (Exception e) { fail("Unexpected exception while resetting input stream: " + e.getMessage()); } // test integrity of replayed bytes byte[] replayedBytes = new byte[data.length]; int length = in.read(replayedBytes); assertEquals(length, data.length); for (int i = 0; i < data.length; i++) { log.append(i + " data: " + data[i] + " replayed: " + replayedBytes[i] + "\n"); assertEquals(data[i], replayedBytes[i]); } assertEquals(-1, in.read()); } finally { in.close(); log.flush(); } }
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 ww w . ja v a 2 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());//ww w . java 2s .c o m in.mark(10); in.read(); in.read(); in.reset(); assertEquals('A', in.read()); }
From source file:com.kurento.kmf.content.internal.ControlProtocolManager.java
/** * Reads inputStream (from request) and detects incoming JSON encoding. * /* w w w.j a va 2 s .c o m*/ * @param inputStream * Input Stream from request * @return String identifier for detected JSON (UTF8, UTF16LE, ...) * @throws IOException * Exception while parsing JSON */ private String detectJsonEncoding(InputStream inputStream) throws IOException { inputStream.mark(4); int mask = 0; for (int count = 0; count < 4; count++) { int r = inputStream.read(); if (r == -1) { break; } mask = mask << 1; mask |= (r == 0) ? 0 : 1; } inputStream.reset(); return match(mask); }
From source file:com.alibaba.simpleimage.codec.jpeg.JPEGDecodePerformanceTest.java
protected void run(DecodeFacade decoder, File rootDir, String filename, int times, int frequency) throws Exception { long start, end, total = 0L; if (rootDir == null) { rootDir = imgDir;/* w ww . j a v a2 s. com*/ } FileInputStream inputStream = new FileInputStream(new File(rootDir, filename)); ByteArrayOutputStream temp = new ByteArrayOutputStream(); IOUtils.copy(inputStream, temp); IOUtils.closeQuietly(inputStream); InputStream img = temp.toInputStream(); temp = null; System.out.println("***********Performance Test**************"); for (int i = 0; i < frequency; i++) { // System.gc(); // Thread.sleep(5 * 1000L); start = System.currentTimeMillis(); for (int t = 0; t < times; t++) { // File img = imgs[t % imgs.length]; img.reset(); BufferedImage bi = decoder.decode(img); bi.getHeight(); bi = null; } end = System.currentTimeMillis(); total += (end - start); } System.out.printf("Decoder : %s \n", decoder.getName()); System.out.println("Image : " + filename); System.out.printf("Times : %d\n", times); System.out.printf("Frequency : %d\n", frequency); System.out.printf("Total time : %d ms\n", total); System.out.printf("Average time : %.2f ms\n", ((double) total / (times * frequency))); }