Example usage for java.net HttpURLConnection setFixedLengthStreamingMode

List of usage examples for java.net HttpURLConnection setFixedLengthStreamingMode

Introduction

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

Prototype

public void setFixedLengthStreamingMode(long contentLength) 

Source Link

Document

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

Usage

From source file:org.c99.wear_imessage.RemoteInputService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        final String action = intent.getAction();
        if (ACTION_REPLY.equals(action)) {
            JSONObject conversations = null, conversation = null;
            try {
                conversations = new JSONObject(
                        getSharedPreferences("data", 0).getString("conversations", "{}"));
            } catch (JSONException e) {
                conversations = new JSONObject();
            }/*from  w  w  w  . ja va  2s  . com*/

            try {
                String key = intent.getStringExtra("service") + ":" + intent.getStringExtra("handle");
                if (conversations.has(key)) {
                    conversation = conversations.getJSONObject(key);
                } else {
                    conversation = new JSONObject();
                    conversations.put(key, conversation);

                    long time = new Date().getTime();
                    String tmpStr = String.valueOf(time);
                    String last4Str = tmpStr.substring(tmpStr.length() - 5);
                    conversation.put("notification_id", Integer.valueOf(last4Str));
                    conversation.put("msgs", new JSONArray());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
            if (remoteInput != null || intent.hasExtra("reply")) {
                String reply = remoteInput != null ? remoteInput.getCharSequence("extra_reply").toString()
                        : intent.getStringExtra("reply");

                if (intent.hasExtra(Intent.EXTRA_STREAM)) {
                    NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
                            .setContentTitle("Uploading File").setProgress(0, 0, true).setLocalOnly(true)
                            .setOngoing(true).setSmallIcon(android.R.drawable.stat_sys_upload);
                    NotificationManagerCompat.from(this).notify(1337, notification.build());

                    InputStream fileIn = null;
                    InputStream responseIn = null;
                    HttpURLConnection http = null;
                    try {
                        String filename = "";
                        int total = 0;
                        String type = getContentResolver()
                                .getType((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
                        if (type == null || type.length() == 0)
                            type = "application/octet-stream";
                        fileIn = getContentResolver()
                                .openInputStream((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));

                        Cursor c = getContentResolver().query(
                                (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM),
                                new String[] { OpenableColumns.SIZE, OpenableColumns.DISPLAY_NAME }, null, null,
                                null);
                        if (c != null && c.moveToFirst()) {
                            total = c.getInt(0);
                            filename = c.getString(1);
                            c.close();
                        } else {
                            total = fileIn.available();
                        }

                        String boundary = UUID.randomUUID().toString();
                        http = (HttpURLConnection) new URL(
                                "http://" + getSharedPreferences("prefs", 0).getString("host", "") + "/upload")
                                        .openConnection();
                        http.setReadTimeout(60000);
                        http.setConnectTimeout(60000);
                        http.setDoOutput(true);
                        http.setFixedLengthStreamingMode(total + (boundary.length() * 5) + filename.length()
                                + type.length() + intent.getStringExtra("handle").length()
                                + intent.getStringExtra("service").length() + reply.length() + 251);
                        http.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

                        OutputStream out = http.getOutputStream();
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"handle\"\r\n\r\n").getBytes());
                        out.write((intent.getStringExtra("handle") + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"service\"\r\n\r\n").getBytes());
                        out.write((intent.getStringExtra("service") + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"msg\"\r\n\r\n").getBytes());
                        out.write((reply + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename
                                + "\"\r\n").getBytes());
                        out.write(("Content-Type: " + type + "\r\n\r\n").getBytes());

                        byte[] buffer = new byte[8192];
                        int count = 0;
                        int n = 0;
                        while (-1 != (n = fileIn.read(buffer))) {
                            out.write(buffer, 0, n);
                            count += n;

                            float progress = (float) count / (float) total;
                            if (progress < 1.0f)
                                notification.setProgress(1000, (int) (progress * 1000), false);
                            else
                                notification.setProgress(0, 0, true);
                            NotificationManagerCompat.from(this).notify(1337, notification.build());
                        }

                        out.write(("\r\n--" + boundary + "--\r\n").getBytes());
                        out.flush();
                        out.close();
                        if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
                            responseIn = http.getInputStream();
                            StringBuilder sb = new StringBuilder();
                            Scanner scanner = new Scanner(responseIn).useDelimiter("\\A");
                            while (scanner.hasNext()) {
                                sb.append(scanner.next());
                            }
                            android.util.Log.i("iMessage", "Upload result: " + sb.toString());
                            try {
                                if (conversation != null) {
                                    JSONArray msgs = conversation.getJSONArray("msgs");
                                    JSONObject m = new JSONObject();
                                    m.put("msg", filename);
                                    m.put("service", intent.getStringExtra("service"));
                                    m.put("handle", intent.getStringExtra("handle"));
                                    m.put("type", "sent_file");
                                    msgs.put(m);

                                    while (msgs.length() > 10) {
                                        msgs.remove(0);
                                    }

                                    GCMIntentService.notify(getApplicationContext(),
                                            intent.getIntExtra("notification_id", 0), msgs, intent, true);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            responseIn = http.getErrorStream();
                            StringBuilder sb = new StringBuilder();
                            Scanner scanner = new Scanner(responseIn).useDelimiter("\\A");
                            while (scanner.hasNext()) {
                                sb.append(scanner.next());
                            }
                            android.util.Log.e("iMessage", "Upload failed: " + sb.toString());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (responseIn != null)
                                responseIn.close();
                        } catch (Exception ignore) {
                        }
                        try {
                            if (http != null)
                                http.disconnect();
                        } catch (Exception ignore) {
                        }
                        try {
                            fileIn.close();
                        } catch (Exception ignore) {
                        }
                    }
                    NotificationManagerCompat.from(this).cancel(1337);
                } else if (reply.length() > 0) {
                    URL url = null;
                    try {
                        url = new URL("http://" + getSharedPreferences("prefs", 0).getString("host", "")
                                + "/send?service=" + intent.getStringExtra("service") + "&handle="
                                + intent.getStringExtra("handle") + "&msg="
                                + URLEncoder.encode(reply, "UTF-8"));
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }
                    HttpURLConnection conn;

                    try {
                        conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return;
                    }
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    conn.setUseCaches(false);

                    BufferedReader reader = null;

                    try {
                        if (conn.getInputStream() != null) {
                            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()), 512);
                        }
                    } catch (IOException e) {
                        if (conn.getErrorStream() != null) {
                            reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()), 512);
                        }
                    }

                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    conn.disconnect();
                    try {
                        if (conversation != null) {
                            JSONArray msgs = conversation.getJSONArray("msgs");
                            JSONObject m = new JSONObject();
                            m.put("msg", reply);
                            m.put("service", intent.getStringExtra("service"));
                            m.put("handle", intent.getStringExtra("handle"));
                            m.put("type", "sent");
                            msgs.put(m);

                            while (msgs.length() > 10) {
                                msgs.remove(0);
                            }

                            GCMIntentService.notify(getApplicationContext(),
                                    intent.getIntExtra("notification_id", 0), msgs, intent, true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                SharedPreferences.Editor e = getSharedPreferences("data", 0).edit();
                e.putString("conversations", conversations.toString());
                e.apply();
            }
        }
    }
}

From source file:org.witness.ssc.xfer.utils.PublishingUtils.java

private String gdataUpload(File file, String uploadUrl, int start, int end, Activity activity)
        throws IOException {

    mActivity = activity;/*from  ww w . j av  a  2s . com*/

    int chunk = end - start + 1;
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    FileInputStream fileStream = new FileInputStream(file);

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);

    // some mobile proxies do not support PUT, using X-HTTP-Method-Override
    // to get around this problem
    if (isFirstRequest()) {
        Log.d(TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded));
        urlConnection.setRequestMethod("POST");
    } else {
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT");
        Log.d(TAG, String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.",
                (int) totalBytesUploaded));
    }
    urlConnection.setDoOutput(true);
    urlConnection.setFixedLengthStreamingMode(chunk);
    // /XXX hardcoded video mimetype
    urlConnection.setRequestProperty("Content-Type", "video/mp4");
    urlConnection.setRequestProperty("Content-Range",
            String.format("bytes %d-%d/%d", start, end, file.length()));
    Log.d(TAG, urlConnection.getRequestProperty("Content-Range"));

    OutputStream outStreamWriter = urlConnection.getOutputStream();

    fileStream.skip(start);

    int bytesRead;
    int totalRead = 0;

    Thread thread = new Thread() {

        public void run() {
            int lastPercent = 0;

            while (lastPercent < 100) {
                if (lastPercent != percentUploaded) {
                    ((SSCXferActivity) mActivity).showProgress("uploading...", percentUploaded);
                    lastPercent = percentUploaded;
                }

                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }

            }
        }
    };
    thread.start();

    while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) {
        outStreamWriter.write(buffer, 0, bytesRead);
        totalRead += bytesRead;
        this.totalBytesUploaded += bytesRead;

        percentUploaded = (int) (((float) totalBytesUploaded) / ((float) currentFileSize) * 99f);

        if (totalRead == (end - start + 1)) {
            break;
        }
    }

    outStreamWriter.close();

    int responseCode = urlConnection.getResponseCode();

    Log.d(TAG, "responseCode=" + responseCode);
    Log.d(TAG, "responseMessage=" + urlConnection.getResponseMessage());

    try {
        if (responseCode == 201) {
            String videoId = parseVideoId(urlConnection.getInputStream());

            Log.i(TAG, "Youtube video submitted - new video id is " + videoId);

            // 100% finished here.

            // dialog.setProgress(100);

            return videoId;
        } else if (responseCode == 200) {
            Set<String> keySet = urlConnection.getHeaderFields().keySet();
            String keys = urlConnection.getHeaderFields().keySet().toString();
            Log.d(TAG, String.format("Headers keys %s.", keys));
            for (String key : keySet) {
                Log.d(TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key)));
            }
            Log.w(TAG, "Received 200 response during resumable uploading");
            throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s",
                    responseCode, urlConnection.getResponseMessage()));
        } else {
            if ((responseCode + "").startsWith("5")) {
                String error = String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage());
                Log.w(TAG, error);
                // TODO - this exception will trigger retry mechanism to
                // kick in
                // TODO - even though it should not, consider introducing a
                // new type so
                // TODO - resume does not kick in upon 5xx
                throw new IOException(error);
            } else if (responseCode == 308) {
                // OK, the chunk completed successfully
                Log.d(TAG, String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage()));
            } else {
                // TODO - this case is not handled properly yet
                Log.w(TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode,
                        urlConnection.getResponseMessage(), uploadUrl));
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:ca.osmcanada.osvuploadr.JPMain.java

