Example usage for java.io InputStream skip

List of usage examples for java.io InputStream skip

Introduction

In this page you can find the example usage for java.io InputStream skip.

Prototype

public long skip(long n) throws IOException 

Source Link

Document

Skips over and discards n bytes of data from this input stream.

Usage

From source file:fr.msch.wissl.server.REST.java

@GET
@Path("song/{song_id}/stream")
public Response getSong(@PathParam("song_id") final int song_id, @HeaderParam("range") final String range)
        throws SQLException, SecurityError {
    final long t1 = System.nanoTime();
    String sid = (sessionIdHeader == null ? sessionIdGet : sessionIdHeader);
    final Session s = Session.check(sid, request.getRemoteAddr(), userAgent);

    s.setLastPlayedSong(DB.get().getSong(song_id));

    final String filePath = DB.get().getSongFilePath(song_id);
    final File f = new File(filePath);

    // check the value for the 'range' http header, which
    // indicates when the client is seeking in the middle of a song
    int _startRange = 0;
    if (range != null) {
        Pattern pat = Pattern.compile("bytes=([0-9]+)-([0-9]*)");
        Matcher mat = pat.matcher(range);
        if (mat.matches()) {
            if (mat.group(1) != null) {
                _startRange = Integer.parseInt(mat.group(1));
            }/*from  ww w. ja va  2s  .c  om*/
        }
    }
    final long startRange = _startRange;
    final long endRange = f.length() - 1;
    final String contentRange = "bytes " + startRange + "-" + endRange + "/" + f.length();

    // this StreamingOutput object gives us a way to write the response to a
    // Stream,
    // which allows reading the file chunk by chunk to avoid having it all
    // in memory
    StreamingOutput stream = new StreamingOutput() {
        @Override
        public void write(OutputStream out) throws IOException, WebApplicationException {
            int totalBytes = 0;
            InputStream in = new FileInputStream(f);
            byte[] bytes = new byte[8192];
            int bytesRead;

            try {
                in.skip(startRange);
                while ((bytesRead = in.read(bytes)) != -1) {
                    totalBytes += bytesRead;
                    out.write(bytes, 0, bytesRead);
                }
            } catch (Throwable t) {
                return;
            } finally {
                RuntimeStats.get().downloaded.addAndGet(totalBytes);
                try {
                    DB.get().updateDownloadedBytes(s.getUserId(), totalBytes);
                } catch (SQLException e) {
                    Logger.error("Failed to update user stats", e);
                }
                in.close();
            }
        }
    };

    String contentType = "*/*";
    if (filePath.endsWith("mp3")) {
        contentType = "audio/mpeg";
    } else if (filePath.endsWith("mp4")) {
        contentType = "audio/aac";
    } else if (filePath.endsWith("aac")) {
        contentType = "audio/aac";
    } else if (filePath.endsWith("m4a")) {
        contentType = "audio/aac";
    } else if (filePath.endsWith("ogg")) {
        contentType = "audio/ogg";
    } else if (filePath.endsWith("wav")) {
        contentType = "audio/wav";
    }

    int status = 200;
    if (startRange > 0) {
        // seeking: HTTP 206 partial content
        status = 206;
    }

    log(s, t1);

    return Response.status(status) //
            .type(contentType) //
            .header("Content-Length", f.length() - startRange) //
            .header("Accept-Ranges", "bytes") //
            .header("Content-Range", contentRange) //
            .header("Cache-Control", "max-age=86400, must-revalidate") //
            .entity(stream) //
            .build();
}

From source file:com.radicaldynamic.groupinform.tasks.InstanceUploaderTask.java

