Example usage for java.net HttpURLConnection getContentLength

List of usage examples for java.net HttpURLConnection getContentLength

Introduction

In this page you can find the example usage for java.net HttpURLConnection getContentLength.

Prototype

public int getContentLength() 

Source Link

Document

Returns the value of the content-length header field.

Usage

From source file:blueprint.sdk.google.gcm.GcmSender.java

/**
 * gets response code//from ww w  .  j a v a 2 s .  c om
 *
 * @param http HTTP connection
 * @return 200: http ok, 6xx: {@link GcmResponse}, others: http error
 * @throws IOException
 */
@SuppressWarnings("IndexOfReplaceableByContains")
private int getResponseCode(HttpURLConnection http) throws IOException {
    int result = http.getResponseCode();

    if (result == HttpURLConnection.HTTP_OK) {
        int contentLength = http.getContentLength();
        String contentType = http.getContentType();
        if (0 == contentLength) {
            result = GcmResponse.ERR_NO_CONTENT;
        } else if (Validator.isEmpty(contentType)) {
            result = GcmResponse.ERR_NO_CONTENT_TYPE;
        } else if (0 > contentType.indexOf("application/json")) {
            result = GcmResponse.ERR_NOT_JSON;
        } else {
            result = 200;
        }
    }

    return result;
}

From source file:com.creactiviti.piper.core.taskhandler.io.Download.java