private String sendForm(String target_url, Map<String, String> arguments, String method,
        List<Cookie> cookielist) {
    try {/*w  ww.  jav a2  s . c  o  m*/
        URL url = new URL(target_url);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        //HttpURLConnection http = (HttpURLConnection)con;
        con.setRequestMethod(method); // PUT is another valid option
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(false);
        String cookiestr = "";
        if (cookielist != null) {
            if (cookielist.size() > 0) {
                for (Cookie cookie : cookielist) {
                    if (!cookiestr.equals("")) {
                        cookiestr += ";" + cookie.getName() + "=" + cookie.getValue();
                    } else {
                        cookiestr += cookie.getName() + "=" + cookie.getValue();
                    }
                }
                con.setRequestProperty("Cookie", cookiestr);
            }
        }

        con.setReadTimeout(5000);

        StringJoiner sj = new StringJoiner("&");
        for (Map.Entry<String, String> entry : arguments.entrySet())
            sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
                    + URLEncoder.encode(entry.getValue(), "UTF-8"));
        byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
        int length = out.length;

        con.setFixedLengthStreamingMode(length);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        con.setRequestProperty("Accept-Language", "en-us;");
        con.connect();
        try (OutputStream os = con.getOutputStream()) {
            os.write(out);
            os.close();
        }

        boolean redirect = false;
        int status = con.getResponseCode();

        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        if (redirect) {
            String newURL = con.getHeaderField("Location");
            String cookies = con.getHeaderField("Set-Cookie");
            if (cookies == null) {
                cookies = cookiestr;
            }
            con = (HttpURLConnection) new URL(newURL).openConnection();
            con.setRequestProperty("Cookie", cookies);
        }

        InputStream is = con.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte buf[] = new byte[1024];
        int letti;

        while ((letti = is.read(buf)) > 0)
            baos.write(buf, 0, letti);

        String data = new String(baos.toByteArray(), Charset.forName("UTF-8"));
        con.disconnect();

        return data;

    } catch (Exception ex) {
        Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}