@Override
// BEGIN custom/*from w w  w. j  a va2 s .c  o m*/
//    protected HashMap<String, String> doInBackground(Long... values) {
protected HashMap<String, String> doInBackground(String... values) {
    // END custom    
    mResults = new HashMap<String, String>();

    // BEGIN custom
    //        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();
    //        }        
    // END custom

    // get shared HttpContext so that authentication and cookies are retained.
    HttpContext localContext = Collect.getInstance().getHttpContext();
    HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT);

    Map<URI, URI> uriRemap = new HashMap<URI, URI>();

    // BEGIN custom        
    //      Cursor c =
    //      Collect.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));

    next_submission: for (int i = 0; i < values.length; i++) {
        if (isCancelled()) {
            return mResults;
        }

        publishProgress(i + 1, values.length);

        FormInstance instanceDoc = null;
        String id = values[i];

        try {
            instanceDoc = Collect.getInstance().getDbService().getDb().get(FormInstance.class, id);
        } catch (DocumentNotFoundException e) {
            if (Collect.Log.WARN)
                Log.w(Collect.LOGTAG, t + "unable to retrieve instance: " + e.toString());
            mResults.put(id, fail + "warning: document not found :: details: " + e.getMessage());
            continue;
        } catch (DbAccessException e) {
            if (Collect.Log.WARN)
                Log.w(Collect.LOGTAG, t + "unable to access database: " + e.toString());
            mResults.put(id, fail + "error: could not acess database :: details: " + e.getMessage());
            continue;
        } catch (Exception e) {
            if (Collect.Log.ERROR)
                Log.e(Collect.LOGTAG, t + "unexpected exception: " + e.toString());
            e.printStackTrace();
            mResults.put(id, fail + "unexpected error :: details: " + e.getMessage());
            continue;
        }

        String urlString = instanceDoc.getOdk().getUploadUri();
        // END custom

        if (urlString == null) {
            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(Collect.getInstance());
            urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL,
                    Collect.getInstance().getString(R.string.default_server_url));
            String submissionUrl = settings.getString(PreferencesActivity.KEY_SUBMISSION_URL, "/submission");
            urlString = urlString + submissionUrl;
        }

        @SuppressWarnings("unused")
        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());
            // BEGIN custom
            //                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
            //                    Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

            try {
                instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                Collect.getInstance().getDbService().getDb().update(instanceDoc);
            } catch (Exception e1) {
                if (Collect.Log.ERROR)
                    Log.e(Collect.LOGTAG,
                            t + ": could not record upload failed because of MalformedURLException for " + id
                                    + ": " + e1.toString());
            }
            // END custom
            continue;
        } catch (URISyntaxException e) {
            e.printStackTrace();
            mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage());
            // BEGIN custom
            //                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
            //                    Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

            try {
                instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                Collect.getInstance().getDbService().getDb().update(instanceDoc);
            } catch (Exception e1) {
                if (Collect.Log.ERROR)
                    Log.e(Collect.LOGTAG,
                            t + ": could not record upload failed because of URISyntaxException for " + id
                                    + ": " + e1.toString());
            }
            // END custom
            continue;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
            // BEGIN custom
            //                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
            //                    Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

            try {
                instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                Collect.getInstance().getDbService().getDb().update(instanceDoc);
            } catch (Exception e1) {
                if (Collect.Log.ERROR)
                    Log.e(Collect.LOGTAG,
                            t + ": could not record upload failed because of UnsupportedEncodingException for "
                                    + id + ": " + e1.toString());
            }
            // END custom
            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());
                                // BEGIN custom
                                //                                        cv.put(InstanceColumns.STATUS,
                                //                                            InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                                //                                        Collect.getInstance().getContentResolver()
                                //                                                .update(toUpdate, cv, null, null);

                                try {
                                    instanceDoc.getOdk()
                                            .setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                                    Collect.getInstance().getDbService().getDb().update(instanceDoc);
                                } catch (Exception e1) {
                                    if (Collect.Log.ERROR)
                                        Log.e(Collect.LOGTAG, t
                                                + ": could not record upload failed because of redirection error for "
                                                + id + ": " + e1.toString());
                                }
                                // END custom
                                continue;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            mResults.put(id, fail + urlString + " " + e.getMessage());
                            // BEGIN custom
                            //                                    cv.put(InstanceColumns.STATUS,
                            //                                        InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                            //                                    Collect.getInstance().getContentResolver()
                            //                                            .update(toUpdate, cv, null, null);

                            try {
                                instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                                Collect.getInstance().getDbService().getDb().update(instanceDoc);
                            } catch (Exception e1) {
                                if (Collect.Log.ERROR)
                                    Log.e(Collect.LOGTAG, t
                                            + ": could not record upload failed because of unexpected exception for "
                                            + id + ": " + e1.toString());
                            }
                            // END custom
                            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. ");
                        // BEGIN custom
                        //                                cv.put(InstanceColumns.STATUS,
                        //                                    InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                        //                                Collect.getInstance().getContentResolver()
                        //                                        .update(toUpdate, cv, null, null);

                        try {
                            instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                            Collect.getInstance().getDbService().getDb().update(instanceDoc);
                        } catch (Exception e1) {
                            if (Collect.Log.ERROR)
                                Log.e(Collect.LOGTAG, t
                                        + ": could not record upload failed because of network login error for "
                                        + id + ": " + e1.toString());
                        }
                        // END custom
                        continue;
                    }
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
                Log.e(t, e.getMessage());
                mResults.put(id, fail + "Client Protocol Exception");

                // BEGIN custom
                //                        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                //                        Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

                try {
                    instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                    Collect.getInstance().getDbService().getDb().update(instanceDoc);
                } catch (Exception e1) {
                    if (Collect.Log.ERROR)
                        Log.e(Collect.LOGTAG,
                                t + ": could not record upload failed because of client protocol exception for "
                                        + id + ": " + e1.toString());
                }
                // END custom
                continue;
            } catch (ConnectTimeoutException e) {
                e.printStackTrace();
                Log.e(t, e.getMessage());
                mResults.put(id, fail + "Connection Timeout");
                // BEGIN custom
                //                        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                //                        Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

                try {
                    instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                    Collect.getInstance().getDbService().getDb().update(instanceDoc);
                } catch (Exception e1) {
                    if (Collect.Log.ERROR)
                        Log.e(Collect.LOGTAG, t
                                + ": could not record upload failed because of connection timeout exception for "
                                + id + ": " + e1.toString());
                }
                // END custom
                continue;
            } catch (UnknownHostException e) {
                e.printStackTrace();
                mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed");
                Log.e(t, e.getMessage());
                // BEGIN custom
                //                        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                //                        Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

                try {
                    instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                    Collect.getInstance().getDbService().getDb().update(instanceDoc);
                } catch (Exception e1) {
                    if (Collect.Log.ERROR)
                        Log.e(Collect.LOGTAG,
                                t + ": could not record upload failed because of unknown host exception for "
                                        + id + ": " + e1.toString());
                }
                // END custom
                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);
                //                        Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

                try {
                    instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                    Collect.getInstance().getDbService().getDb().update(instanceDoc);
                } catch (Exception e1) {
                    if (Collect.Log.ERROR)
                        Log.e(Collect.LOGTAG, t
                                + ": could not record upload failed because of (generic) unexpected exception for "
                                + id + ": " + e1.toString());
                }
                // END custom
                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.
        //
        // BEGIN custom                
        String uploadFolder = FileUtilsExtended.ODK_UPLOAD_PATH + File.separator + UUID.randomUUID();
        FileUtils.createFolder(uploadFolder);

        try {
            HashMap<String, Attachment> attachments = (HashMap<String, Attachment>) instanceDoc
                    .getAttachments();

            // Download files from database
            for (Entry<String, Attachment> entry : attachments.entrySet()) {
                String key = entry.getKey();

                AttachmentInputStream ais = Collect.getInstance().getDbService().getDb().getAttachment(id, key);

                // ODK code below expects the XML instance to have a .xml extension
                if (key.equals("xml"))
                    key = id + ".xml";

                FileOutputStream file = new FileOutputStream(new File(uploadFolder, key));
                byte[] buffer = new byte[8192];
                int bytesRead = 0;

                while ((bytesRead = ais.read(buffer)) != -1) {
                    file.write(buffer, 0, bytesRead);
                }

                ais.close();
                file.close();
            }
        } catch (DocumentNotFoundException e) {
            if (Collect.Log.WARN)
                Log.w(Collect.LOGTAG, t + "unable to retrieve attachment: " + e.toString());
            mResults.put(id, fail + "warning: attachment not found :: details: " + e.getMessage());
            continue;
        } catch (DbAccessException e) {
            if (Collect.Log.WARN)
                Log.w(Collect.LOGTAG, t + "unable to access database: " + e.toString());
            mResults.put(id, fail + "error: could not acess database :: details: " + e.getMessage());
            continue;
        } catch (Exception e) {
            if (Collect.Log.ERROR)
                Log.e(Collect.LOGTAG, t + "unexpected exception: " + e.toString());
            e.printStackTrace();
            mResults.put(id, fail + "unexpected error :: details: " + e.getMessage());
            continue;
        }
        // END custom

        // get instance file
        // BEGIN custom
        //                File instanceFile = new File(instance);
        File instanceFile = new File(uploadFolder, id + ".xml");
        // END custom

        if (!instanceFile.exists()) {
            mResults.put(id, fail + "instance XML file does not exist!");
            // BEGIN custom
            //                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
            //                    Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

            try {
                instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                Collect.getInstance().getDbService().getDb().update(instanceDoc);
            } catch (Exception e1) {
                if (Collect.Log.ERROR)
                    Log.e(Collect.LOGTAG,
                            t + ": could not record upload failed because of missing instance file for " + id
                                    + ": " + e1.toString());
            }
            // END custom
            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 {
                Log.w(t, "unrecognized file type " + f.getName());
            }
        }

        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();
                }
                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 {
                        mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " (" + responseCode
                                + ") at " + urlString);
                    }
                    // BEGIN custom
                    //                            cv.put(InstanceColumns.STATUS,
                    //                                InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    //                            Collect.getInstance().getContentResolver()
                    //                                    .update(toUpdate, cv, null, null);

                    try {
                        instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                        Collect.getInstance().getDbService().getDb().update(instanceDoc);
                    } catch (Exception e1) {
                        if (Collect.Log.ERROR)
                            Log.e(Collect.LOGTAG,
                                    t + ": could not record upload failed because of network login error for "
                                            + id + ": " + e1.toString());
                    }
                    // END custom
                    continue next_submission;
                }
            } catch (Exception e) {
                e.printStackTrace();
                mResults.put(id, fail + "Generic Exception. " + e.getMessage());
                // BEGIN custom
                //                        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                //                        Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);

                try {
                    instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.failed);
                    Collect.getInstance().getDbService().getDb().update(instanceDoc);
                } catch (Exception e1) {
                    if (Collect.Log.ERROR)
                        Log.e(Collect.LOGTAG,
                                t + ": could not record upload failed because of generic exception for " + id
                                        + ": " + e1.toString());
                }
                // END custom
                continue next_submission;
            }
        }

        // if it got here, it must have worked
        mResults.put(id, Collect.getInstance().getString(R.string.success));
        // BEGIN custom
        //                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
        //                Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
        // END custom

        // BEGIN custom
        instanceDoc.getOdk().setUploadStatus(ODKInstanceAttributes.UploadStatus.complete);
        instanceDoc.getOdk().setUploadDate(Generic.generateTimestamp());

        try {
            Collect.getInstance().getDbService().getDb().update(instanceDoc);
        } catch (Exception e) {
            if (Collect.Log.ERROR)
                Log.e(Collect.LOGTAG, t + "unable to setUploadDate of successful upload: " + e.toString());
            e.printStackTrace();
        } finally {
            FileUtilsExtended.deleteFolder(uploadFolder);
        }
        // END custom
    }
    // BEGIN custom
    //            if (c != null) {
    //                c.close();
    //            }
    //
    //        } // end while
    // END custom

    return mResults;
}

