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.louding.frame.http.download.FileEntityHandler.java
public File handleEntity(HttpEntity entity, DownloadProgress callback, File save, boolean isResume) throws IOException { long current = 0; RandomAccessFile file = new RandomAccessFile(save, "rw"); if (isResume) { current = file.length();//from w ww.j av a2s . c om } InputStream input = entity.getContent(); long count = entity.getContentLength() + current; if (mStop) { FileUtils.closeIO(file); return save; } // ??????? /** * <br> * current = input.skip(current); <br> * file.seek(current); <br> * ?JDKInputstream.skip(long i)i<br> * ? n ??????? */ file.seek(input.skip(current)); int readLen = 0; byte[] buffer = new byte[1024]; while ((readLen = input.read(buffer, 0, 1024)) != -1) { if (mStop) { break; } else { file.write(buffer, 0, readLen); current += readLen; callback.onProgress(count, current); } } callback.onProgress(count, current); if (mStop && current < count) { // ? FileUtils.closeIO(file); throw new IOException("user stop download thread"); } FileUtils.closeIO(file); return save; }
From source file:bjerne.gallery.controller.GalleryController.java
/** * Method used to return the binary of a gallery file ( * {@link GalleryFile#getActualFile()} ). This method handles 304 redirects * (if file has not changed) and range headers if requested by browser. The * range parts is particularly important for videos. The correct response * status is set depending on the circumstances. * <p>/*from w ww . j a v a 2s . c o m*/ * NOTE: the range logic should NOT be considered a complete implementation * - it's a bare minimum for making requests for byte ranges work. * * @param request * Request * @param galleryFile * Gallery file * @return The binary of the gallery file, or a 304 redirect, or a part of * the file. * @throws IOException * If there is an issue accessing the binary file. */ private ResponseEntity<InputStreamResource> returnResource(WebRequest request, GalleryFile galleryFile) throws IOException { LOG.debug("Entering returnResource()"); if (request.checkNotModified(galleryFile.getActualFile().lastModified())) { return null; } File file = galleryFile.getActualFile(); String contentType = galleryFile.getContentType(); String rangeHeader = request.getHeader(HttpHeaders.RANGE); long[] ranges = getRangesFromHeader(rangeHeader); long startPosition = ranges[0]; long fileTotalSize = file.length(); long endPosition = ranges[1] != 0 ? ranges[1] : fileTotalSize - 1; long contentLength = endPosition - startPosition + 1; LOG.debug("contentLength: {}, file length: {}", contentLength, fileTotalSize); LOG.debug("Returning resource {} as inputstream. Start position: {}", file.getCanonicalPath(), startPosition); InputStream boundedInputStream = new BoundedInputStream(new FileInputStream(file), endPosition + 1); InputStream is = new BufferedInputStream(boundedInputStream, 65536); InputStreamResource inputStreamResource = new InputStreamResource(is); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentLength(contentLength); responseHeaders.setContentType(MediaType.valueOf(contentType)); responseHeaders.add(HttpHeaders.ACCEPT_RANGES, "bytes"); if (StringUtils.isNotBlank(rangeHeader)) { is.skip(startPosition); String contentRangeResponseHeader = "bytes " + startPosition + "-" + endPosition + "/" + fileTotalSize; responseHeaders.add(HttpHeaders.CONTENT_RANGE, contentRangeResponseHeader); LOG.debug("{} was not null but {}. Adding header {} to response: {}", HttpHeaders.RANGE, rangeHeader, HttpHeaders.CONTENT_RANGE, contentRangeResponseHeader); } HttpStatus status = (startPosition == 0 && contentLength == fileTotalSize) ? HttpStatus.OK : HttpStatus.PARTIAL_CONTENT; LOG.debug("Returning {}. Status: {}, content-type: {}, {}: {}, contentLength: {}", file, status, contentType, HttpHeaders.CONTENT_RANGE, responseHeaders.get(HttpHeaders.CONTENT_RANGE), contentLength); return new ResponseEntity<InputStreamResource>(inputStreamResource, responseHeaders, status); }
From source file:org.openhab.binding.samsungtv.internal.protocol.RemoteControllerLegacy.java
/** * Open Connection to Samsung TV.//from w ww . ja v a 2 s .co m * * @throws RemoteControllerException */ @Override public void openConnection() throws RemoteControllerException { logger.debug("Open connection to host '{}:{}'", host, port); Socket localsocket = new Socket(); socket = localsocket; try { socket.connect(new InetSocketAddress(host, port), CONNECTION_TIMEOUT); } catch (IOException e) { logger.debug("Cannot connect to Legacy Remote Controller: {}", e.getMessage()); throw new RemoteControllerException("Connection failed", e); } InputStream inputStream; try { BufferedWriter localwriter = new BufferedWriter(new OutputStreamWriter(localsocket.getOutputStream())); writer = localwriter; inputStream = localsocket.getInputStream(); InputStreamReader localreader = new InputStreamReader(inputStream); reader = localreader; logger.debug("Connection successfully opened...querying access"); writeInitialInfo(localwriter, localsocket); readInitialInfo(localreader); int i; while ((i = inputStream.available()) > 0) { inputStream.skip(i); } } catch (IOException e) { throw new RemoteControllerException(e); } }
From source file:org.scilla.util.PartialContentHandler.java
/** * Process servlet request. Determine if request is a * request for partial content and write the needed headers * and status back to the client and write the request bytes * range. If the request is not for partial content, just * write all data.// w w w . ja v a2s. c om * @param request HTTP request object * @param response HTTP response object * @param in stream to read data from * @param len length of data to be write or <tt>-1</tt> if unknown, * in which case partial content request are handled as normal requests * @throws IOException when reading or writing fails */ public static void process(HttpServletRequest request, HttpServletResponse response, InputStream in, long len) throws IOException { OutputStream out = response.getOutputStream(); // can only do partial content when length is unknown if (len != -1) { String rangeHeader = request.getHeader(RANGE_HEADER); // was partial content requested? if (rangeHeader != null && rangeHeader.startsWith(BYTE_RANGE)) { String byteSpec = rangeHeader.substring(BYTE_RANGE.length()); int sepPos = byteSpec.indexOf('-'); // does the byte spec describe a range? if (sepPos != -1) { long offset = 0; long endpoint = -1; // determine offset if (sepPos > 0) { String s = byteSpec.substring(0, sepPos).trim(); offset = Integer.parseInt(s); } // determine endpoint if (sepPos != byteSpec.length() - 1) { String s = byteSpec.substring(sepPos + 1).trim(); endpoint = Integer.parseInt(s); } else { endpoint = len - 1; } // notify receiver this is partial content response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); String contentRange = BYTES_UNIT + " " + offset + "-" + endpoint + "/" + len; response.setHeader(CONTENT_RANGE_HEADER, contentRange); log.debug("send range header: " + CONTENT_RANGE_HEADER + ": " + contentRange); response.setContentLength((int) (endpoint - offset + 1)); // skip till offset if (offset > 0) { in.skip(offset); } // write partial data int n; byte[] b = new byte[BUFFER_SIZE]; while ((n = in.read(b)) != -1) { if (endpoint != -1) { if (offset + n > endpoint) { n = (int) (endpoint - offset) + 1; if (n > 0) { out.write(b, 0, n); } break; } offset += n; } out.write(b, 0, n); } // done return; } log.info("didn't understand request.. treat as normal request"); if (log.isDebugEnabled()) { logHeaders(request); } } // inform client of data size response.setContentLength((int) len); } // write all content to client int n; byte[] b = new byte[BUFFER_SIZE]; while ((n = in.read(b)) != -1) { out.write(b, 0, n); } }
From source file:org.apache.fontbox.ttf.TTFSubFont.java
private byte[] buildHmtxTable() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); LOG.debug("Building table [hmtx]..."); HorizontalHeaderTable h = this.baseTTF.getHorizontalHeader(); HorizontalMetricsTable hm = this.baseTTF.getHorizontalMetrics(); byte[] buf = new byte[4]; InputStream is = this.baseTTF.getOriginalData(); try {//from w ww. j av a 2 s. c o m is.skip(hm.getOffset()); long lastOff = 0; for (Integer glyphId : this.glyphIds) { // offset in original file. long off; if (glyphId < h.getNumberOfHMetrics()) { off = glyphId * 4; } else { off = h.getNumberOfHMetrics() * 4 + (glyphId - h.getNumberOfHMetrics()) * 2; } // skip over from last original offset. if (off != lastOff) { long nskip = off - lastOff; if (nskip != is.skip(nskip)) { throw new EOFException("Unexpected EOF exception parsing glyphId of hmtx table."); } } // read left side bearings only, if we are beyond numOfHMetrics. int n = glyphId < h.getNumberOfHMetrics() ? 4 : 2; if (n != is.read(buf, 0, n)) { throw new EOFException("Unexpected EOF exception parsing glyphId of hmtx table."); } bos.write(buf, 0, n); lastOff = off + n; } LOG.debug("Finished table [hmtx]."); return bos.toByteArray(); } finally { is.close(); } }
From source file:org.apache.fontbox.ttf.TTFSubsetter.java
private byte[] buildGlyfTable(long[] newOffsets) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); GlyphTable g = ttf.getGlyph();// w w w. jav a2 s . c om long[] offsets = ttf.getIndexToLocation().getOffsets(); InputStream is = ttf.getOriginalData(); try { is.skip(g.getOffset()); long prevEnd = 0; // previously read glyph offset long newOffset = 0; // new offset for the glyph in the subset font int newGid = 0; // new GID in subset font // for each glyph in the subset for (Integer gid : glyphIds) { long offset = offsets[gid]; long length = offsets[gid + 1] - offset; newOffsets[newGid++] = newOffset; is.skip(offset - prevEnd); byte[] buf = new byte[(int) length]; is.read(buf); // detect glyph type if (buf.length >= 2 && buf[0] == -1 && buf[1] == -1) { // compound glyph int off = 2 * 5; int flags; do { // flags flags = (buf[off] & 0xff) << 8 | buf[off + 1] & 0xff; off += 2; // glyphIndex int componentGid = (buf[off] & 0xff) << 8 | buf[off + 1] & 0xff; if (!glyphIds.contains(componentGid)) { glyphIds.add(componentGid); } int newComponentGid = getNewGlyphId(componentGid); buf[off] = (byte) (newComponentGid >>> 8); buf[off + 1] = (byte) newComponentGid; 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; } } while ((flags & 1 << 5) != 0); // MORE_COMPONENTS // WE_HAVE_INSTRUCTIONS if ((flags & 0x0100) == 0x0100) { // USHORT numInstr int numInstr = (buf[off] & 0xff) << 8 | buf[off + 1] & 0xff; off += 2; // BYTE instr[numInstr] off += numInstr; } // write the compound glyph bos.write(buf, 0, off); // offset to start next glyph newOffset += off; } else if (buf.length > 0) { // copy the entire glyph bos.write(buf, 0, buf.length); // offset to start next glyph newOffset += buf.length; } // 4-byte alignment if (newOffset % 4 != 0) { int len = 4 - (int) (newOffset % 4); bos.write(PAD_BUF, 0, len); newOffset += len; } prevEnd = offset + length; } newOffsets[newGid++] = newOffset; } finally { is.close(); } return bos.toByteArray(); }
From source file:org.apache.fontbox.ttf.TTFSubsetter.java
/** * Resolve compound glyph references.//from w ww .ja v a 2 s .c om */ private void addCompoundReferences() throws IOException { if (hasAddedCompoundReferences) { return; } hasAddedCompoundReferences = true; boolean hasNested; do { GlyphTable g = ttf.getGlyph(); long[] offsets = ttf.getIndexToLocation().getOffsets(); InputStream is = ttf.getOriginalData(); Set<Integer> glyphIdsToAdd = null; try { is.skip(g.getOffset()); long lastOff = 0L; for (Integer glyphId : glyphIds) { long offset = offsets[glyphId]; long len = offsets[glyphId + 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; do { flags = (buf[off] & 0xff) << 8 | buf[off + 1] & 0xff; off += 2; int ogid = (buf[off] & 0xff) << 8 | buf[off + 1] & 0xff; if (!glyphIds.contains(ogid)) { 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; } } while ((flags & 1 << 5) != 0); // MORE_COMPONENTS } lastOff = offsets[glyphId + 1]; } } finally { is.close(); } if (glyphIdsToAdd != null) { glyphIds.addAll(glyphIdsToAdd); } hasNested = glyphIdsToAdd != null; } while (hasNested); }
From source file:org.musa.payload.MechanicusTeleportReceiver.java
public SpaceMarine deserialize(InputStream in) throws IOException { String name = readString(in); System.out.println("name == " + name); String chapter = readString(in); System.out.println("chapter == " + chapter); int kills = Integer.parseInt(readString(in)); System.out.println("kills == " + kills); SMRank rank = SMRank.valueOf(readString(in)); System.out.println("rank == " + rank.name()); SMLoyalty loyalty = SMLoyalty.valueOf(readString(in)); System.out.println("loyalty == " + loyalty.name()); SMStatus status = SMStatus.valueOf(readString(in)); System.out.println("status == " + status.name()); //public SpaceMarine(String name, String chapter, int kills, SMRank rank, SMLoyalty loyalty, int damage) int damage = Integer.parseInt(readString(in)); System.out.println("damage == " + damage); SpaceMarine spacemarine = new SpaceMarine(name, chapter, kills, rank, loyalty, damage); int b = in.available(); in.skip(b); return spacemarine; }
From source file:com.mpower.mintel.android.tasks.InstanceUploaderTask.java
@Override protected HashMap<String, String> doInBackground(Long... values) { mResults = new HashMap<String, String>(); String postResponse;/*www . java 2 s . c o m*/ String selection = InstanceColumns._ID + "=?"; String[] selectionArgs = new String[values.length]; for (int i = 0; i < values.length; i++) { if (i != values.length - 1) { selection += " or " + InstanceColumns._ID + "=?"; } selectionArgs[i] = values[i].toString(); } // get shared HttpContext so that authentication and cookies are // retained. HttpContext localContext = MIntel.getInstance().getHttpContext(); HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT); Map<URI, URI> uriRemap = new HashMap<URI, URI>(); 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()); String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); String id = c.getString(c.getColumnIndex(InstanceColumns._ID)); Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id); String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI)); if (urlString == null) { SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(MIntel.getInstance()); urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null); urlString = urlString + WebUtils.URL_PART_SUBMISSION; } ContentValues cv = new ContentValues(); URI u = null; try { URL url = new URL(URLDecoder.decode(urlString, "utf-8")); u = url.toURI(); } catch (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 (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 (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 HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u); // prepare response HttpResponse response = null; try { response = httpclient.execute(httpHead, localContext); 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) { Header[] locations = response.getHeaders("Location"); if (locations != null && locations.length == 1) { try { URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8")); 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 (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 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(); } 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 (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 (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 (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 (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 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 File[] allFiles = instanceFile.getParentFile().listFiles(); // add media files List<File> files = new ArrayList<File>(); for (File f : allFiles) { String fileName = f.getName(); 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; HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth); MimeTypeMap m = MimeTypeMap.getSingleton(); long byteCount = 0L; // mime post 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++) { File f = files.get(j); String fileName = f.getName(); 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 { StringBody sb = new StringBody("yes", Charset.forName("UTF-8")); entity.addPart("*isIncomplete*", sb); } catch (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); 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(); // } HttpEntity httpEntity = response.getEntity(); try { postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim(); } catch (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 (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:com.autoupdater.server.controllers.FrontEndAPIController.java
/** * Send file to client./*w w w . j a v a2 s . c o m*/ * * Runs on GET /server/api/download/{updateID} request. * * @param updateID * update's ID * @param response * response to be sent * @param request * received by servlet */ @SuppressWarnings("resource") @RequestMapping(value = "/download/{updateID}", method = GET) public @ResponseBody void getFile(@PathVariable("updateID") int updateID, HttpServletResponse response, HttpServletRequest request) { InputStream is = null; try { logger.debug("Received request: GET /api/download/" + updateID); Update update = updateService.findById(updateID); if (update == null) { logger.debug("Response 404, Update not found for: GET /api/list_updates/" + updateID); sendError(response, SC_NOT_FOUND, "Update id=" + updateID + " not found"); return; } is = fileService.loadFile(update.getFileData()); String range = request.getHeader("Range"); long skip = 0; if (range != null) { logger.debug("Values of range header : " + range); range = range.substring("bytes=".length()); skip = parseLong(range); is.skip(skip); } response.setContentType(update.getFileType()); response.setContentLength((int) (update.getFileSize() - skip)); logger.debug("Sending file on request: GET /api/download/" + updateID); copy(is, response.getOutputStream()); response.flushBuffer(); } catch (NumberFormatException | IOException e) { logger.error("Error sending file updateID=" + updateID + ": " + e); sendError(response, SC_INTERNAL_SERVER_ERROR, "Couldn't prepare file to send"); } finally { if (is != null) try { is.close(); } catch (IOException e) { logger.debug(e); } } }