From source file:com.docdoku.client.actions.MainController.java

private void uploadFileWithServlet(final Component pParent, File pLocalFile, String pURL) throws IOException {
    System.out.println("Uploading file with servlet");
    InputStream in = null;/*w ww.j  a v  a  2s.  c  o m*/
    OutputStream out = null;
    HttpURLConnection conn = null;
    try {
        //Hack for NTLM proxy
        //perform a head method to negociate the NTLM proxy authentication
        performHeadHTTPMethod(pURL);

        MainModel model = MainModel.getInstance();
        URL url = new URL(pURL);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        byte[] encoded = org.apache.commons.codec.binary.Base64
                .encodeBase64((model.getLogin() + ":" + model.getPassword()).getBytes("ISO-8859-1"));
        conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII"));

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "--------------------" + Long.toString(System.currentTimeMillis(), 16);
        byte[] header = (twoHyphens + boundary + lineEnd + "Content-Disposition: form-data; name=\"upload\";"
                + " filename=\"" + pLocalFile + "\"" + lineEnd + lineEnd).getBytes("ISO-8859-1");
        byte[] footer = (lineEnd + twoHyphens + boundary + twoHyphens + lineEnd).getBytes("ISO-8859-1");

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        //conn.setRequestProperty("Content-Length",len + "");
        long len = header.length + pLocalFile.length() + footer.length;
        conn.setFixedLengthStreamingMode((int) len);
        out = new BufferedOutputStream(conn.getOutputStream(), Config.BUFFER_CAPACITY);
        out.write(header);

        byte[] data = new byte[Config.CHUNK_SIZE];
        int length;
        in = new ProgressMonitorInputStream(pParent,
                I18N.BUNDLE.getString("UploadMsg_part1") + " " + pLocalFile.getName() + " ("
                        + (int) (pLocalFile.length() / 1024) + I18N.BUNDLE.getString("UploadMsg_part2"),
                new BufferedInputStream(new FileInputStream(pLocalFile), Config.BUFFER_CAPACITY));
        while ((length = in.read(data)) != -1) {
            out.write(data, 0, length);
        }

        out.write(footer);
        out.flush();

        int code = conn.getResponseCode();
        System.out.println("Upload HTTP response code: " + code);
        if (code != 200) {
            //TODO create a more suitable exception
            throw new IOException();
        }
        out.close();
    } catch (InterruptedIOException pEx) {
        throw pEx;
    } catch (IOException pEx) {
        out.close();
        throw pEx;
    } finally {
        in.close();
        conn.disconnect();
    }
}