From source file:org.kurento.repository.internal.http.RepositoryHttpServlet.java

/**
 * Copy the contents of the specified input stream to the specified output stream, and ensure that
 * both streams are closed before returning (even in the face of an exception).
 *
 * @param istream/*  w w w  .j  av a  2 s. c  o m*/
 *          The input stream to read from
 * @param ostream
 *          The output stream to write to
 * @param range
 *          Range we are copying
 *
 * @return Exception which occurred during processing
 */
protected IOException copyStreamsRange(InputStream istream, OutputStream ostream, Range range) {

    long start = range.start;
    long end = range.end;

    if (debug > 10) {
        log("Serving bytes:" + start + "-" + end);
    }

    long skipped = 0;
    try {
        skipped = istream.skip(start);
    } catch (IOException e) {
        return e;
    }
    if (skipped < start) {
        return new IOException("Has been skiped " + skipped + " when " + start + " is required");
    }

    IOException exception = null;
    long remBytes = end - start + 1;

    byte[] buffer = new byte[INPUT_BUFFER_SIZE];
    int readBytes = buffer.length;
    while (remBytes > 0) {
        try {
            readBytes = istream.read(buffer);
            if (readBytes == -1) {
                break;
            } else if (readBytes <= remBytes) {
                ostream.write(buffer, 0, readBytes);
                remBytes -= readBytes;
            } else {
                ostream.write(buffer, 0, (int) remBytes);
                break;
            }
        } catch (IOException e) {
            exception = e;
            break;
        }
    }

    return exception;
}