@Override
public Object handle(Task aTask) {
    try {/*w w  w  .  java  2  s  .com*/
        URL url = new URL(aTask.getRequiredString("url"));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        if (connection.getResponseCode() / 100 == 2) {
            File downloadedFile = File.createTempFile("download-", "", null);
            int contentLength = connection.getContentLength();
            Consumer<Integer> progressConsumer = (p) -> eventPublisher.publishEvent(PiperEvent
                    .of(Events.TASK_PROGRESSED, "taskId", ((TaskExecution) aTask).getId(), "progress", p));

            try (BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
                    OutputStream os = new ProgressingOutputStream(new FileOutputStream(downloadedFile),
                            contentLength, progressConsumer)) {

                copy(in, os);
            }
            return downloadedFile.toString();
        }

        throw new IllegalStateException("Server returned: " + connection.getResponseCode());

    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:io.github.jeremgamer.preview.actions.Download.java

private void download() {

    GeneralSave gs = new GeneralSave();
    try {//from   w w w .  j a  va 2  s.  c om
        gs.load(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    name = gs.getString("name");
    new Thread(new Runnable() {

        @Override
        public void run() {
            if (url == null) {

            } else {
                File archive = new File(System.getProperty("user.home") + "/AppData/Roaming/.rocketbuilder/"
                        + name + "/data.zip");
                File outputFolder = new File(
                        System.getProperty("user.home") + "/AppData/Roaming/.rocketbuilder/" + name);

                new File(System.getProperty("user.home") + "/AppData/Roaming/.rocketbuilder/" + name).mkdirs();
                URL webFile;
                try {
                    webFile = new URL(url);
                    ReadableByteChannel rbc = Channels.newChannel(webFile.openStream());
                    fos = new FileOutputStream(System.getProperty("user.home")
                            + "/AppData/Roaming/.rocketbuilder/" + name + "/data.zip");
                    HttpURLConnection httpConn = (HttpURLConnection) webFile.openConnection();
                    totalBytes = httpConn.getContentLength();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                while (bytesCopied < totalBytes) {
                                    for (CustomProgressBar bar : barList) {
                                        bytesCopied = fos.getChannel().size();
                                        progressValue = (int) (100 * bytesCopied / totalBytes);
                                        bar.setValue(progressValue);
                                        if (bar.isStringPainted()) {
                                            bar.setString(progressValue + "%     " + bytesCopied / 1000 + "/"
                                                    + totalBytes / 1000 + "Kb     tape " + step + "/2");
                                        }
                                    }
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                    }).start();
                    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
                    fos.close();
                    step = 2;
                    for (CustomProgressBar bar : barList) {
                        if (bar.isStringPainted()) {
                            bar.setString("tape " + step + "/2 : Extraction");
                        }
                    }

                    for (int timeout = 100; timeout > 0; timeout--) {
                        RandomAccessFile ran = null;

                        try {
                            ran = new RandomAccessFile(archive, "rw");
                            break;
                        } catch (Exception ex) {
                        } finally {
                            if (ran != null)
                                try {
                                    ran.close();
                                } catch (IOException ex) {
                                }

                            ran = null;
                        }

                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException ex) {
                        }
                    }

                    ZipFile zipFile = new ZipFile(archive, Charset.forName("Cp437"));
                    Enumeration<? extends ZipEntry> entries = zipFile.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = entries.nextElement();
                        File entryDestination = new File(outputFolder, entry.getName());
                        entryDestination.getParentFile().mkdirs();
                        if (entry.isDirectory())
                            entryDestination.mkdirs();
                        else {
                            InputStream in = zipFile.getInputStream(entry);
                            OutputStream out = new FileOutputStream(entryDestination);
                            IOUtils.copy(in, out);
                            IOUtils.closeQuietly(in);
                            IOUtils.closeQuietly(out);
                            in.close();
                            out.close();
                        }
                    }

                    for (CustomProgressBar bar : barList) {
                        bar.setString("");
                    }

                    zipFile.close();
                    archive.delete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }).start();
}

From source file:com.commsen.jwebthumb.WebThumbService.java

/**
 * Fetches single file form webthumb site and writes its content to given output stream.
 * Depending on what image format was requested (jpg|png|png8) and what file size is set in
 * {@link WebThumbFetchRequest} it will be the content of the jpg, png, png8 or zip file.
 * /*from   w w w . j a  va  2s.c o  m*/
 * @since 0.3
 * 
 * @param webThumbFetchRequest fetch request containing the job and size to be fetched
 * @param outputStream output stream to write the result to
 * @throws WebThumbException if the file can not be fetched for whatever reason
 */
public void fetch(WebThumbFetchRequest webThumbFetchRequest, OutputStream outputStream)
        throws WebThumbException {
    HttpURLConnection connection = getFetchConnection(webThumbFetchRequest);
    int contentLength = connection.getContentLength();
    if (contentLength != -1) {
        try {
            IOUtils.copy(connection.getInputStream(), outputStream);
        } catch (IOException e) {
            throw new WebThumbException("failed to read response", e);
        }
    } else {
        throw new WebThumbException("Failed to fetch image! Missing content length!");
    }
}

From source file:com.commsen.jwebthumb.WebThumbService.java

/**
 * Fetches single file form webthumb site. Depending on what image format was requested
 * (jpg|png|png8) and what file size is set in {@link WebThumbFetchRequest} returned byte array
 * will be the content of the jpg, png, png8 or zip file.
 * //from w w  w  . j a v  a2s.c o m
 * @param webThumbFetchRequest fetch request containing the job and size to be fetched
 * @return the content of the jpg, png, png8 or zip file.
 * @throws WebThumbException if the file can not be fetched for whatever reason
 */
public byte[] fetch(WebThumbFetchRequest webThumbFetchRequest) throws WebThumbException {
    HttpURLConnection connection = getFetchConnection(webThumbFetchRequest);
    int contentLength = connection.getContentLength();
    if (contentLength != -1) {
        byte[] data;
        try {
            data = IOUtils.toByteArray(connection.getInputStream());
        } catch (IOException e) {
            throw new WebThumbException("failed to read response", e);
        }
        if (data.length != contentLength) {
            throw new WebThumbException("Read " + data.length + " bytes; Expected " + contentLength + " bytes");
        }
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine("Response processed! Returning: " + data.length + " bytes of data");
        }
        return data;
    } else {
        throw new WebThumbException("Failed to fetch image! Missing content length!");
    }
}

From source file:foam.blob.RestBlobService.java

@Override
public Blob find_(X x, Object id) {
    InputStream is = null;// w w  w .j  ava  2  s. c  o  m
    ByteArrayOutputStream os = null;
    HttpURLConnection connection = null;

    try {
        URL url = new URL(this.address_ + "/" + id.toString());
        connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("GET");
        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK || connection.getContentLength() == -1) {
            throw new RuntimeException("Failed to find blob");
        }

        is = new BufferedInputStream(connection.getInputStream());
        os = new ByteArrayOutputStream();

        int read = 0;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((read = is.read(buffer, 0, BUFFER_SIZE)) != -1) {
            os.write(buffer, 0, read);
        }

        return new ByteArrayBlob(os.toByteArray());
    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(is);
        IOUtils.close(connection);
    }
}

From source file:com.facebook.android.Example.java

/** Called when the activity is first created. */
@Override/* ww w.  j  a  va 2  s.c om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (APP_ID == null) {
        Util.showAlert(this, "Warning",
                "Facebook Applicaton ID must be " + "specified before running this example: see Example.java");
    }

    setContentView(R.layout.main);
    mLoginButton = (LoginButton) findViewById(R.id.login);
    mText = (TextView) Example.this.findViewById(R.id.txt);
    mRequestButton = (Button) findViewById(R.id.requestButton);
    mPostButton = (Button) findViewById(R.id.postButton);
    mDeleteButton = (Button) findViewById(R.id.deletePostButton);
    mUploadButton = (Button) findViewById(R.id.uploadButton);

    mFacebook = new Facebook(APP_ID);
    mAsyncRunner = new AsyncFacebookRunner(mFacebook);

    SessionStore.restore(mFacebook, this);
    SessionEvents.addAuthListener(new SampleAuthListener());
    SessionEvents.addLogoutListener(new SampleLogoutListener());
    mLoginButton.init(this, mFacebook);

    mRequestButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mAsyncRunner.request("me", new SampleRequestListener());
        }
    });
    mRequestButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);

    mUploadButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Bundle params = new Bundle();
            params.putString("method", "photos.upload");

            URL uploadFileUrl = null;
            try {
                uploadFileUrl = new URL("http://www.facebook.com/images/devsite/iphone_connect_btn.jpg");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            try {
                HttpURLConnection conn = (HttpURLConnection) uploadFileUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                int length = conn.getContentLength();

                byte[] imgData = new byte[length];
                InputStream is = conn.getInputStream();
                is.read(imgData);
                params.putByteArray("picture", imgData);

            } catch (IOException e) {
                e.printStackTrace();
            }

            mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
        }
    });
    mUploadButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);

    mPostButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mFacebook.dialog(Example.this, "feed", new SampleDialogListener());
        }
    });
    mPostButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);
}

From source file:com.jittr.android.facebook.Example.java

/** Called when the activity is first created. */
@Override//w  ww  .j  a v a2s.  co  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (APP_ID == null) {
        Util.showAlert(this, "Warning",
                "Facebook Applicaton ID must be " + "specified before running this example: see Example.java");
    }

    // mFacebook.
    setContentView(R.layout.mainfacebook);
    mLoginButton = (LoginButton) findViewById(R.id.login);
    mText = (TextView) Example.this.findViewById(R.id.txt);
    mRequestButton = (Button) findViewById(R.id.requestButton);
    mPostButton = (Button) findViewById(R.id.postButton);
    mDeleteButton = (Button) findViewById(R.id.deletePostButton);
    mUploadButton = (Button) findViewById(R.id.uploadButton);

    mFacebook = new Facebook();
    mAsyncRunner = new AsyncFacebookRunner(mFacebook);

    SessionStore.restore(mFacebook, this);
    SessionEvents.addAuthListener(new SampleAuthListener());
    SessionEvents.addLogoutListener(new SampleLogoutListener());
    mLoginButton.init(mFacebook, PERMISSIONS);

    mRequestButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mAsyncRunner.request("me", new SampleRequestListener());
        }
    });
    mRequestButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);

    mUploadButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Bundle params = new Bundle();
            params.putString("method", "photos.upload");

            URL uploadFileUrl = null;
            try {
                uploadFileUrl = new URL("http://www.facebook.com/images/devsite/iphone_connect_btn.jpg");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            try {
                HttpURLConnection conn = (HttpURLConnection) uploadFileUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                int length = conn.getContentLength();

                byte[] imgData = new byte[length];
                InputStream is = conn.getInputStream();
                is.read(imgData);
                params.putByteArray("picture", imgData);

            } catch (IOException e) {
                e.printStackTrace();
            }

            mAsyncRunner.request(null, params, "POST", new SampleUploadListener());
        }
    });
    mUploadButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);

    mPostButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mFacebook.dialog(Example.this, "stream.publish", new SampleDialogListener());
        }
    });
    mPostButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);
}