From source file:fi.hip.sicx.store.HIPStoreClient.java

@Override
public boolean storeFile(String localInputFilename, String fileInTheCloud, StorageClientObserver sco) {

    HttpURLConnection conn = null;
    boolean ret = false;
    String boundary = Long.toHexString(System.currentTimeMillis());
    String crlf = "\r\n";
    try {//from  www  .  ja  v  a  2s.com
        // create the preamble to the file stream (incl. the other parameters ..)
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(bos, "UTF-8"));

        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("permissions", "");
        params.put("path", fileInTheCloud); // this could be set in the filename

        for (Enumeration<String> e = params.keys(); e.hasMoreElements();) {
            String k = (String) e.nextElement();
            String v = params.get(k);
            writer.print("--" + boundary + crlf);
            writer.print("Content-Disposition: form-data; name=\"" + k + "\"" + crlf);
            writer.print("Content-Type: text/plain; charset=UTF-8" + crlf + crlf);
            writer.print(v + crlf);
        }

        writer.print("--" + boundary + crlf);
        writer.print(
                "Content-Disposition: form-data; name=\"data\"; filename=\"" + fileInTheCloud + "\"" + crlf);
        writer.print("Content-Type: application/octet-stream" + crlf + crlf);
        writer.close();
        byte[] preamble = bos.toByteArray();

        bos = new ByteArrayOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(bos, "UTF-8"));
        writer.print(crlf + "--" + boundary + "--" + crlf);
        writer.close();
        byte[] postamble = bos.toByteArray();

        File f = new File(localInputFilename);
        long total = preamble.length + f.length() + postamble.length;
        long sent = 0;

        // do a multipart post
        conn = getConnection("/store/store");
        conn.setDoOutput(true); // do POST
        conn.setFixedLengthStreamingMode((int) total);
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        OutputStream out = conn.getOutputStream();
        FileInputStream fis = new FileInputStream(f);
        byte[] buf = new byte[1024 * 64];
        int r = 0;

        /* note: we need to bundle the first bytes from the file with the preamble,
           becase the apache commons fileupload used on the other side is buggy. */
        while ((r = fis.read(buf)) > 0) {
            if (preamble != null) {
                byte[] tmp = new byte[preamble.length + r];
                System.arraycopy(preamble, 0, tmp, 0, preamble.length);
                System.arraycopy(buf, 0, tmp, preamble.length, r);

                r = preamble.length + r;
                out.write(tmp, 0, r);
                preamble = null;
            } else {
                out.write(buf, 0, r);
            }
            sent += r;
            sco.progressMade((int) ((sent * 100) / total));
        }

        fis.close();

        out.write(postamble);
        sent += postamble.length;
        sco.progressMade((int) ((sent * 100) / total));
        out.flush();

        ret = true;
    } catch (Exception ex) {
        System.out.println("Error connecting, " + ex);
        ex.printStackTrace();
        failed = true;
    }
    closeConnection(conn);
    return ret;
}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