From source file:com.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java

/**
 * Copy the contents of the specified input stream to the specified output
 * stream, and ensure that both streams are closed before returning (even in
 * the face of an exception).//from   ww  w. j a v a 2  s  . co  m
 * 
 * @param istream
 *            The input stream to read from
 * @param ostream
 *            The output stream to write to
 * @param range
 *            Range we are copying
 *
 * @return Exception which occurred during processing
 */
protected IOException copyStreamsRange(InputStream istream, OutputStream ostream, Range range) {

    long start = range.start;
    long end = range.end;

    if (debug > 10) {
        log("Serving bytes:" + start + "-" + end);
    }

    long skipped = 0;
    try {
        skipped = istream.skip(start);
    } catch (IOException e) {
        return e;
    }
    if (skipped < start) {
        return new IOException("Has been skiped " + skipped + " when " + start + " is required");
    }

    IOException exception = null;
    long remBytes = end - start + 1;

    byte buffer[] = new byte[INPUT_BUFFER_SIZE];
    int readBytes = buffer.length;
    while (remBytes > 0) {
        try {
            readBytes = istream.read(buffer);
            if (readBytes == -1) {
                break;
            } else if (readBytes <= remBytes) {
                ostream.write(buffer, 0, readBytes);
                remBytes -= readBytes;
            } else {
                ostream.write(buffer, 0, (int) remBytes);
                break;
            }
        } catch (IOException e) {
            exception = e;
            break;
        }
    }

    return exception;
}

