List of usage examples for java.io InputStream skip
public long skip(long n) throws IOException
n
bytes of data from this input stream. From source file:Main.java
public static int getOrientation(InputStream is) { if (is == null) { return 0; }/*from w ww .j a va2 s .co m*/ byte[] buf = new byte[8]; int length = 0; // ISO/IEC 10918-1:1993(E) while (read(is, buf, 2) && (buf[0] & 0xFF) == 0xFF) { int marker = buf[1] & 0xFF; // Check if the marker is a padding. if (marker == 0xFF) { continue; } // Check if the marker is SOI or TEM. if (marker == 0xD8 || marker == 0x01) { continue; } // Check if the marker is EOI or SOS. if (marker == 0xD9 || marker == 0xDA) { return 0; } // Get the length and check if it is reasonable. if (!read(is, buf, 2)) { return 0; } length = pack(buf, 0, 2, false); if (length < 2) { Log.e(TAG, "Invalid length"); return 0; } length -= 2; // Break if the marker is EXIF in APP1. if (marker == 0xE1 && length >= 6) { if (!read(is, buf, 6)) return 0; length -= 6; if (pack(buf, 0, 4, false) == 0x45786966 && pack(buf, 4, 2, false) == 0) { break; } } // Skip other markers. try { is.skip(length); } catch (IOException ex) { return 0; } length = 0; } // JEITA CP-3451 Exif Version 2.2 if (length > 8) { int offset = 0; byte[] jpeg = new byte[length]; if (!read(is, jpeg, length)) { return 0; } // Identify the byte order. int tag = pack(jpeg, offset, 4, false); if (tag != 0x49492A00 && tag != 0x4D4D002A) { Log.e(TAG, "Invalid byte order"); return 0; } boolean littleEndian = (tag == 0x49492A00); // Get the offset and check if it is reasonable. int count = pack(jpeg, offset + 4, 4, littleEndian) + 2; if (count < 10 || count > length) { Log.e(TAG, "Invalid offset"); return 0; } offset += count; length -= count; // Get the count and go through all the elements. count = pack(jpeg, offset - 2, 2, littleEndian); while (count-- > 0 && length >= 12) { // Get the tag and check if it is orientation. tag = pack(jpeg, offset, 2, littleEndian); if (tag == 0x0112) { // We do not really care about type and count, do we? int orientation = pack(jpeg, offset + 8, 2, littleEndian); switch (orientation) { case 1: return 0; case 3: return 180; case 6: return 90; case 8: return 270; } Log.i(TAG, "Unsupported orientation"); return 0; } offset += 12; length -= 12; } } Log.i(TAG, "Orientation not found"); return 0; }
From source file:org.apache.flume.source.FTPSource.java
public boolean readStream(InputStream inputStream, long position) { if (inputStream == null) { return false; }//from w ww. j av a 2s. c o m boolean successRead = true; if (ftpSourceUtils.isFlushLines()) { try { inputStream.skip(position); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String line = null; while ((line = in.readLine()) != null) { processMessage(line.getBytes()); } } catch (IOException e) { log.error(e.getMessage(), e); successRead = false; } } else { try { inputStream.skip(position); byte[] bytesArray = new byte[CHUNKSIZE]; int bytesRead = -1; while ((bytesRead = inputStream.read(bytesArray)) != -1) { try (ByteArrayOutputStream baostream = new ByteArrayOutputStream(CHUNKSIZE)) { baostream.write(bytesArray, 0, bytesRead); byte[] data = baostream.toByteArray(); processMessage(data); data = null; } } inputStream.close(); } catch (IOException e) { log.error("on readStream", e); successRead = false; } } //end condition for only byte return successRead; }
From source file:no.nordicsemi.android.nrftoolbox.dfu.HexInputStream.java
private int calculateBinSize() throws IOException { int binSize = 0; final InputStream in = this.in; in.mark(in.available());//from w ww .j a va2 s . c o m int b, lineSize, type; try { b = in.read(); while (true) { checkComma(b); lineSize = readByte(in); // reading the length of the data in this line in.skip(4); // skipping address part type = readByte(in); // reading the line type switch (type) { case 0x00: // data type line binSize += lineSize; break; case 0x01: // end of file return binSize; case 0x02: // extended segment address record case 0x04: // extended linear address record default: break; } in.skip(lineSize * 2 /* 2 hex per one byte */ + 2 /* check sum */); // skip end of line while (true) { b = in.read(); if (b != '\n' && b != '\r') { break; } } } } finally { try { in.reset(); } catch (IOException ex) { this.in = new BufferedInputStream( new DefaultHttpClient().execute(this.httpGet).getEntity().getContent()); } } }
From source file:org.kawanfw.sql.jdbc.BlobHttp.java
/** * Retrieves all or part of the <code>BLOB</code> value that this * <code>Blob</code> object represents, as an array of bytes. This * <code>byte</code> array contains up to <code>length</code> consecutive * bytes starting at position <code>pos</code>. * /*ww w . ja v a2s. com*/ * @param pos * the ordinal position of the first byte in the * <code>BLOB</code> value to be extracted; the first byte is at * position 1 * @param length * the number of consecutive bytes to be copied * @return a byte array containing up to <code>length</code> consecutive * bytes from the <code>BLOB</code> value designated by this * <code>Blob</code> object, starting with the byte at position * <code>pos</code> * @exception SQLException * if there is an error accessing the <code>BLOB</code> value * @see #setBytes * @since 1.2 */ @Override public byte[] getBytes(long pos, int length) throws SQLException { // Before reading, close the Output Stream if user forgot it IOUtils.closeQuietly(outputStream); if (file == null) { throw new SQLException(BLOB_NO_FILE); } if (!file.exists()) { throw new SQLException(BLOB_IS_NOT_ACCESSIBLE_ANYMORE); } // Close silently the OutputStream if use forgot it InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); byte[] b = new byte[length]; in.skip(pos - 1); in.read(b); return b; } catch (IOException e) { throw new SQLException(e); } finally { IOUtils.closeQuietly(in); } }
From source file:com.intel.chimera.stream.AbstractCryptoStreamTest.java
private void doSkipTest(String cipherClass, boolean withChannel) throws IOException { InputStream in = getCryptoInputStream(new ByteArrayInputStream(encData), getCipher(cipherClass), defaultBufferSize, iv, withChannel); byte[] result = new byte[dataLen]; int n1 = readAll(in, result, 0, dataLen / 3); long skipped = in.skip(dataLen / 3); int n2 = readAll(in, result, 0, dataLen); Assert.assertEquals(dataLen, n1 + skipped + n2); byte[] readData = new byte[n2]; System.arraycopy(result, 0, readData, 0, n2); byte[] expectedData = new byte[n2]; System.arraycopy(data, dataLen - n2, expectedData, 0, n2); Assert.assertArrayEquals(readData, expectedData); try {//from w w w . j a v a2s.co m skipped = in.skip(-3); Assert.fail("Skip Negative length should fail."); } catch (IllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("Negative skip length")); } // Skip after EOF skipped = in.skip(3); Assert.assertEquals(skipped, 0); in.close(); }
From source file:org.apache.pdfbox.preflight.process.StreamValidationProcess.java
protected void checkStreamLength(PreflightContext context, COSObject cObj) throws ValidationException { COSStream streamObj = (COSStream) cObj.getObject(); int length = streamObj.getInt(COSName.LENGTH); InputStream ra = null; try {/* w w w.ja v a 2s. co m*/ ra = context.getSource().getInputStream(); Long offset = context.getDocument().getDocument().getXrefTable().get(new COSObjectKey(cObj)); // ---- go to the beginning of the object long skipped = 0; if (offset != null) { while (skipped != offset) { long curSkip = ra.skip(offset - skipped); if (curSkip < 0) { addValidationError(context, new ValidationError(ERROR_SYNTAX_STREAM_DAMAGED, "Unable to skip bytes in the PDFFile to check stream length")); return; } skipped += curSkip; } // ---- go to the stream key word if (readUntilStream(ra)) { int c = ra.read(); if (c == '\r') { ra.read(); } // else c is '\n' no more character to read // ---- Here is the true beginning of the Stream Content. // ---- Read the given length of bytes and check the 10 next bytes // ---- to see if there are endstream. byte[] buffer = new byte[1024]; int nbBytesToRead = length; do { int cr; if (nbBytesToRead > 1024) { cr = ra.read(buffer, 0, 1024); } else { cr = ra.read(buffer, 0, nbBytesToRead); } if (cr == -1) { addStreamLengthValidationError(context, cObj, length, ""); return; } else { nbBytesToRead -= cr; } } while (nbBytesToRead > 0); int len = "endstream".length() + 2; byte[] buffer2 = new byte[len]; for (int i = 0; i < len; ++i) { buffer2[i] = (byte) ra.read(); } // ---- check the content of 10 last characters String endStream = new String(buffer2, Charsets.ISO_8859_1); if (buffer2[0] == '\r' && buffer2[1] == '\n') { if (!endStream.contains("endstream")) { addStreamLengthValidationError(context, cObj, length, endStream); } } else if (buffer2[0] == '\r' && buffer2[1] == 'e') { if (!endStream.contains("endstream")) { addStreamLengthValidationError(context, cObj, length, endStream); } } else if (buffer2[0] == '\n' && buffer2[1] == 'e') { if (!endStream.contains("endstream")) { addStreamLengthValidationError(context, cObj, length, endStream); } } else { if (!endStream.startsWith("endStream")) { addStreamLengthValidationError(context, cObj, length, endStream); } } } else { addStreamLengthValidationError(context, cObj, length, ""); } } } catch (IOException e) { throw new ValidationException("Unable to read a stream to validate: " + e.getMessage(), e); } finally { IOUtils.closeQuietly(ra); } }
From source file:org.jboss.windup.util.RPMToZipTransformer.java
public static File convertRpmToZip(File file) throws Exception { LOG.info("File: " + file.getAbsolutePath()); FileInputStream fis = new FileInputStream(file); ReadableChannelWrapper in = new ReadableChannelWrapper(Channels.newChannel(fis)); InputStream uncompressed = new GZIPInputStream(fis); in = new ReadableChannelWrapper(Channels.newChannel(uncompressed)); String rpmZipName = file.getName(); rpmZipName = StringUtils.replace(rpmZipName, ".", "-"); rpmZipName = rpmZipName + ".zip"; String rpmZipPath = FilenameUtils.getFullPath(file.getAbsolutePath()); File rpmZipOutput = new File(rpmZipPath + File.separator + rpmZipName); LOG.info("Converting RPM: " + file.getName() + " to ZIP: " + rpmZipOutput.getName()); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(rpmZipOutput)); String rpmName = file.getName(); rpmName = StringUtils.replace(rpmName, ".", "-"); CpioHeader header;//www.j a va 2s .co m int total = 0; do { header = new CpioHeader(); total = header.read(in, total); if (header.getFileSize() > 0) { BoundedInputStream bis = new BoundedInputStream(uncompressed, header.getFileSize()); String relPath = FilenameUtils.separatorsToSystem(header.getName()); relPath = StringUtils.removeStart(relPath, "."); relPath = StringUtils.removeStart(relPath, "/"); relPath = rpmName + File.separator + relPath; relPath = StringUtils.replace(relPath, "\\", "/"); ZipEntry zipEntry = new ZipEntry(relPath); zos.putNextEntry(zipEntry); IOUtils.copy(bis, zos); } else { final int skip = header.getFileSize(); if (uncompressed.skip(skip) != skip) throw new RuntimeException("Skip failed."); } total += header.getFileSize(); } while (!header.isLast()); zos.flush(); zos.close(); return rpmZipOutput; }
From source file:SubmitResults.java
public boolean sendFile(Main parent, String hostname, String instanceFilePath, String status, String user, String password, boolean encrypted, String newIdent) { boolean submit_status = false; File tempFile = null;//from www .ja v a2 s.co m // XSLT if ident needs to be changed final String changeIdXSLT = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" + "<xsl:param name=\"surveyId\"/>" + "<xsl:template match=\"@*|node()\">" + "<xsl:copy>" + "<xsl:apply-templates select=\"@*|node()\"/>" + "</xsl:copy>" + "</xsl:template>" + "<xsl:template match=\"@id\">" + "<xsl:attribute name=\"id\">" + "<xsl:value-of select=\"$surveyId\"/>" + "</xsl:attribute>" + "</xsl:template>" + "</xsl:stylesheet>"; //FileBody fb = null; ContentType ct = null; MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); String urlString = null; HttpHost targetHost = null; if (encrypted) { urlString = "https://" + hostname + "/submission"; targetHost = new HttpHost(hostname, 443, "https"); parent.appendToStatus(" Using https"); //credsProvider.setCredentials( // new AuthScope(hostname, 443, "smap", "digest"), // new UsernamePasswordCredentials(user, password)); credsProvider.setCredentials(new AuthScope(hostname, 443, "smap", "basic"), new UsernamePasswordCredentials(user, password)); } else { urlString = "http://" + hostname + "/submission"; targetHost = new HttpHost(hostname, 80, "http"); parent.appendToStatus(" Using http (not encrypted)"); credsProvider.setCredentials(new AuthScope(hostname, 80, "smap", "digest"), new UsernamePasswordCredentials(user, password)); } CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); // get instance file File instanceFile = new File(instanceFilePath); if (!instanceFile.exists()) { parent.appendToStatus(" Error: Submission file " + instanceFilePath + " does not exist"); } else { HttpPost req = new HttpPost(URI.create(urlString)); //req.setHeader("form_status", status); // smap add form_status header tempFile = populateRequest(parent, status, instanceFilePath, req, changeIdXSLT, ct, entityBuilder, newIdent); // find all files in parent directory /* File[] allFiles = instanceFile.getParentFile().listFiles(); // add media files ignoring invisible files and the submission file List<File> files = new ArrayList<File>(); for (File f : allFiles) { String fileName = f.getName(); if (!fileName.startsWith(".") && !fileName.equals(instanceFile.getName())) { // ignore invisible files and instance xml file files.add(f); } } */ // add the submission file first... /* ct = ContentType.create("text/xml"); //fb = new FileBody(instanceFile, ct); entity.addBinaryBody("xml_submission_file", instanceFile, ct, instanceFile.getPath()); //entity.addPart("xml_submission_file", fb); */ /* for (int j = 0; j < files.size(); j++) { File f = files.get(j); String fileName = f.getName(); int idx = fileName.lastIndexOf("."); String extension = ""; if (idx != -1) { extension = fileName.substring(idx + 1); } // we will be processing every one of these, so // we only need to deal with the content type determination... if (extension.equals("xml")) { ct = ContentType.create("text/xml"); } else if (extension.equals("jpg")) { ct = ContentType.create("image/jpeg"); } else if (extension.equals("3gp")) { ct = ContentType.create("video/3gp"); } else if (extension.equals("3ga")) { ct = ContentType.create("audio/3ga"); } else if (extension.equals("mp4")) { ct = ContentType.create("video/mp4"); } else if (extension.equals("m4a")) { ct = ContentType.create("audio/m4a"); }else if (extension.equals("csv")) { ct = ContentType.create("text/csv"); } else if (f.getName().endsWith(".amr")) { ct = ContentType.create("audio/amr"); } else if (extension.equals("xls")) { ct = ContentType.create("application/vnd.ms-excel"); } else { ct = ContentType.create("application/octet-stream"); parent.appendToStatus(" Info: unrecognised content type for extension " + extension); } //fb = new FileBody(f, ct); //entity.addPart(f.getName(), fb); entity.addBinaryBody(f.getName(), f, ct, f.getName()); parent.appendToStatus(" Info: added file " + f.getName()); } */ //req.setEntity(entity.build()); // prepare response and return uploaded HttpResponse response = null; try { // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate DIGEST scheme object, initialize it and add it to the local auth cache DigestScheme digestAuth = new DigestScheme(); // Suppose we already know the realm name digestAuth.overrideParamter("realm", "smap"); // Suppose we already know the expected nonce value digestAuth.overrideParamter("nonce", "whatever"); authCache.put(targetHost, digestAuth); // Generate Basic scheme object BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); parent.appendToStatus(" Info: submitting to: " + req.getURI().toString()); response = httpclient.execute(targetHost, req, localContext); int responseCode = response.getStatusLine().getStatusCode(); try { // have to read the stream in order to reuse the connection InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) ; is.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } // verify that the response was a 201 or 202. // If it wasn't, the submission has failed. parent.appendToStatus(" Info: Response code: " + responseCode + " : " + response.getStatusLine().getReasonPhrase()); if (responseCode != HttpStatus.SC_CREATED && responseCode != HttpStatus.SC_ACCEPTED) { parent.appendToStatus(" Error: upload failed: "); } else { submit_status = true; } } catch (Exception e) { e.printStackTrace(); parent.appendToStatus(" Error: Generic Exception. " + e.toString()); } } try { httpclient.close(); } catch (Exception e) { } finally { } if (tempFile != null) { tempFile.delete(); } return submit_status; }
From source file:org.orderofthebee.addons.support.tools.share.AbstractLogFileWebScript.java
protected void streamRangeBytes(final Range r, final InputStream is, final OutputStream os, final long offset) throws IOException { if (r.start != 0L && r.start > offset) { final long skipped = offset + is.skip(r.start - offset); if (skipped < r.start) { // Nothing left to download! return; }/*from w ww .ja v a2 s . c o m*/ } final long span = (r.end - r.start) + 1L; long bytesLeft = span; int read = 0; // Check that bytesLeft isn't greater than int can hold int bufSize; if (bytesLeft >= Integer.MAX_VALUE - 8) { bufSize = CHUNKSIZE; } else { bufSize = ((int) bytesLeft) < CHUNKSIZE ? (int) bytesLeft : CHUNKSIZE; } byte[] buf = new byte[bufSize]; while ((read = is.read(buf)) > 0 && bytesLeft != 0L) { os.write(buf, 0, read); bytesLeft -= read; if (bytesLeft != 0L) { int resize; if (bytesLeft >= Integer.MAX_VALUE - 8) { resize = CHUNKSIZE; } else { resize = ((int) bytesLeft) < CHUNKSIZE ? (int) bytesLeft : CHUNKSIZE; } if (resize != buf.length) { buf = new byte[resize]; } } if (LOGGER.isTraceEnabled()) { LOGGER.trace("...wrote " + read + " bytes, with " + bytesLeft + " to go..."); } } }
From source file:net.padaf.preflight.helpers.StreamValidationHelper.java
protected void checkStreamLength(DocumentHandler handler, COSObject cObj, List<ValidationError> result) throws ValidationException { COSStream streamObj = (COSStream) cObj.getObject(); int length = streamObj.getInt(COSName.getPDFName(STREAM_DICTIONARY_KEY_LENGHT)); InputStream ra = null; try {//from w w w . java 2s . c o m ra = handler.getSource().getInputStream(); Integer offset = (Integer) handler.getDocument().getDocument().getXrefTable() .get(new COSObjectKey(cObj)); // ---- go to the beginning of the object long skipped = 0; while (skipped != offset) { long curSkip = ra.skip(offset - skipped); if (curSkip < 0) { throw new ValidationException("Unable to skip bytes in the PDFFile to check stream length"); } skipped += curSkip; } // ---- go to the stream key word if (readUntilStream(ra)) { int c = ra.read(); if (c == '\r') { ra.read(); } // else c is '\n' no more character to read // ---- Here is the true beginning of the Stream Content. // ---- Read the given length of bytes and check the 10 next bytes // ---- to see if there are endstream. byte[] buffer = new byte[1024]; int nbBytesToRead = length; do { int cr = 0; if (nbBytesToRead > 1024) { cr = ra.read(buffer, 0, 1024); } else { cr = ra.read(buffer, 0, nbBytesToRead); } if (cr == -1) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); return; } else { nbBytesToRead = nbBytesToRead - cr; } } while (nbBytesToRead > 0); int len = "endstream".length() + 2; byte[] buffer2 = new byte[len]; for (int i = 0; i < len; ++i) { buffer2[i] = (byte) ra.read(); } // ---- check the content of 10 last characters String endStream = new String(buffer2); if (buffer2[0] == '\r' && buffer2[1] == '\n') { if (!endStream.contains("endstream")) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else if (buffer2[0] == '\r' && buffer2[1] == 'e') { if (!endStream.contains("endstream")) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else if (buffer2[0] == '\n' && buffer2[1] == 'e') { if (!endStream.contains("endstream")) { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } else { result.add(new ValidationResult.ValidationError( ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_INVALID, "Stream length is invalide")); } } catch (IOException e) { throw new ValidationException("Unable to read a stream to validate it due to : " + e.getMessage(), e); } finally { if (ra != null) { IOUtils.closeQuietly(ra); } } }