private String gdataUpload(File file, String uploadUrl, int start, int end) throws IOException {
    int chunk = end - start + 1;
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    FileInputStream fileStream = new FileInputStream(file);

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    // some mobile proxies do not support PUT, using X-HTTP-Method-Override
    // to get around this problem
    if (isFirstRequest()) {
        Log.d(TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded));
        urlConnection.setRequestMethod("POST");
    } else {//w w w.  j a v a2s  . c om
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT");
        Log.d(TAG, String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.",
                (int) totalBytesUploaded));
    }
    urlConnection.setDoOutput(true);
    urlConnection.setFixedLengthStreamingMode(chunk);
    // /XXX hardcoded video mimetype
    urlConnection.setRequestProperty("Content-Type", "video/mp4");
    urlConnection.setRequestProperty("Content-Range",
            String.format("bytes %d-%d/%d", start, end, file.length()));
    Log.d(TAG, urlConnection.getRequestProperty("Content-Range"));

    OutputStream outStreamWriter = urlConnection.getOutputStream();

    fileStream.skip(start);

    int bytesRead;
    int totalRead = 0;
    while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) {
        outStreamWriter.write(buffer, 0, bytesRead);
        totalRead += bytesRead;
        this.totalBytesUploaded += bytesRead;

        // double percent = (totalBytesUploaded / currentFileSize) * 99;

        /*
         * Log.d(TAG, String.format(
         * "fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize,
         * totalBytesUploaded, percent));
         */

        if (totalRead == (end - start + 1)) {
            break;
        }
    }

    outStreamWriter.close();

    int responseCode = urlConnection.getResponseCode();

    Log.d(TAG, "responseCode=" + responseCode);
    Log.d(TAG, "responseMessage=" + urlConnection.getResponseMessage());

    try {
        if (responseCode == 201) {
            String videoId = parseVideoId(urlConnection.getInputStream());

            Log.i(TAG, "Youtube video submitted - new video id is " + videoId);

            // 100% finished here.

            // dialog.setProgress(100);

            return videoId;
        } else if (responseCode == 200) {
            Set<String> keySet = urlConnection.getHeaderFields().keySet();
            String keys = urlConnection.getHeaderFields().keySet().toString();
            Log.d(TAG, String.format("Headers keys %s.", keys));
            for (String key : keySet) {
                Log.d(TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key)));
            }
            Log.w(TAG, "Received 200 response during resumable uploading");
            throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s",
                    responseCode, urlConnection.getResponseMessage()));
        } else {
            if ((responseCode + "").startsWith("5")) {
                String error = String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage());
                Log.w(TAG, error);
                // TODO - this exception will trigger retry mechanism to
                // kick in
                // TODO - even though it should not, consider introducing a
                // new type so
                // TODO - resume does not kick in upon 5xx
                throw new IOException(error);
            } else if (responseCode == 308) {
                // OK, the chunk completed successfully
                Log.d(TAG, String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage()));
            } else {
                // TODO - this case is not handled properly yet
                Log.w(TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode,
                        urlConnection.getResponseMessage(), uploadUrl));
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.mozilla.mozstumbler.service.core.http.HttpUtil.java

@Override
public IResponse post(String urlString, byte[] data, Map<String, String> headers, boolean precompressed) {

    URL url = null;//from   w  ww . java  2  s.c  om
    HttpURLConnection httpURLConnection = null;

    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Invalid URL", e);
    }

    if (data == null) {
        throw new IllegalArgumentException("Data must be not null");
    }

    if (headers == null) {
        headers = new HashMap<String, String>();
    }

    try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(5000); // set timeout to 5 seconds
        // HttpURLConnection and Java are braindead.
        // http://stackoverflow.com/questions/8587913/what-exactly-does-urlconnection-setdooutput-affect
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");

    } catch (IOException e) {
        Log.e(LOG_TAG, "Couldn't open a connection: ", e);
        return null;
    }

    httpURLConnection.setDoOutput(true);
    httpURLConnection.setRequestProperty(USER_AGENT_HEADER, userAgent);
    httpURLConnection.setRequestProperty("Content-Type", "application/json");

    // Workaround for a bug in Android mHttpURLConnection. When the library
    // reuses a stale connection, the connection may fail with an EOFException
    // http://stackoverflow.com/questions/15411213/android-httpsurlconnection-eofexception/17791819#17791819
    if (Build.VERSION.SDK_INT > 13 && Build.VERSION.SDK_INT < 19) {
        httpURLConnection.setRequestProperty("Connection", "Close");
    }

    // Set headers
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
    }

    byte[] wire_data = data;
    if (!precompressed) {
        wire_data = Zipper.zipData(data);
        if (wire_data != null) {
            httpURLConnection.setRequestProperty("Content-Encoding", "gzip");
        } else {
            Log.w(LOG_TAG, "Couldn't compress data, falling back to raw data.");
            wire_data = data;
        }
    } else {
        httpURLConnection.setRequestProperty("Content-Encoding", "gzip");
    }

    httpURLConnection.setFixedLengthStreamingMode(wire_data.length);
    try {
        OutputStream out = new BufferedOutputStream(httpURLConnection.getOutputStream());
        out.write(wire_data);
        out.flush();
        return new HTTPResponse(httpURLConnection.getResponseCode(), httpURLConnection.getHeaderFields(),
                getContentBody(httpURLConnection), wire_data.length);
    } catch (IOException e) {
        Log.e(LOG_TAG, "post error", e);
    } finally {
        httpURLConnection.disconnect();
    }
    return null;
}

From source file:hudson.Main.java

/**
 * Run command and send result to {@code ExternalJob} in the {@code external-monitor-job} plugin.
 * Obsoleted by {@code SetExternalBuildResultCommand} but kept here for compatibility.
 *//*  w  w w .j  a v  a  2s . com*/