From source file:org.gluu.oxtrust.servlet.LogoImageServlet.java

@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse response) {
    log.debug("Starting organization logo upload");
    try {//from   ww w .j  a v  a 2  s . c  o m
        GluuOrganization organization = OrganizationService.instance().getOrganization();
        ImageService imageService = ImageService.instance();
        GluuImage image = imageService.getGluuImageFromXML(organization.getLogoImage());
        if (image != null) {
            image.setLogo(true);
        }

        OutputStream os = null;
        InputStream is = null;
        try {
            DownloadWrapper downloadWrapper = null;

            // Send customized organization logo
            if (image != null) {
                File file = imageService.getSourceFile(image);
                try {
                    is = FileUtils.openInputStream(file);
                    downloadWrapper = new DownloadWrapper(is, image.getSourceName(),
                            image.getSourceContentType(), image.getCreationDate(), (int) file.length());
                } catch (IOException ex) {
                    log.error("Organization logo image doesn't exist", ex);
                    FileDownloader.sendError(response);
                    return;
                }
            } else {
                // If customized logo doesn't exist then send default
                // organization logo
                String defaultLogoFileName = "/WEB-INF/static/images/default_logo.png";
                is = getServletContext().getResourceAsStream(defaultLogoFileName);
                if (is == null) {
                    log.error("Default organization logo image doesn't exist");
                    FileDownloader.sendError(response);
                    return;
                }

                // Calculate default logo size
                long contentLength;
                try {
                    contentLength = is.skip(Long.MAX_VALUE);
                } catch (IOException ex) {
                    log.error("Failed to calculate default organization logo image size", ex);
                    FileDownloader.sendError(response);
                    return;
                } finally {
                    IOUtils.closeQuietly(is);
                }

                is = getServletContext().getResourceAsStream(defaultLogoFileName);
                downloadWrapper = new DownloadWrapper(is, "default_logo.png", "image/png", new Date(),
                        (int) contentLength);
            }

            try {
                int logoSize = FileDownloader.writeOutput(downloadWrapper, ContentDisposition.INLINE, response);
                response.getOutputStream().flush();
                log.debug("Successfully send organization logo with size", logoSize);
            } catch (IOException ex) {
                log.error("Failed to send organization logo", ex);
                FileDownloader.sendError(response);
            }
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
    } catch (Exception ex) {
        log.error("Failed to send organization logo", ex);
    }
}

From source file:net.lightbody.bmp.proxy.jetty.http.handler.ResourceHandler.java

public void sendData(HttpRequest request, HttpResponse response, String pathInContext, Resource resource,
        boolean writeHeaders) throws IOException {
    long resLength = resource.length();

    //  see if there are any range headers
    Enumeration reqRanges = request.getDotVersion() > 0 ? request.getFieldValues(HttpFields.__Range) : null;

    if (!writeHeaders || reqRanges == null || !reqRanges.hasMoreElements()) {
        // look for a gziped content.
        Resource data = resource;
        if (_minGzipLength > 0) {
            String accept = request.getField(HttpFields.__AcceptEncoding);
            if (accept != null && resLength > _minGzipLength && !pathInContext.endsWith(".gz")) {
                Resource gz = getHttpContext().getResource(pathInContext + ".gz");
                if (gz.exists() && accept.indexOf("gzip") >= 0) {
                    if (log.isDebugEnabled())
                        log.debug("gzip=" + gz);
                    response.setField(HttpFields.__ContentEncoding, "gzip");
                    data = gz;//from w ww .  jav  a 2s .c om
                    resLength = data.length();
                }
            }
        }
        writeHeaders(response, resource, resLength);

        request.setHandled(true);
        OutputStream out = response.getOutputStream();
        data.writeTo(out, 0, resLength);
        return;
    }

    // Parse the satisfiable ranges
    List ranges = InclusiveByteRange.satisfiableRanges(reqRanges, resLength);
    if (log.isDebugEnabled())
        log.debug("ranges: " + reqRanges + " == " + ranges);

    //  if there are no satisfiable ranges, send 416 response
    if (ranges == null || ranges.size() == 0) {
        log.debug("no satisfiable ranges");
        writeHeaders(response, resource, resLength);
        response.setStatus(HttpResponse.__416_Requested_Range_Not_Satisfiable);
        response.setReason((String) HttpResponse.__statusMsg
                .get(TypeUtil.newInteger(HttpResponse.__416_Requested_Range_Not_Satisfiable)));

        response.setField(HttpFields.__ContentRange, InclusiveByteRange.to416HeaderRangeString(resLength));

        OutputStream out = response.getOutputStream();
        resource.writeTo(out, 0, resLength);
        request.setHandled(true);
        return;
    }

    //  if there is only a single valid range (must be satisfiable 
    //  since were here now), send that range with a 216 response
    if (ranges.size() == 1) {
        InclusiveByteRange singleSatisfiableRange = (InclusiveByteRange) ranges.get(0);
        if (log.isDebugEnabled())
            log.debug("single satisfiable range: " + singleSatisfiableRange);
        long singleLength = singleSatisfiableRange.getSize(resLength);
        writeHeaders(response, resource, singleLength);
        response.setStatus(HttpResponse.__206_Partial_Content);
        response.setReason(
                (String) HttpResponse.__statusMsg.get(TypeUtil.newInteger(HttpResponse.__206_Partial_Content)));
        response.setField(HttpFields.__ContentRange, singleSatisfiableRange.toHeaderRangeString(resLength));
        OutputStream out = response.getOutputStream();
        resource.writeTo(out, singleSatisfiableRange.getFirst(resLength), singleLength);
        request.setHandled(true);
        return;
    }

    //  multiple non-overlapping valid ranges cause a multipart
    //  216 response which does not require an overall 
    //  content-length header
    //
    ResourceCache.ResourceMetaData metaData = (ResourceCache.ResourceMetaData) resource.getAssociate();
    String encoding = metaData.getMimeType();
    MultiPartResponse multi = new MultiPartResponse(response);
    response.setStatus(HttpResponse.__206_Partial_Content);
    response.setReason(
            (String) HttpResponse.__statusMsg.get(TypeUtil.newInteger(HttpResponse.__206_Partial_Content)));

    // If the request has a "Request-Range" header then we need to
    // send an old style multipart/x-byteranges Content-Type. This
    // keeps Netscape and acrobat happy. This is what Apache does.
    String ctp;
    if (request.containsField(HttpFields.__RequestRange))
        ctp = "multipart/x-byteranges; boundary=";
    else
        ctp = "multipart/byteranges; boundary=";
    response.setContentType(ctp + multi.getBoundary());

    InputStream in = (resource instanceof CachedResource) ? null : resource.getInputStream();
    OutputStream out = response.getOutputStream();
    long pos = 0;

    for (int i = 0; i < ranges.size(); i++) {
        InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i);
        String header = HttpFields.__ContentRange + ": " + ibr.toHeaderRangeString(resLength);
        if (log.isDebugEnabled())
            log.debug("multi range: " + encoding + " " + header);
        multi.startPart(encoding, new String[] { header });

        long start = ibr.getFirst(resLength);
        long size = ibr.getSize(resLength);
        if (in != null) {
            // Handle non cached resource
            if (start < pos) {
                in.close();
                in = resource.getInputStream();
                pos = 0;
            }
            if (pos < start) {
                in.skip(start - pos);
                pos = start;
            }
            IO.copy(in, out, size);
            pos += size;
        } else
            // Handle cached resource
            resource.writeTo(out, start, size);

    }
    if (in != null)
        in.close();
    multi.close();

    request.setHandled(true);

    return;
}