From source file:edu.stanford.mobisocial.dungbeetle.facebook.FacebookInterfaceActivity.java

/** Called when the activity is first created. */
@Override/*from  w w w. ja  v  a2 s. co m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (APP_ID == null) {
        Util.showAlert(this, "Warning", "Facebook Applicaton ID must be "
                + "specified before running this example: see FacebookInterfaceActivity.java");
    }

    setContentView(R.layout.facebook);
    mLoginButton = (LoginButton) findViewById(R.id.login);
    mText = (TextView) FacebookInterfaceActivity.this.findViewById(R.id.txt);
    mRequestButton = (Button) findViewById(R.id.requestButton);
    mPostButton = (Button) findViewById(R.id.postButton);
    mDeleteButton = (Button) findViewById(R.id.deletePostButton);
    mUploadButton = (Button) findViewById(R.id.uploadButton);

    mFacebook = new Facebook(APP_ID);
    mAsyncRunner = new AsyncFacebookRunner(mFacebook);

    SessionStore.restore(mFacebook, this);
    SessionEvents.addAuthListener(new SampleAuthListener());
    SessionEvents.addLogoutListener(new SampleLogoutListener());
    mLoginButton.init(this, mFacebook);

    mRequestButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mAsyncRunner.request("me", new SampleRequestListener());
        }
    });
    mRequestButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);

    mUploadButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Bundle params = new Bundle();
            params.putString("method", "photos.upload");

            URL uploadFileUrl = null;
            try {
                uploadFileUrl = new URL("http://www.facebook.com/images/devsite/iphone_connect_btn.jpg");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            try {
                HttpURLConnection conn = (HttpURLConnection) uploadFileUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                int length = conn.getContentLength();

                byte[] imgData = new byte[length];
                InputStream is = conn.getInputStream();
                is.read(imgData);
                params.putByteArray("picture", imgData);

            } catch (IOException e) {
                e.printStackTrace();
            }

            mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
        }
    });
    mUploadButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);

    mPostButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mFacebook.dialog(FacebookInterfaceActivity.this, "feed", new SampleDialogListener());
        }
    });
    mPostButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);
}

From source file:com.pixem.core.activity.Example.java

/** Called when the activity is first created. */
@Override//from   w w  w. j  av  a 2 s .  c  o m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (APP_ID == null) {
        Util.showAlert(this, "Warning",
                "Facebook Applicaton ID must be " + "specified before running this example: see Example.java");
    }

    setContentView(R.layout.facebook);
    mLoginButton = (LoginButton) findViewById(R.id.login);
    mText = (TextView) Example.this.findViewById(R.id.txt);
    mRequestButton = (Button) findViewById(R.id.requestButton);
    mPostButton = (Button) findViewById(R.id.postButton);
    mDeleteButton = (Button) findViewById(R.id.deletePostButton);
    mUploadButton = (Button) findViewById(R.id.uploadButton);

    mFacebook = new Facebook(APP_ID);
    mAsyncRunner = new AsyncFacebookRunner(mFacebook);

    SessionStore.restore(mFacebook, this);
    SessionEvents.addAuthListener(new SampleAuthListener());
    SessionEvents.addLogoutListener(new SampleLogoutListener());
    mLoginButton.init(this, mFacebook);

    mRequestButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mAsyncRunner.request("me", new SampleRequestListener());
        }
    });
    mRequestButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);

    mUploadButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Bundle params = new Bundle();
            params.putString("method", "photos.upload");

            URL uploadFileUrl = null;
            try {
                uploadFileUrl = new URL("http://www.facebook.com/images/devsite/iphone_connect_btn.jpg");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            try {
                HttpURLConnection conn = (HttpURLConnection) uploadFileUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                int length = conn.getContentLength();

                byte[] imgData = new byte[length];
                InputStream is = conn.getInputStream();
                is.read(imgData);
                params.putByteArray("picture", imgData);

            } catch (IOException e) {
                e.printStackTrace();
            }

            mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
        }
    });
    mUploadButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);

    mPostButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mFacebook.dialog(Example.this, "feed", new SampleDialogListener());
        }
    });
    mPostButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE);
}