public static int remotePost(String[] args) throws Exception {
    String projectName = args[0];

    String home = getHudsonHome();
    if (!home.endsWith("/"))
        home = home + '/'; // make sure it ends with '/'

    // check for authentication info
    String auth = new URL(home).getUserInfo();
    if (auth != null)
        auth = "Basic " + new Base64Encoder().encode(auth.getBytes("UTF-8"));

    {// check if the home is set correctly
        HttpURLConnection con = open(new URL(home));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        con.connect();
        if (con.getResponseCode() != 200 || con.getHeaderField("X-Hudson") == null) {
            System.err.println(home + " is not Hudson (" + con.getResponseMessage() + ")");
            return -1;
        }
    }

    URL jobURL = new URL(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/");

    {// check if the job name is correct
        HttpURLConnection con = open(new URL(jobURL, "acceptBuildResult"));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        con.connect();
        if (con.getResponseCode() != 200) {
            System.err.println(jobURL + " is not a valid external job (" + con.getResponseCode() + " "
                    + con.getResponseMessage() + ")");
            return -1;
        }
    }

    // get a crumb to pass the csrf check
    String crumbField = null, crumbValue = null;
    try {
        HttpURLConnection con = open(
                new URL(home + "crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'"));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        String line = IOUtils.readFirstLine(con.getInputStream(), "UTF-8");
        String[] components = line.split(":");
        if (components.length == 2) {
            crumbField = components[0];
            crumbValue = components[1];
        }
    } catch (IOException e) {
        // presumably this Hudson doesn't use CSRF protection
    }

    // write the output to a temporary file first.
    File tmpFile = File.createTempFile("jenkins", "log");
    try {
        int ret;
        try (OutputStream os = Files.newOutputStream(tmpFile.toPath());
                Writer w = new OutputStreamWriter(os, "UTF-8")) {
            w.write("<?xml version='1.1' encoding='UTF-8'?>");
            w.write("<run><log encoding='hexBinary' content-encoding='" + Charset.defaultCharset().name()
                    + "'>");
            w.flush();

            // run the command
            long start = System.currentTimeMillis();

            List<String> cmd = new ArrayList<String>();
            for (int i = 1; i < args.length; i++)
                cmd.add(args[i]);
            Proc proc = new Proc.LocalProc(cmd.toArray(new String[0]), (String[]) null, System.in,
                    new DualOutputStream(System.out, new EncodingStream(os)));

            ret = proc.join();

            w.write("</log><result>" + ret + "</result><duration>" + (System.currentTimeMillis() - start)
                    + "</duration></run>");
        } catch (InvalidPathException e) {
            throw new IOException(e);
        }

        URL location = new URL(jobURL, "postBuildResult");
        while (true) {
            try {
                // start a remote connection
                HttpURLConnection con = open(location);
                if (auth != null)
                    con.setRequestProperty("Authorization", auth);
                if (crumbField != null && crumbValue != null) {
                    con.setRequestProperty(crumbField, crumbValue);
                }
                con.setDoOutput(true);
                // this tells HttpURLConnection not to buffer the whole thing
                con.setFixedLengthStreamingMode((int) tmpFile.length());
                con.connect();
                // send the data
                try (InputStream in = Files.newInputStream(tmpFile.toPath())) {
                    org.apache.commons.io.IOUtils.copy(in, con.getOutputStream());
                } catch (InvalidPathException e) {
                    throw new IOException(e);
                }

                if (con.getResponseCode() != 200) {
                    org.apache.commons.io.IOUtils.copy(con.getErrorStream(), System.err);
                }

                return ret;
            } catch (HttpRetryException e) {
                if (e.getLocation() != null) {
                    // retry with the new location
                    location = new URL(e.getLocation());
                    continue;
                }
                // otherwise failed for reasons beyond us.
                throw e;
            }
        }
    } finally {
        tmpFile.delete();
    }
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteDataExt(JSONObject obj) {
    String requestUrl;/*from w  w w. j a v  a 2s  .  c om*/
    String id;
    String method;
    String body;
    String headers;
    try {
        //Request url
        requestUrl = obj.getString("url");

        //ID that correlates the request to the event
        id = obj.getString("id");

        //Request method
        method = obj.getString("method");

        //Request body
        body = obj.getString("body");

        //Request header
        headers = obj.getString("headers");

        String js = null;
        if (method == null || method.length() == 0)
            method = "GET";

        HttpURLConnection connection = (HttpURLConnection) new URL(requestUrl).openConnection();
        boolean forceUTF8 = false;

        try {
            if (headers.length() > 0) {
                String[] headerArray = headers.split("&");

                //Set request header
                for (String header : headerArray) {
                    String[] headerPair = header.split("=");
                    if (headerPair.length == 2) {
                        String field = headerPair[0];
                        String value = headerPair[1];
                        if (field != null && value != null) {
                            if (!"content-length".equals(field.toLowerCase())) {//skip Content-Length - causes error because it is managed by the request
                                connection.setRequestProperty(field, value);
                            }

                            field = field.toLowerCase();
                            value = value.toLowerCase();
                            if (field.equals("content-type") && value.indexOf("charset") > -1
                                    && value.indexOf("utf-8") > -1) {
                                forceUTF8 = true;
                            }
                        }
                    }
                }

            }

            if ("POST".equalsIgnoreCase(method)) {
                connection.setRequestMethod(method);
                connection.setDoOutput(true);
                connection.setFixedLengthStreamingMode(body.length());
                DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
                dStream.writeBytes(body);
                dStream.flush();
                dStream.close();
            }

            //inject response
            int statusCode = connection.getResponseCode();

            final StringBuilder response = new StringBuilder();
            try {
                InputStream responseStream = connection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
                String line;
                while ((line = br.readLine()) != null) {
                    response.append(line);
                }
                br.close();
            } catch (Exception e) {
            }

            String responseBody = null;
            // how to handle UTF8 without EntityUtils?
            //                if (forceUTF8) {
            //                    responseBody = EntityUtils.toString(entity, "UTF-8");
            //                } else {
            //                    responseBody = EntityUtils.toString(entity);
            //                }
            responseBody = response.toString();
            String responseMessage = connection.getResponseMessage();

            char[] bom = { 0xef, 0xbb, 0xbf };
            //check for BOM characters, then strip if present
            if (responseBody.length() >= 3 && responseBody.charAt(0) == bom[0]
                    && responseBody.charAt(1) == bom[1] && responseBody.charAt(2) == bom[2]) {
                responseBody = responseBody.substring(3);
            }

            //escape existing backslashes
            responseBody = responseBody.replaceAll("\\\\", "\\\\\\\\");

            //escape internal double-quotes
            responseBody = responseBody.replaceAll("\"", "\\\\\"");
            responseBody = responseBody.replaceAll("'", "\\\\'");

            //replace linebreaks with \n
            responseBody = responseBody.replaceAll("\\r\\n|\\r|\\n", "\\\\n");

            StringBuilder extras = new StringBuilder("{");
            extras.append(String.format("status:'%d',", statusCode));

            String status = null;
            switch (statusCode) {
            case 200:
                status = "OK";
                break;
            case 201:
                status = "CREATED";
                break;
            case 202:
                status = "Accepted";
                break;
            case 203:
                status = "Partial Information";
                break;
            case 204:
                status = "No Response";
                break;
            case 301:
                status = "Moved";
                break;
            case 302:
                status = "Found";
                break;
            case 303:
                status = "Method";
                break;
            case 304:
                status = "Not Modified";
                break;
            case 400:
                status = "Bad request";
                break;
            case 401:
                status = "Unauthorized";
                break;
            case 402:
                status = "PaymentRequired";
                break;
            case 403:
                status = "Forbidden";
                break;
            case 404:
                status = "Not found";
                break;
            case 500:
                status = "Internal Error";
                break;
            case 501:
                status = "Not implemented";
                break;
            case 502:
                status = "Service temporarily overloaded";
                break;
            case 503:
                status = "Gateway timeout";
                break;
            }
            extras.append(String.format("statusText:'%s',", status));
            extras.append("headers: {");

            List<String> cookieData = new ArrayList<String>();
            Map<String, List<String>> allHeaders = connection.getHeaderFields();
            for (String key : allHeaders.keySet()) {
                if (key == null) {
                    continue;
                }
                String value = connection.getHeaderField(key);
                value = value.replaceAll("'", "\\\\'");
                if (key.toLowerCase().equals("set-cookie"))
                    cookieData.add(value);
                else
                    extras.append(String.format("'%s':'%s',", key, value));
            }

            String concatCookies = cookieData.toString();
            concatCookies = concatCookies.substring(0, concatCookies.length());
            extras.append(String.format("'Set-Cookie':'%s',",
                    concatCookies.substring(1, concatCookies.length() - 1)));

            String cookieArray = "[";
            for (int i = 0; i < cookieData.size(); i++)
                cookieArray += String.format("'%s',", cookieData.get(i));
            cookieArray += "]";

            extras.append("'All-Cookies': " + cookieArray);
            extras.append("} }");

            js = String.format(
                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=true;e.id='%s';e.response='%s';e.extras=%s;document.dispatchEvent(e);",
                    id, responseBody, extras.toString());

        } catch (Exception ex) {
            js = String.format(
                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=false;e.id='%s';e.response='';e.extras={};e.error='%s';document.dispatchEvent(e);",
                    id, ex.getMessage());
        } catch (OutOfMemoryError err) {
            js = String.format(
                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=false;e.id='%s';e.response='';e.extras={};e.error='%s';document.dispatchEvent(e);",
                    id, err.getMessage());
        } finally {
            connection.disconnect();
        }

        injectJS(js);

    } catch (Exception e) {
        Log.d("getRemoteDataExt", e.getMessage());
    }
}

From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java

/**
 * ?/*from   www .  jav  a  2 s.  com*/
 * @param appWorkspace  ?
 * @param source        ?
 * @param target        ??
 * @param args          JSONArray
 * @param callbackCtx   nativejs
 *
 * args[2] fileKey       ?name file?
 * args[3] fileName      ??? image.jpg?
 * args[4] mimeType      ?mimeimage/jpeg?
 * args[5] params        HTTP????/
 * args[6] trustEveryone 
 * args[7] chunkedMode   ??????true
 * @return FileUploadResult
 */
private XExtensionResult upload(String appWorkspace, String source, String target, JSONArray args,
        XCallbackContext callbackCtx) {
    XLog.d(CLASS_NAME, "upload " + source + " to " + target);

    HttpURLConnection conn = null;
    try {
        String fileKey = getArgument(args, 2, "file");
        String fileName = getArgument(args, 3, "image.jpg");
        String mimeType = getArgument(args, 4, "image/jpeg");
        JSONObject params = args.optJSONObject(5);
        if (params == null) {
            params = new JSONObject();
        }
        boolean trustEveryone = args.optBoolean(6);
        boolean chunkedMode = args.optBoolean(7) || args.isNull(7);
        JSONObject headers = args.optJSONObject(8);
        if (headers == null && params != null) {
            headers = params.optJSONObject("headers");
        }
        String objectId = args.getString(9);
        //------------------ 
        URL url = new URL(target);
        conn = getURLConnection(url, trustEveryone);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
        setCookieProperty(conn, target);
        // ??
        handleRequestHeader(headers, conn);
        byte[] extraBytes = extraBytesFromParams(params, fileKey);

        String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END;
        String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;
        byte[] fileNameBytes = fileName.getBytes(ENCODING_TYPE);

        FileInputStream fileInputStream = (FileInputStream) getPathFromUri(appWorkspace, source);
        int maxBufferSize = XConstant.BUFFER_LEN;

        if (chunkedMode) {
            conn.setChunkedStreamingMode(maxBufferSize);
        } else {
            int stringLength = extraBytes.length + midParams.length() + tailParams.length()
                    + fileNameBytes.length;
            XLog.d(CLASS_NAME, "String Length: " + stringLength);
            int fixedLength = (int) fileInputStream.getChannel().size() + stringLength;
            XLog.d(CLASS_NAME, "Content Length: " + fixedLength);
            conn.setFixedLengthStreamingMode(fixedLength);
        }
        // ???
        OutputStream ouputStream = conn.getOutputStream();
        DataOutputStream dos = new DataOutputStream(ouputStream);
        dos.write(extraBytes);
        dos.write(fileNameBytes);
        dos.writeBytes(midParams);
        XFileUploadResult result = new XFileUploadResult();
        FileTransferProgress progress = new FileTransferProgress();
        int bytesAvailable = fileInputStream.available();
        int bufferSize = Math.min(bytesAvailable, maxBufferSize);
        byte[] buffer = new byte[bufferSize];
        int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        long totalBytes = 0;

        while (bytesRead > 0) {
            totalBytes += bytesRead;
            result.setBytesSent(totalBytes);
            dos.write(buffer, 0, bytesRead);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            if (objectId != null) {
                //?js??object ID?
                progress.setTotal(bytesAvailable);
                XLog.d(CLASS_NAME, "total=" + bytesAvailable);
                progress.setLoaded(totalBytes);
                progress.setLengthComputable(true);
                XExtensionResult progressResult = new XExtensionResult(XExtensionResult.Status.OK,
                        progress.toJSONObject());
                progressResult.setKeepCallback(true);
                callbackCtx.sendExtensionResult(progressResult);
            }
            synchronized (abortTriggered) {
                if (objectId != null && abortTriggered.contains(objectId)) {
                    abortTriggered.remove(objectId);
                    throw new AbortException(ABORT_EXCEPTION_UPLOAD_ABORTED);
                }
            }
        }
        dos.writeBytes(tailParams);
        fileInputStream.close();
        dos.flush();
        dos.close();
        checkConnection(conn);
        setUploadResult(result, conn);

        // 
        if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
            ((HttpsURLConnection) conn).setHostnameVerifier(mDefaultHostnameVerifier);
            HttpsURLConnection.setDefaultSSLSocketFactory(mDefaultSSLSocketFactory);
        }

        XLog.d(CLASS_NAME, "****** About to return a result from upload");
        return new XExtensionResult(XExtensionResult.Status.OK, result.toJSONObject());

    } catch (AbortException e) {
        JSONObject error = createFileTransferError(ABORTED_ERR, source, target, conn);
        return new XExtensionResult(XExtensionResult.Status.ERROR, error);
    } catch (FileNotFoundException e) {
        JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
        XLog.e(CLASS_NAME, error.toString());
        return new XExtensionResult(XExtensionResult.Status.ERROR, error);
    } catch (MalformedURLException e) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn);
        XLog.e(CLASS_NAME, error.toString());
        return new XExtensionResult(XExtensionResult.Status.ERROR, error);
    } catch (IOException e) {
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        XLog.e(CLASS_NAME, error.toString());
        return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error);
    } catch (JSONException e) {
        XLog.e(CLASS_NAME, e.getMessage());
        return new XExtensionResult(XExtensionResult.Status.JSON_EXCEPTION);
    } catch (Throwable t) {
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        XLog.e(CLASS_NAME, error.toString());
        return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}