From source file:org.jlibrary.core.jcr.modules.JCRImportExportModule.java

public void importRepository(Ticket ticket, String name, InputStream inputStream)
        throws RepositoryAlreadyExistsException, RepositoryException, SecurityException {

    try {//w ww .j ava  2s  .co  m

        if (!ticket.getUser().isAdmin()) {
            throw new SecurityException(SecurityException.NOT_ENOUGH_PERMISSIONS);
        }

        javax.jcr.Session systemSession = SessionManager.getInstance().getSystemSession();
        WorkspaceImpl workspace = checkWorkspaceExists(name, systemSession);
        // Always change to lowercase
        name = name.toLowerCase();
        workspace.createWorkspace(name);

        javax.jcr.Repository repository = SessionManager.getInstance().getRepository();
        SimpleCredentials creds = new SimpleCredentials(
                JLibraryProperties.getProperty(JLibraryProperties.JLIBRARY_SYSTEM_USERNAME, "username"),
                JLibraryProperties.getProperty(JLibraryProperties.JLIBRARY_SYSTEM_PASSWORD, "password")
                        .toCharArray());

        systemSession = repository.login(creds, name);

        // Copy to temp file. We cannot wrap to zip input stream due to incompatibilities
        // between apache implementation and java.util implementation
        File tempFile = File.createTempFile("jlib", "tmp");
        tempFile.deleteOnExit();
        FileOutputStream fos = new FileOutputStream(tempFile);
        IOUtils.copy(inputStream, fos);
        fos.flush();
        fos.close();

        ZipFile archive = null;
        try {
            archive = new ZipFile(tempFile);
        } catch (IOException ioe) {
            logger.warn("[JCRImportService] Trying to import non zipped repository");
            // probably this will be an old repository, so we will return the 
            // content to let the process try to import it
            return;
        }

        // do our own buffering; reuse the same buffer.
        byte[] buffer = new byte[16384];
        ZipEntry entry = archive.getEntry("jlibrary");

        // get a stream of the archive entry's bytes
        InputStream zis = archive.getInputStream(entry);

        //ZipInputStream zis = new ZipInputStream(inputStream);         
        byte[] smallBuffer = new byte[32];
        int i = 0;
        boolean tagFound = false;
        while (!tagFound) {
            byte next = (byte) zis.read();
            if (next == '*') {
                tagFound = true;
            } else {
                smallBuffer[i] = next;
                i++;
            }
        }

        byte[] header = new byte[i];
        System.arraycopy(smallBuffer, 0, header, 0, i);
        String lengthString = new String(header);
        int contentLength = Integer.parseInt(lengthString.substring(0, lengthString.length()));

        InputStream wrapzis = new ImportInputStream(zis, contentLength);
        systemSession.importXML("/", wrapzis, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);

        // Reopen the stream. importXML closes it
        zis = archive.getInputStream(entry);
        zis.skip(i + 1 + contentLength);

        // Now import the remaining info
        systemSession.importXML("/", zis, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);

        tempFile.delete();

        checkCustomProperties(systemSession);

        systemSession.save();

        // Finally check versions compatibility
        VersionChecker checker = new VersionChecker();
        checker.checkSession(systemSession);
    } catch (ConfigurationException ce) {
        //TODO: Remove this catch block when Jackrabbit supports workspace deletes
        throw new RecentlyRemovedRepositoryException();
    } catch (RepositoryAlreadyExistsException raee) {
        throw raee;
    } catch (SecurityException se) {
        throw se;
    } catch (AccessDeniedException e) {
        logger.error(e.getMessage(), e);
        throw new SecurityException(e);
    } catch (LoginException e) {
        logger.error(e.getMessage(), e);
        throw new SecurityException(e);
    } catch (RepositoryException re) {
        throw re;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new RepositoryException(e);
    }
}

