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:com.mpower.daktar.android.tasks.InstanceUploaderTask.java
@Override protected HashMap<String, String> doInBackground(final Long... values) { mResults = new HashMap<String, String>(); String postResponse;/* www. j av a 2 s . com*/ String selection = BaseColumns._ID + "=?"; final String[] selectionArgs = new String[values.length]; for (int i = 0; i < values.length; i++) { if (i != values.length - 1) { selection += " or " + BaseColumns._ID + "=?"; } selectionArgs[i] = values[i].toString(); } // get shared HttpContext so that authentication and cookies are // retained. final HttpContext localContext = MIntel.getInstance().getHttpContext(); final HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT); final Map<URI, URI> uriRemap = new HashMap<URI, URI>(); final Cursor c = MIntel.getInstance().getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (c.getCount() > 0) { c.moveToPosition(-1); next_submission: while (c.moveToNext()) { if (isCancelled()) return mResults; publishProgress(c.getPosition() + 1, c.getCount()); final String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); final String id = c.getString(c.getColumnIndex(BaseColumns._ID)); final Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id); String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI)); if (urlString == null) { final SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(MIntel.getInstance()); urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null); urlString = urlString + WebUtils.URL_PART_SUBMISSION; } final ContentValues cv = new ContentValues(); URI u = null; try { final URL url = new URL(URLDecoder.decode(urlString, "utf-8")); u = url.toURI(); } catch (final MalformedURLException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final URISyntaxException e) { e.printStackTrace(); mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final UnsupportedEncodingException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } boolean openRosaServer = false; if (uriRemap.containsKey(u)) { // we already issued a head request and got a response, // so we know the proper URL to send the submission to // and the proper scheme. We also know that it was an // OpenRosa compliant server. openRosaServer = true; u = uriRemap.get(u); } else { // we need to issue a head request final HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u); // prepare response HttpResponse response = null; try { response = httpclient.execute(httpHead, localContext); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { // we need authentication, so stop and return what // we've // done so far. mAuthRequestingServer = u; return null; } else if (statusCode == 204) { final Header[] locations = response.getHeaders("Location"); if (locations != null && locations.length == 1) { try { final URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8")); final URI uNew = url.toURI(); if (u.getHost().equalsIgnoreCase(uNew.getHost())) { openRosaServer = true; // trust the server to tell us a new // location // ... and possibly to use https // instead. uriRemap.put(u, uNew); u = uNew; } else { // Don't follow a redirection attempt to // a different host. // We can't tell if this is a spoof or // not. mResults.put(id, fail + "Unexpected redirection attempt to a different host: " + uNew.toString()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } catch (final Exception e) { e.printStackTrace(); mResults.put(id, fail + urlString + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } else { // may be a server that does not handle try { // have to read the stream in order to reuse the // connection final InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) { ; } is.close(); } catch (final IOException e) { e.printStackTrace(); } catch (final Exception e) { e.printStackTrace(); } Log.w(t, "Status code on Head request: " + statusCode); if (statusCode >= 200 && statusCode <= 299) { mResults.put(id, fail + "Invalid status code on Head request. If you have a web proxy, you may need to login to your network. "); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } catch (final ClientProtocolException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Client Protocol Exception"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final ConnectTimeoutException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Connection Timeout"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final UnknownHostException e) { e.printStackTrace(); mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final Exception e) { e.printStackTrace(); mResults.put(id, fail + "Generic Exception"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } // At this point, we may have updated the uri to use https. // This occurs only if the Location header keeps the host name // the same. If it specifies a different host name, we error // out. // // And we may have set authentication cookies in our // cookiestore (referenced by localContext) that will enable // authenticated publication to the server. // // get instance file final File instanceFile = new File(instance); if (!instanceFile.exists()) { mResults.put(id, fail + "instance XML file does not exist!"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } // find all files in parent directory final File[] allFiles = instanceFile.getParentFile().listFiles(); // add media files final List<File> files = new ArrayList<File>(); for (final File f : allFiles) { final String fileName = f.getName(); final int dotIndex = fileName.lastIndexOf("."); String extension = ""; if (dotIndex != -1) { extension = fileName.substring(dotIndex + 1); } if (fileName.startsWith(".")) { // ignore invisible files continue; } if (fileName.equals(instanceFile.getName())) { continue; // the xml file has already been added } else if (openRosaServer) { files.add(f); } else if (extension.equals("jpg")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gpp")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gp")) { // legacy 0.9x files.add(f); } else if (extension.equals("mp4")) { // legacy 0.9x files.add(f); } else if (extension.equals("amr")) { // legacy 0.9x files.add(f); } else { Log.w(t, "unrecognized file type " + f.getName()); } } postResponse = ""; boolean first = true; int j = 0; while (j < files.size() || first) { first = false; final HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth); final MimeTypeMap m = MimeTypeMap.getSingleton(); long byteCount = 0L; // mime post final MultipartEntity entity = new MultipartEntity(); // add the submission file first... FileBody fb = new FileBody(instanceFile, "text/xml"); entity.addPart("xml_submission_file", fb); Log.i(t, "added xml_submission_file: " + instanceFile.getName()); byteCount += instanceFile.length(); for (; j < files.size(); j++) { final File f = files.get(j); final String fileName = f.getName(); final int idx = fileName.lastIndexOf("."); String extension = ""; if (idx != -1) { extension = fileName.substring(idx + 1); } String contentType = m.getMimeTypeFromExtension(extension); // we will be processing every one of these, so // we only need to deal with the content type // determination... if (extension.equals("xml")) { fb = new FileBody(f, "text/xml"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xml file " + f.getName()); } else if (extension.equals("jpg")) { fb = new FileBody(f, "image/jpeg"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added image file " + f.getName()); } else if (extension.equals("3gpp")) { fb = new FileBody(f, "audio/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("3gp")) { fb = new FileBody(f, "video/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("mp4")) { fb = new FileBody(f, "video/mp4"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("csv")) { fb = new FileBody(f, "text/csv"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added csv file " + f.getName()); } else if (f.getName().endsWith(".amr")) { fb = new FileBody(f, "audio/amr"); entity.addPart(f.getName(), fb); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("xls")) { fb = new FileBody(f, "application/vnd.ms-excel"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xls file " + f.getName()); } else if (contentType != null) { fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added recognized filetype (" + contentType + ") " + f.getName()); } else { contentType = "application/octet-stream"; fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName()); } // we've added at least one attachment to the request... if (j + 1 < files.size()) { if (byteCount + files.get(j + 1).length() > 10000000L) { // the next file would exceed the 10MB // threshold... Log.i(t, "Extremely long post is being split into multiple posts"); try { final StringBody sb = new StringBody("yes", Charset.forName("UTF-8")); entity.addPart("*isIncomplete*", sb); } catch (final Exception e) { e.printStackTrace(); // never happens... } ++j; // advance over the last attachment // added... break; } } } httppost.setEntity(entity); // prepare response and return uploaded HttpResponse response = null; try { response = httpclient.execute(httppost, localContext); final 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(); // } final HttpEntity httpEntity = response.getEntity(); try { postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim(); } catch (final IOException e) { e.printStackTrace(); } Log.i(t, "Response code:" + responseCode); // verify that the response was a 201 or 202. // If it wasn't, the submission has failed. if (responseCode != 201 && responseCode != 202) { if (responseCode == 200) { mResults.put(id, fail + "Network login failure? Again?"); } else { if (postResponse.length() > 0) { mResults.put(id, postResponse); } else { mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " (" + responseCode + ") at " + urlString); } } cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } catch (final Exception e) { e.printStackTrace(); mResults.put(id, fail + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } // if it got here, it must have worked if (postResponse.length() > 0) { // Custom msg from server mResults.put(id, postResponse); } else { // There is no response from server, use default string mResults.put(id, MIntel.getInstance().getString(R.string.success)); } // mResults.put(id, // MIntel.getInstance().getString(R.string.success)); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); } if (c != null) { c.close(); } } // end while return mResults; }
From source file:org.apache.fontbox.ttf.TTFSubFont.java
private boolean addCompoundReferences() throws IOException { GlyphTable g = this.baseTTF.getGlyph(); long[] offsets = this.baseTTF.getIndexToLocation().getOffsets(); InputStream is = this.baseTTF.getOriginalData(); Set<Integer> glyphIdsToAdd = null; try {//from w w w . j a v a 2 s. c o m is.skip(g.getOffset()); long lastOff = 0L; for (Integer glyphId : this.glyphIds) { long offset = offsets[glyphId.intValue()]; long len = offsets[glyphId.intValue() + 1] - offset; is.skip(offset - lastOff); byte[] buf = new byte[(int) len]; is.read(buf); // rewrite glyphIds for compound glyphs if (buf.length >= 2 && buf[0] == -1 && buf[1] == -1) { int off = 2 * 5; int flags = 0; do { flags = ((((int) buf[off]) & 0xff) << 8) | (buf[off + 1] & 0xff); off += 2; int ogid = ((((int) buf[off]) & 0xff) << 8) | (buf[off + 1] & 0xff); if (!this.glyphIds.contains(ogid)) { LOG.debug("Adding referenced glyph " + ogid + " of compound glyph " + glyphId); if (glyphIdsToAdd == null) { glyphIdsToAdd = new TreeSet<Integer>(); } glyphIdsToAdd.add(ogid); } off += 2; // ARG_1_AND_2_ARE_WORDS if ((flags & (1 << 0)) != 0) { off += 2 * 2; } else { off += 2; } // WE_HAVE_A_TWO_BY_TWO if ((flags & (1 << 7)) != 0) { off += 2 * 4; } // WE_HAVE_AN_X_AND_Y_SCALE else if ((flags & (1 << 6)) != 0) { off += 2 * 2; } // WE_HAVE_A_SCALE else if ((flags & (1 << 3)) != 0) { off += 2; } // MORE_COMPONENTS } while ((flags & (1 << 5)) != 0); } lastOff = offsets[glyphId.intValue() + 1]; } } finally { is.close(); } if (glyphIdsToAdd != null) { this.glyphIds.addAll(glyphIdsToAdd); } return glyphIdsToAdd == null; }
From source file:org.apache.fontbox.ttf.TTFSubsetter.java
private long copyBytes(InputStream is, OutputStream os, long newOffset, long lastOffset, int count) throws IOException { // skip over from last original offset long nskip = newOffset - lastOffset; if (nskip != is.skip(nskip)) { throw new EOFException("Unexpected EOF exception parsing glyphId of hmtx table."); }/*from w w w . jav a 2 s.c om*/ byte[] buf = new byte[count]; if (count != is.read(buf, 0, count)) { throw new EOFException("Unexpected EOF exception parsing glyphId of hmtx table."); } os.write(buf, 0, count); return newOffset + count; }
From source file:org.apache.fontbox.ttf.TTFSubFont.java
private byte[] buildGlyfTable(long[] newOffsets) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); LOG.debug("Building table [glyf]..."); GlyphTable g = this.baseTTF.getGlyph(); long[] offsets = this.baseTTF.getIndexToLocation().getOffsets(); InputStream is = this.baseTTF.getOriginalData(); try {// w w w . j a v a 2s . c om is.skip(g.getOffset()); long lastOff = 0L; long newOff = 0L; int ioff = 0; for (Integer glyphId : this.glyphIds) { long offset = offsets[glyphId.intValue()]; long len = offsets[glyphId.intValue() + 1] - offset; newOffsets[ioff++] = newOff; is.skip(offset - lastOff); byte[] buf = new byte[(int) len]; is.read(buf); // rewrite glyphIds for compound glyphs if (buf.length >= 2 && buf[0] == -1 && buf[1] == -1) { LOG.debug("Compound glyph " + glyphId); int off = 2 * 5; int flags = 0; do { // clear the WE_HAVE_INSTRUCTIONS bit. (bit 8 is lsb of the first byte) buf[off] &= 0xfe; flags = ((((int) buf[off]) & 0xff) << 8) | ((int) buf[off + 1] & 0xff); off += 2; int ogid = ((((int) buf[off]) & 0xff) << 8) | ((int) buf[off + 1] & 0xff); if (!this.glyphIds.contains(ogid)) { this.glyphIds.add(ogid); } int ngid = this.getNewGlyphId(ogid); if (LOG.isDebugEnabled()) { LOG.debug(String.format("mapped glyph %d to %d in compound reference (flags=%04x)", ogid, ngid, flags)); } buf[off] = (byte) (ngid >>> 8); buf[off + 1] = (byte) ngid; off += 2; // ARG_1_AND_2_ARE_WORDS if ((flags & (1 << 0)) != 0) { off += 2 * 2; } else { off += 2; } // WE_HAVE_A_TWO_BY_TWO if ((flags & (1 << 7)) != 0) { off += 2 * 4; } // WE_HAVE_AN_X_AND_Y_SCALE else if ((flags & (1 << 6)) != 0) { off += 2 * 2; } // WE_HAVE_A_SCALE else if ((flags & (1 << 3)) != 0) { off += 2; } // MORE_COMPONENTS } while ((flags & (1 << 5)) != 0); // write the compound glyph bos.write(buf, 0, off); newOff += off; } else if (buf.length > 0) { /* * bail out instructions for simple glyphs, an excerpt from the specs is given below: * * int16 numberOfContours If the number of contours is positive or zero, it is a single glyph; * If the number of contours is -1, the glyph is compound * FWord xMin Minimum x for coordinate data * FWord yMin Minimum y for coordinate data * FWord xMax Maximum x for coordinate data * FWord yMax Maximum y for coordinate data * (here follow the data for the simple or compound glyph) * * Table 15: Simple glyph definition * Type Name Description * uint16 endPtsOfContours[n] Array of last points of each contour; n is the number of contours; * array entries are point indices * uint16 instructionLength Total number of bytes needed for instructions * uint8 instructions[instructionLength] Array of instructions for this glyph * uint8 flags[variable] Array of flags * uint8 or int16 xCoordinates[] Array of x-coordinates; the first is relative to (0,0), * others are relative to previous point * uint8 or int16 yCoordinates[] Array of y-coordinates; the first is relative to (0,0), * others are relative to previous point */ int numberOfContours = (((int) buf[0] & 0xff) << 8) | ((int) buf[1] & 0xff); // offset of instructionLength int off = 2 * 5 + numberOfContours * 2; // write numberOfContours, xMin, yMin, xMax, yMax, endPtsOfContours[n] bos.write(buf, 0, off); newOff += off; int instructionLength = ((((int) buf[off]) & 0xff) << 8) | ((int) buf[off + 1] & 0xff); // zarro instructions. bos.write(0); bos.write(0); newOff += 2; off += 2 + instructionLength; // flags and coordinates bos.write(buf, off, buf.length - off); newOff += buf.length - off; } if ((newOff % 4L) != 0L) { int np = (int) (4 - newOff % 4L); bos.write(PAD_BUF, 0, np); newOff += np; } lastOff = offsets[glyphId.intValue() + 1]; } newOffsets[ioff++] = newOff; } finally { is.close(); } LOG.debug("Finished table [glyf]."); return bos.toByteArray(); }
From source file:org.apache.cordova.core.FileUtils.java
/** * Read the contents of a file as binary. * This is done synchronously; the result is returned. * * @param filename The name of the file. * @param start Start position in the file. * @param end End position to stop at (exclusive). * @return Contents of the file as a byte[]. * @throws IOException//from ww w . j a v a 2 s.c o m */ private byte[] readAsBinaryHelper(String filename, int start, int end) throws IOException { int numBytesToRead = end - start; byte[] bytes = new byte[numBytesToRead]; InputStream inputStream = FileHelper.getInputStreamFromUriString(filename, cordova); int numBytesRead = 0; if (start > 0) { inputStream.skip(start); } while (numBytesToRead > 0 && (numBytesRead = inputStream.read(bytes, numBytesRead, numBytesToRead)) >= 0) { numBytesToRead -= numBytesRead; } return bytes; }
From source file:com.rjfun.cordova.httpd.NanoHTTPD.java
/** * Serves file from homeDir and its' subdirectories (only). * Uses only URI, ignores all headers and HTTP parameters. */// www .ja va 2 s. c o m public Response serveFile(String uri, Properties header, AndroidFile homeDir, boolean allowDirectoryListing) { Response res = null; // Make sure we won't die of an exception later if (!homeDir.isDirectory()) res = new Response(HTTP_INTERNALERROR, MIME_PLAINTEXT, "INTERNAL ERRROR: serveFile(): given homeDir is not a directory."); if (res == null) { // Remove URL arguments uri = uri.trim().replace(File.separatorChar, '/'); if (uri.indexOf('?') >= 0) uri = uri.substring(0, uri.indexOf('?')); // Prohibit getting out of current directory if (uri.startsWith("..") || uri.endsWith("..") || uri.indexOf("../") >= 0) res = new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Won't serve ../ for security reasons."); } AndroidFile f = new AndroidFile(homeDir, uri); if (res == null && !f.exists()) res = new Response(HTTP_NOTFOUND, MIME_PLAINTEXT, "Error 404, file not found."); // List the directory, if necessary if (res == null && f.isDirectory()) { // Browsers get confused without '/' after the // directory, send a redirect. if (!uri.endsWith("/")) { uri += "/"; res = new Response(HTTP_REDIRECT, MIME_HTML, "<html><body>Redirected: <a href=\"" + uri + "\">" + uri + "</a></body></html>"); res.addHeader("Location", uri); } if (res == null) { // First try index.html and index.htm if (new AndroidFile(f, "index.html").exists()) f = new AndroidFile(homeDir, uri + "/index.html"); else if (new AndroidFile(f, "index.htm").exists()) f = new AndroidFile(homeDir, uri + "/index.htm"); // No index file, list the directory if it is readable else if (allowDirectoryListing && f.canRead()) { String[] files = f.list(); String msg = "<html><body><h1>Directory " + uri + "</h1><br/>"; if (uri.length() > 1) { String u = uri.substring(0, uri.length() - 1); int slash = u.lastIndexOf('/'); if (slash >= 0 && slash < u.length()) msg += "<b><a href=\"" + uri.substring(0, slash + 1) + "\">..</a></b><br/>"; } if (files != null) { for (int i = 0; i < files.length; ++i) { AndroidFile curFile = new AndroidFile(f, files[i]); boolean dir = curFile.isDirectory(); if (dir) { msg += "<b>"; files[i] += "/"; } msg += "<a href=\"" + encodeUri(uri + files[i]) + "\">" + files[i] + "</a>"; // Show file size if (curFile.isFile()) { long len = curFile.length(); msg += " <font size=2>("; if (len < 1024) msg += len + " bytes"; else if (len < 1024 * 1024) msg += len / 1024 + "." + (len % 1024 / 10 % 100) + " KB"; else msg += len / (1024 * 1024) + "." + len % (1024 * 1024) / 10 % 100 + " MB"; msg += ")</font>"; } msg += "<br/>"; if (dir) msg += "</b>"; } } msg += "</body></html>"; res = new Response(HTTP_OK, MIME_HTML, msg); } else { res = new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: No directory listing."); } } } try { if (res == null) { // Get MIME type from file name extension, if possible String mime = null; int dot = f.getCanonicalPath().lastIndexOf('.'); if (dot >= 0) mime = (String) theMimeTypes.get(f.getCanonicalPath().substring(dot + 1).toLowerCase()); if (mime == null) mime = MIME_DEFAULT_BINARY; // Calculate etag String etag = Integer .toHexString((f.getAbsolutePath() + f.lastModified() + "" + f.length()).hashCode()); //System.out.println( String.format("mime: %s, etag: %s", mime, etag)); // Support (simple) skipping: long startFrom = 0; long endAt = -1; String range = header.getProperty("range"); if (range != null) { if (range.startsWith("bytes=")) { range = range.substring("bytes=".length()); int minus = range.indexOf('-'); try { if (minus > 0) { startFrom = Long.parseLong(range.substring(0, minus)); endAt = Long.parseLong(range.substring(minus + 1)); } } catch (NumberFormatException nfe) { } } } // Change return code and add Content-Range header when skipping is requested long fileLen = f.length(); //System.out.println( String.format("file length: %d", fileLen)); if (range != null && startFrom >= 0) { if (startFrom >= fileLen) { res = new Response(HTTP_RANGE_NOT_SATISFIABLE, MIME_PLAINTEXT, ""); res.addHeader("Content-Range", "bytes 0-0/" + fileLen); res.addHeader("ETag", etag); } else { if (endAt < 0) endAt = fileLen - 1; long newLen = endAt - startFrom + 1; if (newLen < 0) newLen = 0; final long dataLen = newLen; //InputStream fis = new FileInputStream( f ) { // public int available() throws IOException { return (int)dataLen; } //}; InputStream fis = f.getInputStream(); fis.skip(startFrom); res = new Response(HTTP_PARTIALCONTENT, mime, fis); res.addHeader("Content-Length", "" + dataLen); res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen); res.addHeader("ETag", etag); } } else { if (etag.equals(header.getProperty("if-none-match"))) res = new Response(HTTP_NOTMODIFIED, mime, ""); else { //res = new Response( HTTP_OK, mime, new FileInputStream( f )); res = new Response(HTTP_OK, mime, f.getInputStream()); res.addHeader("Content-Length", "" + fileLen); res.addHeader("ETag", etag); } } } } catch (IOException ioe) { res = new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Reading file failed."); } res.addHeader("Accept-Ranges", "bytes"); // Announce that the file server accepts partial content requestes return res; }
From source file:com.izforge.izpack.installer.unpacker.UnpackerBase.java
/** * Skips bytes in a stream.// w w w . j a v a2s . c o m * * @param stream the stream * @param bytes the no. of bytes to skip * @throws IOException for any I/O error, or if the no. of bytes skipped doesn't match that expected */ protected void skip(InputStream stream, long bytes) throws IOException { long skipped = stream.skip(bytes); if (skipped != bytes) { throw new IOException("Expected to skip: " + bytes + " in stream but skipped: " + skipped); } }
From source file:org.apache.hadoop.crypto.CryptoStreamsTestBase.java
@Test(timeout = 120000) public void testCombinedOp() throws Exception { OutputStream out = getOutputStream(defaultBufferSize); writeData(out);// ww w . j a v a 2 s .c o m final int len1 = dataLen / 8; final int len2 = dataLen / 10; InputStream in = getInputStream(defaultBufferSize); // Read len1 data. byte[] readData = new byte[len1]; readAll(in, readData, 0, len1); byte[] expectedData = new byte[len1]; System.arraycopy(data, 0, expectedData, 0, len1); Assert.assertArrayEquals(readData, expectedData); long pos = ((Seekable) in).getPos(); Assert.assertEquals(len1, pos); // Seek forward len2 ((Seekable) in).seek(pos + len2); // Skip forward len2 long n = in.skip(len2); Assert.assertEquals(len2, n); // Pos: 1/4 dataLen positionedReadCheck(in, dataLen / 4); // Pos should be len1 + len2 + len2 pos = ((Seekable) in).getPos(); Assert.assertEquals(len1 + len2 + len2, pos); // Read forward len1 ByteBuffer buf = ByteBuffer.allocate(len1); int nRead = ((ByteBufferReadable) in).read(buf); Assert.assertEquals(nRead, buf.position()); readData = new byte[nRead]; buf.rewind(); buf.get(readData); expectedData = new byte[nRead]; System.arraycopy(data, (int) pos, expectedData, 0, nRead); Assert.assertArrayEquals(readData, expectedData); long lastPos = pos; // Pos should be lastPos + nRead pos = ((Seekable) in).getPos(); Assert.assertEquals(lastPos + nRead, pos); // Pos: 1/3 dataLen positionedReadCheck(in, dataLen / 3); // Read forward len1 readData = new byte[len1]; readAll(in, readData, 0, len1); expectedData = new byte[len1]; System.arraycopy(data, (int) pos, expectedData, 0, len1); Assert.assertArrayEquals(readData, expectedData); lastPos = pos; // Pos should be lastPos + len1 pos = ((Seekable) in).getPos(); Assert.assertEquals(lastPos + len1, pos); // Read forward len1 buf = ByteBuffer.allocate(len1); nRead = ((ByteBufferReadable) in).read(buf); Assert.assertEquals(nRead, buf.position()); readData = new byte[nRead]; buf.rewind(); buf.get(readData); expectedData = new byte[nRead]; System.arraycopy(data, (int) pos, expectedData, 0, nRead); Assert.assertArrayEquals(readData, expectedData); lastPos = pos; // Pos should be lastPos + nRead pos = ((Seekable) in).getPos(); Assert.assertEquals(lastPos + nRead, pos); // ByteBuffer read after EOF ((Seekable) in).seek(dataLen); buf.clear(); n = ((ByteBufferReadable) in).read(buf); Assert.assertEquals(n, -1); in.close(); }
From source file:ch.entwine.weblounge.common.impl.request.Http11ProtocolHandler.java
/** * Method generateResponse.// ww w. ja va 2 s. c o m * * @param resp * @param type * @param is * @return boolean * @throws IOException * if generating the response fails */ public static boolean generateResponse(HttpServletResponse resp, Http11ResponseType type, InputStream is) throws IOException { /* first generate the response headers */ generateHeaders(resp, type); /* adjust the statistics */ ++stats[STATS_BODY_GENERATED]; incResponseStats(type.type, bodyStats); /* generate the response body */ try { if (resp.isCommitted()) log.warn("Response is already committed!"); switch (type.type) { case RESPONSE_OK: if (!type.isHeaderOnly() && is != null) { resp.setBufferSize(BUFFER_SIZE); OutputStream os = null; try { os = resp.getOutputStream(); IOUtils.copy(is, os); } catch (IOException e) { if (RequestUtils.isCausedByClient(e)) return true; } finally { IOUtils.closeQuietly(os); } } break; case RESPONSE_PARTIAL_CONTENT: if (type.from < 0 || type.to < 0 || type.from > type.to || type.to > type.size) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid partial content parameters"); log.warn("Invalid partial content parameters"); } else if (!type.isHeaderOnly() && is != null) { resp.setBufferSize(BUFFER_SIZE); OutputStream os = resp.getOutputStream(); if (is.skip(type.from) != type.from) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Premature end of input stream"); log.warn("Premature end of input stream"); break; } try { /* get the temporary buffer for this thread */ byte[] tmp = buffer.get(); if (tmp == null) { tmp = new byte[BUFFER_SIZE]; buffer.set(tmp); } int read = type.to - type.from; int copy = read; int write = 0; read = is.read(tmp); while (copy > 0 && read >= 0) { copy -= read; write = copy > 0 ? read : read + copy; os.write(tmp, 0, write); stats[STATS_BYTES_WRITTEN] += write; read = is.read(tmp); } if (copy > 0) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Premature end of input stream"); log.warn("Premature end of input stream"); break; } os.flush(); os.close(); } catch (SocketException e) { log.debug("Request cancelled by client"); } } break; case RESPONSE_NOT_MODIFIED: /* NOTE: we MUST NOT return any content (RFC 2616)!!! */ break; case RESPONSE_PRECONDITION_FAILED: if (type.err == null) resp.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); else resp.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, type.err); break; case RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE: if (type.err == null) resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); else resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE, type.err); break; case RESPONSE_METHOD_NOT_ALLOWED: if (type.err == null) resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); else resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, type.err); break; case RESPONSE_INTERNAL_SERVER_ERROR: default: if (type.err == null) resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); else resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, type.err); } } catch (IOException e) { if (e instanceof EOFException) { log.debug("Request canceled by client"); return true; } ++stats[STATS_ERRORS]; String message = e.getCause() != null ? e.getCause().getMessage() : e.getMessage(); Throwable cause = e.getCause() != null ? e.getCause() : e; log.warn("I/O exception while sending response: {}", message, cause); throw e; } return true; }
From source file:de.digitalcollections.streaming.euphoria.controller.StreamingController.java
/** * Copy the given byte range of the given input to the given output. * * @param input The input to copy the given range to the given output for. * @param output The output to copy the given range from the given input for. * @param start Start of the byte range. * @param inputSize the length of the entire resource. * @param length Length of the byte range. * @throws IOException If something fails at I/O level. *//*from w w w . j a va2 s . c om*/ private void copy(InputStream input, OutputStream output, long inputSize, long start, long length) throws IOException { byte[] buffer = new byte[DEFAULT_STREAM_BUFFER_SIZE]; int read; if (inputSize == length) { LOGGER.debug("*** Response: writing FULL RANGE (from byte {} to byte {} = {} kB of total {} kB)", start, (start + length - 1), length / 1024, inputSize / 1024); stream(input, output); } else { LOGGER.debug("*** Response: writing partial range (from byte {} to byte {} = {} kB of total {} kB)", start, (start + length - 1), length / 1024, inputSize / 1024); input.skip(start); long toRead = length; while ((read = input.read(buffer)) > 0) { if ((toRead -= read) > 0) { output.write(buffer, 0, read); // output.flush(); } else { output.write(buffer, 0, (int) toRead + read); // output.flush(); break; } } } }