From source file:org.opendatakit.survey.android.tasks.DownloadFormsTask.java

/**
 * Common routine to download a document from the downloadUrl and save the
 * contents in the file 'f'. Shared by media file download and form file
 * download.//from   w w w . j  ava  2  s. co  m
 *
 * @param f
 * @param downloadUrl
 * @throws Exception
 */
private void downloadFile(File f, String downloadUrl) throws Exception {
    URI uri = null;
    try {
        // assume the downloadUrl is escaped properly
        URL url = new URL(downloadUrl);
        uri = url.toURI();
    } catch (MalformedURLException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        throw e;
    } catch (URISyntaxException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        throw e;
    }

    // WiFi network connections can be renegotiated during a large form
    // download sequence.
    // This will cause intermittent download failures. Silently retry once
    // after each
    // failure. Only if there are two consecutive failures, do we abort.
    boolean success = false;
    int attemptCount = 1;
    while (!success && attemptCount++ <= 2) {
        if (isCancelled()) {
            throw new Exception("cancelled");
        }

        // get shared HttpContext so that authentication and cookies are
        // retained.
        HttpContext localContext = ClientConnectionManagerFactory.get(appName).getHttpContext();

        HttpClient httpclient = ClientConnectionManagerFactory.get(appName)
                .createHttpClient(WebUtils.CONNECTION_TIMEOUT);

        // set up request...
        HttpGet req = WebUtils.get().createOpenRosaHttpGet(uri, mAuth);

        HttpResponse response = null;
        try {
            response = httpclient.execute(req, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != 200) {
                WebUtils.get().discardEntityBytes(response);
                String errMsg = appContext.getString(R.string.file_fetch_failed, downloadUrl,
                        response.getStatusLine().getReasonPhrase(), statusCode);
                WebLogger.getLogger(appName).e(t, errMsg);
                throw new Exception(errMsg);
            }

            // write connection to file
            InputStream is = null;
            OutputStream os = null;
            try {
                is = response.getEntity().getContent();
                os = new FileOutputStream(f);
                byte buf[] = new byte[1024];
                int len;
                while ((len = is.read(buf)) > 0) {
                    os.write(buf, 0, len);
                }
                os.flush();
                success = true;
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (Exception e) {
                    }
                }
                if (is != null) {
                    try {
                        // ensure stream is consumed...
                        final long count = 1024L;
                        while (is.skip(count) == count)
                            ;
                    } catch (Exception e) {
                        // no-op
                    }
                    try {
                        is.close();
                    } catch (Exception e) {
                    }
                }
            }

        } catch (Exception e) {
            ClientConnectionManagerFactory.get(appName).clearHttpConnectionManager();
            WebLogger.getLogger(appName).e(t, e.toString());
            WebLogger.getLogger(appName).printStackTrace(e);
            if (attemptCount != 1) {
                throw e;
            }
        }
    }
}

From source file:org.dcache.chimera.FsSqlDriver.java

int read(FsInode inode, int level, long beginIndex, byte[] data, int offset, int len) {
    ResultSetExtractor<Integer> extractor = rs -> {
        try {/*  w  w  w.j  a  v a2 s .  c  om*/
            int count = 0;
            if (rs.next()) {
                InputStream in = rs.getBinaryStream(1);
                if (in != null) {
                    in.skip(beginIndex);
                    int c;
                    while (((c = in.read()) != -1) && (count < len)) {
                        data[offset + count] = (byte) c;
                        ++count;
                    }
                }
            }
            return count;
        } catch (IOException e) {
            throw new LobRetrievalFailureException(e.getMessage(), e);
        }
    };
    if (level == 0) {
        return _jdbc.query("SELECT ifiledata FROM t_inodes_data WHERE inumber=?", extractor, inode.ino());
    } else {
        return _jdbc.query("SELECT ifiledata FROM t_level_" + level + " WHERE inumber=?", extractor,
                inode.ino());
    }
}

From source file:org.gluu.oxtrust.servlet.FaviconImageServlet.java

@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("Starting organization favicon upload");
    String preview = httpServletRequest.getParameter("preview");
    GluuOrganization organization = null;
    try {/* w w w.ja v a  2 s .co  m*/
        organization = OrganizationService.instance().getOrganization();
    } catch (Exception ex) {
        log.error("an Error Occured", ex);
    }
    ImageService imageService = ImageService.instance();
    GluuImage image = null;
    if ("true".equals(preview)) {
        image = imageService.getGluuImageFromXML(organization.getTempFaviconImage());
        if (image != null) {
            image.setStoreTemporary(true);
        }

    }

    if (!"true".equals(preview) || image == null) {
        image = imageService.getGluuImageFromXML(organization.getFaviconImage());
    }

    if (image != null) {
        image.setLogo(false);
    }
    OutputStream os = null;
    InputStream is = null;
    try {
        DownloadWrapper downloadWrapper = null;

        // Send customized organization logo
        if (image != null) {
            File file = null;
            try {
                file = imageService.getSourceFile(image);
            } catch (Exception ex) {
                log.error("an Error Occured", ex);

            }
            try {
                is = FileUtils.openInputStream(file);
                if (is != null && file != null) {
                    downloadWrapper = new DownloadWrapper(is, image.getSourceName(),
                            image.getSourceContentType(), image.getCreationDate(), (int) file.length());
                }
            } catch (IOException ex) {
                log.error("Organization favicon image doesn't exist", ex);
                FileDownloader.sendError(response);
                return;
            }
        } else {
            // If customized logo doesn't exist then send default
            // organization logo
            String defaultFaviconFileName = "/WEB-INF/static/images/favicon_ic.ico";
            is = getServletContext().getResourceAsStream(defaultFaviconFileName);
            if (is == null) {
                log.error("Default organization favicon image doesn't exist");
                FileDownloader.sendError(response);
                return;
            }

            // Calculate default logo size
            long contentLength;
            try {
                contentLength = is.skip(Long.MAX_VALUE);
            } catch (IOException ex) {
                log.error("Failed to calculate default organization favicon image size", ex);
                FileDownloader.sendError(response);
                return;
            } finally {
                IOUtils.closeQuietly(is);
            }

            is = getServletContext().getResourceAsStream(defaultFaviconFileName);
            downloadWrapper = new DownloadWrapper(is, "favicon_ic.ico", "image/x-icon", new Date(),
                    (int) contentLength);
        }

        try {
            int logoSize = FileDownloader.writeOutput(downloadWrapper, ContentDisposition.INLINE, response);
            response.getOutputStream().flush();
            log.debug("Successfully send organization favicon with size", logoSize);
        } catch (IOException ex) {
            log.error("Failed to send organization favicon", ex);
            FileDownloader.sendError(response);
        }
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}