Example usage for java.net HttpURLConnection setChunkedStreamingMode

List of usage examples for java.net HttpURLConnection setChunkedStreamingMode

Introduction

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

Prototype

public void setChunkedStreamingMode(int chunklen) 

Source Link

Document

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

Usage

From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java

public String doRedirect(String urlRedirect) {
    // android.os.Debug.waitForDebugger();
    try {//from w w  w .ja va 2  s.  co  m

        Log.d(TAG, "mOcp.m_redirect_uri=" + mOcp.m_redirect_uri);

        Log.d(TAG, "urlRedirect=" + urlRedirect);

        // with server phpOIDC, check for '#'
        if ((urlRedirect.startsWith(mOcp.m_redirect_uri + "?"))
                || (urlRedirect.startsWith(mOcp.m_redirect_uri + "#"))) {
            Log.d(TAG, "doRedirect : in check");

            String[] params = urlRedirect.substring(mOcp.m_redirect_uri.length() + 1).split("&");
            String code = "";
            String state = "";
            String state_key = "state";
            for (int i = 0; i < params.length; i++) {
                String param = params[i];
                int idxEqual = param.indexOf('=');
                if (idxEqual >= 0) {
                    String key = param.substring(0, idxEqual);
                    String value = param.substring(idxEqual + 1);
                    if (key.startsWith("code"))
                        code = value;
                    if (key.startsWith("state"))
                        state = value;
                    if (key.startsWith("session_state")) {
                        state = value;
                        state_key = "session_state";
                    }
                }
            }

            // display code and state
            Logd(TAG, "doRedirect => code: " + code + " / state: " + state);

            // doRepost(code,state);
            if (code.length() > 0) {

                // get token_endpoint endpoint
                String token_endpoint = getEndpointFromConfigOidc("token_endpoint", mOcp.m_server_url);

                Log.d(TAG, "token_endpoint=" + token_endpoint);

                if (isEmpty(token_endpoint)) {
                    Logd(TAG, "logout : could not get token_endpoint on server : " + mOcp.m_server_url);
                    return null;
                }

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                HttpURLConnection huc = getHUC(token_endpoint);
                huc.setInstanceFollowRedirects(false);

                if (mUsePrivateKeyJWT) {
                    nameValuePairs.add(new BasicNameValuePair("client_assertion_type",
                            "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"));
                    String client_assertion = secureProxy.getPrivateKeyJwt(token_endpoint);
                    Logd(TAG, "client_assertion: " + client_assertion);
                    nameValuePairs.add(new BasicNameValuePair("client_assertion", client_assertion));
                } else {
                    huc.setRequestProperty("Authorization", "Basic " + secureProxy.getClientSecretBasic());
                }

                huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                huc.setDoOutput(true);
                huc.setChunkedStreamingMode(0);

                OutputStream os = huc.getOutputStream();
                OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8");
                BufferedWriter writer = new BufferedWriter(out);

                nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
                Logd(TAG, "code: " + code);
                nameValuePairs.add(new BasicNameValuePair("code", code));
                nameValuePairs.add(new BasicNameValuePair("redirect_uri", mOcp.m_redirect_uri));
                Logd(TAG, "redirect_uri" + mOcp.m_redirect_uri);
                if (state != null && state.length() > 0)
                    nameValuePairs.add(new BasicNameValuePair(state_key, state));

                // write URL encoded string from list of key value pairs
                writer.write(getQuery(nameValuePairs));
                writer.flush();
                writer.close();
                out.close();
                os.close();

                Logd(TAG, "doRedirect => before connect");
                Logd(TAG, "huc=" + huc.toString());
                huc.connect();
                Logd(TAG, "huc2=" + huc.getContentEncoding());
                int responseCode = huc.getResponseCode();
                System.out.println("2 - code " + responseCode);
                Log.d(TAG, "doRedirect => responseCode " + responseCode);
                InputStream in = null;
                try {
                    in = new BufferedInputStream(huc.getInputStream());
                } catch (IOException ioe) {
                    sysout("io exception: " + huc.getErrorStream());
                }
                if (in != null) {
                    String result = convertStreamToString(in);
                    // now you have the string representation of the HTML request
                    in.close();

                    Logd(TAG, "doRedirect: " + result);

                    // save as static for now
                    return result;

                } else {
                    Logd(TAG, "doRedirect null");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:net.myrrix.client.ClientRecommender.java

/**
 * @param replica host and port of replica to connect to
 * @param path URL to access (relative to context root)
 * @param method HTTP method to use/* w  w w  .  j av  a2s .c o m*/
 * @param doOutput if true, will need to write data into the request body
 * @param chunkedStreaming if true, use chunked streaming to accommodate a large upload, if possible
 * @param requestProperties additional request key/value pairs or {@code null} for none
 */
private HttpURLConnection buildConnectionToReplica(HostAndPort replica, String path, String method,
        boolean doOutput, boolean chunkedStreaming, Map<String, String> requestProperties) throws IOException {
    String contextPath = config.getContextPath();
    if (contextPath != null) {
        path = '/' + contextPath + path;
    }
    String protocol = config.isSecure() ? "https" : "http";
    URL url;
    try {
        url = new URL(protocol, replica.getHostText(), replica.getPort(), path);
    } catch (MalformedURLException mue) {
        // can't happen
        throw new IllegalStateException(mue);
    }
    log.debug("{} {}", method, url);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(method);
    connection.setDoInput(true);
    connection.setDoOutput(doOutput);
    connection.setUseCaches(false);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty(HttpHeaders.ACCEPT, DESIRED_RESPONSE_CONTENT_TYPE);
    if (closeConnection) {
        connection.setRequestProperty(HttpHeaders.CONNECTION, "close");
    }
    if (chunkedStreaming) {
        if (needAuthentication) {
            // Must buffer in memory if using authentication since it won't handle the authorization challenge
            log.debug("Authentication is enabled, so ingest data must be buffered in memory");
        } else {
            connection.setChunkedStreamingMode(0); // Use default buffer size
        }
    }
    if (requestProperties != null) {
        for (Map.Entry<String, String> entry : requestProperties.entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    return connection;
}

From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java

public String doRedirect(String urlRedirect, boolean useTim) {
    // android.os.Debug.waitForDebugger();
    try {// w w  w .ja v a 2  s .  c om
        // with server phpOIDC, check for '#'
        if ((urlRedirect.startsWith(mOcp.m_redirect_uri + "?"))
                || (urlRedirect.startsWith(mOcp.m_redirect_uri + "#"))) {
            String[] params = urlRedirect.substring(mOcp.m_redirect_uri.length() + 1).split("&");
            String code = "";
            String state = "";
            String state_key = "state";
            for (int i = 0; i < params.length; i++) {
                String param = params[i];
                int idxEqual = param.indexOf('=');
                if (idxEqual >= 0) {
                    String key = param.substring(0, idxEqual);
                    String value = param.substring(idxEqual + 1);
                    if (key.startsWith("code"))
                        code = value;
                    if (key.startsWith("state"))
                        state = value;
                    if (key.startsWith("session_state")) {
                        state = value;
                        state_key = "session_state";
                    }
                }
            }

            // display code and state
            Logd(TAG, "doRedirect => code: " + code + " / state: " + state);

            // doRepost(code,state);
            if (code.length() > 0) {

                // get token_endpoint endpoint
                String token_endpoint = getEndpointFromConfigOidc("token_endpoint", mOcp.m_server_url);
                if (isEmpty(token_endpoint)) {
                    Logd(TAG, "logout : could not get token_endpoint on server : " + mOcp.m_server_url);
                    return null;
                }

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                HttpURLConnection huc = getHUC(token_endpoint);
                huc.setInstanceFollowRedirects(false);

                if (useTim) {
                    if (mUsePrivateKeyJWT) {
                        nameValuePairs.add(new BasicNameValuePair("client_assertion_type",
                                "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"));
                        String client_assertion = secureStorage.getPrivateKeyJwt(token_endpoint);
                        Logd(TAG, "client_assertion: " + client_assertion);
                        nameValuePairs.add(new BasicNameValuePair("client_assertion", client_assertion));
                    } else {
                        huc.setRequestProperty("Authorization",
                                "Basic " + secureStorage.getClientSecretBasic());
                    }
                } else {
                    String authorization = (mOcp.m_client_id + ":" + mOcp.m_client_secret);
                    authorization = Base64.encodeToString(authorization.getBytes(), Base64.DEFAULT);
                    huc.setRequestProperty("Authorization", "Basic " + authorization);
                }

                huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                huc.setDoOutput(true);
                huc.setChunkedStreamingMode(0);

                OutputStream os = huc.getOutputStream();
                OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8");
                BufferedWriter writer = new BufferedWriter(out);

                nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
                nameValuePairs.add(new BasicNameValuePair("code", code));
                nameValuePairs.add(new BasicNameValuePair("redirect_uri", mOcp.m_redirect_uri));
                if (state != null && state.length() > 0)
                    nameValuePairs.add(new BasicNameValuePair(state_key, state));

                // write URL encoded string from list of key value pairs
                writer.write(getQuery(nameValuePairs));
                writer.flush();
                writer.close();
                out.close();
                os.close();

                Logd(TAG, "doRedirect => before connect");
                huc.connect();
                int responseCode = huc.getResponseCode();
                System.out.println("2 - code " + responseCode);
                Log.d(TAG, "doRedirect => responseCode " + responseCode);
                InputStream in = null;
                try {
                    in = new BufferedInputStream(huc.getInputStream());
                } catch (IOException ioe) {
                    sysout("io exception: " + huc.getErrorStream());
                }
                if (in != null) {
                    String result = convertStreamToString(in);
                    // now you have the string representation of the HTML request
                    in.close();

                    Logd(TAG, "doRedirect: " + result);

                    // save as static for now
                    return result;

                } else {
                    Logd(TAG, "doRedirect null");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

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

/**
 * ?//from  w  ww .j  a  v  a2 s  .co m
 * @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();
        }
    }
}

From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java

/**
 * Uploads the specified file to the server URL provided using an HTTP multipart request.
 * @param source        Full path of the file on the file system
 * @param target        URL of the server to receive the file
 * @param args          JSON Array of args
 * @param callbackContext    callback id for optional progress reports
 *
 * args[2] fileKey       Name of file request parameter
 * args[3] fileName      File name to be used on server
 * args[4] mimeType      Describes file content type
 * args[5] params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 *//*from  w w w.  ja va  2 s . c  o  m*/
private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext)
        throws JSONException {
    Log.d(LOG_TAG, "upload " + source + " to " + target);

    // Setup the options
    final String mimeType = getArgument(args, 4, "image/jpeg");
    final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5);
    final boolean trustEveryone = args.optBoolean(6);
    // Always use chunked mode unless set to false as per API
    final boolean chunkedMode = args.optBoolean(7) || args.isNull(7);
    // Look for headers on the params map for backwards compatibility with older Cordova versions.
    final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers")
            : args.optJSONObject(8);
    final String objectId = args.getString(9);
    final String httpMethod = getArgument(args, 10, "POST");

    final CordovaResourceApi resourceApi = webView.getResourceApi();

    Log.d(LOG_TAG, "mimeType: " + mimeType);
    Log.d(LOG_TAG, "params: " + params);
    Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
    Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);
    Log.d(LOG_TAG, "headers: " + headers);
    Log.d(LOG_TAG, "objectId: " + objectId);
    Log.d(LOG_TAG, "httpMethod: " + httpMethod);

    final Uri targetUri = resourceApi.remapUri(Uri.parse(target));
    // Accept a path or a URI for the source.
    Uri tmpSrc = Uri.parse(source);
    final Uri sourceUri = resourceApi
            .remapUri(tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source)));

    int uriType = CordovaResourceApi.getUriType(targetUri);
    final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
    if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0);
        Log.e(LOG_TAG, "Unsupported URI: " + targetUri);
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
        return;
    }

    final RequestContext context = new RequestContext(source, target, callbackContext);
    synchronized (activeRequests) {
        activeRequests.put(objectId, context);
    }

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            if (context.aborted) {
                return;
            }
            HttpURLConnection conn = null;
            HostnameVerifier oldHostnameVerifier = null;
            SSLSocketFactory oldSocketFactory = null;
            int totalBytes = 0;
            int fixedLength = -1;
            try {
                // Create return object
                PSFileUploadResult result = new PSFileUploadResult();
                PSFileProgressResult progress = new PSFileProgressResult();

                //------------------ CLIENT REQUEST
                // Open a HTTP connection to the URL based on protocol
                conn = resourceApi.createHttpConnection(targetUri);
                if (useHttps && trustEveryone) {
                    // Setup the HTTPS connection class to trust everyone
                    HttpsURLConnection https = (HttpsURLConnection) conn;
                    oldSocketFactory = trustAllHosts(https);
                    // Save the current hostnameVerifier
                    oldHostnameVerifier = https.getHostnameVerifier();
                    // Setup the connection not to verify hostnames
                    https.setHostnameVerifier(DO_NOT_VERIFY);
                }

                // Allow Inputs
                conn.setDoInput(true);

                // Allow Outputs
                conn.setDoOutput(true);

                // Don't use a cached copy.
                conn.setUseCaches(false);

                // Use a post method.
                conn.setRequestMethod(httpMethod);
                conn.setRequestProperty("Content-Type", mimeType);

                // Set the cookies on the response
                String cookie = CookieManager.getInstance().getCookie(target);
                if (cookie != null) {
                    conn.setRequestProperty("Cookie", cookie);
                }

                // Handle the other headers
                if (headers != null) {
                    addHeadersToRequest(conn, headers);
                }

                // Get a input stream of the file on the phone
                OpenForReadResult readResult = resourceApi.openForRead(sourceUri);

                if (readResult.length >= 0) {
                    fixedLength = (int) readResult.length;
                    progress.setLengthComputable(true);
                    progress.setTotal(fixedLength);
                }
                Log.d(LOG_TAG, "Content Length: " + fixedLength);
                // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices.
                // http://code.google.com/p/android/issues/detail?id=3164
                // It also causes OOM if HTTPS is used, even on newer devices.
                boolean useChunkedMode = chunkedMode
                        && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps);
                useChunkedMode = useChunkedMode || (fixedLength == -1);

                if (useChunkedMode) {
                    conn.setChunkedStreamingMode(MAX_BUFFER_SIZE);
                    // Although setChunkedStreamingMode sets this header, setting it explicitly here works
                    // around an OutOfMemoryException when using https.
                    conn.setRequestProperty("Transfer-Encoding", "chunked");
                } else {
                    conn.setFixedLengthStreamingMode(fixedLength);
                }

                conn.connect();

                OutputStream sendStream = null;
                try {
                    sendStream = conn.getOutputStream();
                    synchronized (context) {
                        if (context.aborted) {
                            return;
                        }
                        context.currentOutputStream = sendStream;
                    }
                    //We don't want to change encoding, we just want this to write for all Unicode.

                    // create a buffer of maximum size
                    int bytesAvailable = readResult.inputStream.available();
                    int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                    byte[] buffer = new byte[bufferSize];

                    // read file and write it into form...
                    int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);

                    long prevBytesRead = 0;
                    while (bytesRead > 0) {
                        result.setBytesSent(totalBytes);
                        sendStream.write(buffer, 0, bytesRead);
                        totalBytes += bytesRead;
                        if (totalBytes > prevBytesRead + 102400) {
                            prevBytesRead = totalBytes;
                            Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes");
                        }
                        bytesAvailable = readResult.inputStream.available();
                        bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                        bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);

                        // Send a progress event.
                        progress.setLoaded(totalBytes);
                        PluginResult progressResult = new PluginResult(PluginResult.Status.OK,
                                progress.toJSONObject());
                        progressResult.setKeepCallback(true);
                        context.sendPluginResult(progressResult);
                    }

                    sendStream.flush();
                } finally {
                    safeClose(readResult.inputStream);
                    safeClose(sendStream);
                }
                context.currentOutputStream = null;
                Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength);

                //------------------ read the SERVER RESPONSE
                String responseString;
                int responseCode = conn.getResponseCode();
                Log.d(LOG_TAG, "response code: " + responseCode);
                Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields());
                TrackingInputStream inStream = null;
                try {
                    inStream = getInputStream(conn);
                    synchronized (context) {
                        if (context.aborted) {
                            return;
                        }
                        context.currentInputStream = inStream;
                    }

                    ByteArrayOutputStream out = new ByteArrayOutputStream(
                            Math.max(1024, conn.getContentLength()));
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    // write bytes to file
                    while ((bytesRead = inStream.read(buffer)) > 0) {
                        out.write(buffer, 0, bytesRead);
                    }
                    responseString = out.toString("UTF-8");
                } finally {
                    context.currentInputStream = null;
                    safeClose(inStream);
                }

                Log.d(LOG_TAG, "got response from server");
                Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length())));

                // send request and retrieve response
                result.setResponseCode(responseCode);
                result.setResponse(responseString);

                context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject()));
            } catch (FileNotFoundException e) {
                JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
                Log.e(LOG_TAG, error.toString(), e);
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } catch (IOException e) {
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
                Log.e(LOG_TAG, error.toString(), e);
                Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes.");
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
            } catch (Throwable t) {
                // Shouldn't happen, but will
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
                Log.e(LOG_TAG, error.toString(), t);
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } finally {
                synchronized (activeRequests) {
                    activeRequests.remove(objectId);
                }

                if (conn != null) {
                    // Revert back to the proper verifier and socket factories
                    // Revert back to the proper verifier and socket factories
                    if (trustEveryone && useHttps) {
                        HttpsURLConnection https = (HttpsURLConnection) conn;
                        https.setHostnameVerifier(oldHostnameVerifier);
                        https.setSSLSocketFactory(oldSocketFactory);
                    }
                }
            }
        }
    });
}

From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java

protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers,
        Output writer, BindingSession session, BigInteger offset, BigInteger length) {
    try {/*from w  ww. jav a  2s. c  o m*/
        // log before connect
        //Log.d("URL", url.toString());
        if (LOG.isDebugEnabled()) {
            LOG.debug(method + " " + url);
        }

        // connect
        HttpURLConnection conn = getHttpURLConnection(new URL(url.toString()));
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty(HTTP.USER_AGENT, ClientVersion.OPENCMIS_CLIENT);

        // timeouts
        int connectTimeout = session.get(SessionParameter.CONNECT_TIMEOUT, -1);
        if (connectTimeout >= 0) {
            conn.setConnectTimeout(connectTimeout);
        }

        int readTimeout = session.get(SessionParameter.READ_TIMEOUT, -1);
        if (readTimeout >= 0) {
            conn.setReadTimeout(readTimeout);
        }

        // set content type
        if (contentType != null) {
            conn.setRequestProperty(HTTP.CONTENT_TYPE, contentType);
        }
        // set other headers
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                conn.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // authenticate
        AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session);
        if (authProvider != null) {
            Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString());
            if (httpHeaders != null) {
                for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                    if (header.getValue() != null) {
                        for (String value : header.getValue()) {
                            conn.addRequestProperty(header.getKey(), value);
                        }
                    }
                }
            }

            if (conn instanceof HttpsURLConnection) {
                SSLSocketFactory sf = authProvider.getSSLSocketFactory();
                if (sf != null) {
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sf);
                }

                HostnameVerifier hv = authProvider.getHostnameVerifier();
                if (hv != null) {
                    ((HttpsURLConnection) conn).setHostnameVerifier(hv);
                }
            }
        }

        // range
        if ((offset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((offset == null) || (offset.signum() == -1)) {
                offset = BigInteger.ZERO;
            }

            sb.append(offset.toString());
            sb.append("-");

            if ((length != null) && (length.signum() == 1)) {
                sb.append(offset.add(length.subtract(BigInteger.ONE)).toString());
            }

            conn.setRequestProperty("Range", sb.toString());
        }

        // compression
        Object compression = session.get(AlfrescoSession.HTTP_ACCEPT_ENCODING);
        if (compression == null) {
            conn.setRequestProperty("Accept-Encoding", "");
        } else {
            Boolean compressionValue;
            try {
                compressionValue = Boolean.parseBoolean(compression.toString());
                if (compressionValue) {
                    conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
                } else {
                    conn.setRequestProperty("Accept-Encoding", "");
                }
            } catch (Exception e) {
                conn.setRequestProperty("Accept-Encoding", compression.toString());
            }
        }

        // locale
        if (session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) instanceof String
                && session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) != null) {
            conn.setRequestProperty("Accept-Language",
                    session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE).toString());
        }

        // send data
        if (writer != null) {
            Object chunkTransfert = session.get(AlfrescoSession.HTTP_CHUNK_TRANSFERT);
            if (chunkTransfert != null && Boolean.parseBoolean(chunkTransfert.toString())) {
                conn.setRequestProperty(HTTP.TRANSFER_ENCODING, "chunked");
                conn.setChunkedStreamingMode(0);
            }

            conn.setConnectTimeout(900000);

            OutputStream connOut = null;

            Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION);
            if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                conn.setRequestProperty(HTTP.CONTENT_ENCODING, "gzip");
                connOut = new GZIPOutputStream(conn.getOutputStream(), 4096);
            } else {
                connOut = conn.getOutputStream();
            }

            OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
            writer.write(out);
            out.flush();
        }

        // connect
        conn.connect();

        // get stream, if present
        int respCode = conn.getResponseCode();
        InputStream inputStream = null;
        if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED)
                || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION)
                || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) {
            inputStream = conn.getInputStream();
        }

        // log after connect
        if (LOG.isTraceEnabled()) {
            LOG.trace(method + " " + url + " > Headers: " + conn.getHeaderFields());
        }

        // forward response HTTP headers
        if (authProvider != null) {
            authProvider.putResponseHeaders(url.toString(), respCode, conn.getHeaderFields());
        }

        // get the response
        return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream,
                conn.getErrorStream());
    } catch (Exception e) {
        throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e);
    }
}

From source file:org.skt.runtime.html5apis.file.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP multipart request.
 * @param source        Full path of the file on the file system
 * @param target        URL of the server to receive the file
 * @param args          JSON Array of args
 *
 * args[2] fileKey       Name of file request parameter
 * args[3] fileName      File name to be used on server
 * args[4] mimeType      Describes file content type
 * args[5] params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 *//* w  ww  .  j  av a 2  s.  co  m*/
private PluginResult upload(String source, String target, JSONArray args) {
    Log.d(LOG_TAG, "upload " + source + " to " + target);

    HttpURLConnection conn = null;
    try {
        // Setup the options
        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); //Always use chunked mode unless set to false as per API

        Log.d(LOG_TAG, "fileKey: " + fileKey);
        Log.d(LOG_TAG, "fileName: " + fileName);
        Log.d(LOG_TAG, "mimeType: " + mimeType);
        Log.d(LOG_TAG, "params: " + params);
        Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
        Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);

        // Create return object
        FileUploadResult result = new FileUploadResult();

        // Get a input stream of the file on the phone
        FileInputStream fileInputStream = (FileInputStream) getPathFromUri(source);

        DataOutputStream dos = null;

        int bytesRead, bytesAvailable, bufferSize;
        long totalBytes;
        byte[] buffer;
        int maxBufferSize = 8096;

        //------------------ CLIENT REQUEST
        // open a URL connection to the server
        URL url = new URL(target);

        // Open a HTTP connection to the URL based on protocol
        if (url.getProtocol().toLowerCase().equals("https")) {
            // Using standard HTTPS connection. Will not allow self signed certificate
            if (!trustEveryone) {
                conn = (HttpsURLConnection) url.openConnection();
            }
            // Use our HTTPS connection that blindly trusts everyone.
            // This should only be used in debug environments
            else {
                // Setup the HTTPS connection class to trust everyone
                trustAllHosts();
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                // Save the current hostnameVerifier
                defaultHostnameVerifier = https.getHostnameVerifier();
                // Setup the connection not to verify hostnames
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            }
        }
        // Return a standard HTTP connection
        else {
            conn = (HttpURLConnection) url.openConnection();
        }

        // Allow Inputs
        conn.setDoInput(true);

        // Allow Outputs
        conn.setDoOutput(true);

        // Don't use a cached copy.
        conn.setUseCaches(false);

        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

        // Handle the other headers
        try {
            JSONObject headers = params.getJSONObject("headers");
            for (Iterator iter = headers.keys(); iter.hasNext();) {
                String headerKey = iter.next().toString();
                conn.setRequestProperty(headerKey, headers.getString(headerKey));
            }
        } catch (JSONException e1) {
            // No headers to be manipulated!
        }

        // Set the cookies on the response
        String cookie = CookieManager.getInstance().getCookie(target);
        if (cookie != null) {
            conn.setRequestProperty("Cookie", cookie);
        }

        /*
        * Store the non-file portions of the multipart data as a string, so that we can add it
        * to the contentSize, since it is part of the body of the HTTP request.
        */
        String extraParams = "";
        try {
            for (Iterator iter = params.keys(); iter.hasNext();) {
                Object key = iter.next();
                if (!String.valueOf(key).equals("headers")) {
                    extraParams += LINE_START + BOUNDARY + LINE_END;
                    extraParams += "Content-Disposition: form-data; name=\"" + key.toString() + "\";";
                    extraParams += LINE_END + LINE_END;
                    extraParams += params.getString(key.toString());
                    extraParams += LINE_END;
                }
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }

        extraParams += LINE_START + BOUNDARY + LINE_END;
        extraParams += "Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"";

        String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END;
        String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;

        // Should set this up as an option
        if (chunkedMode) {
            conn.setChunkedStreamingMode(maxBufferSize);
        } else {
            int stringLength = extraParams.getBytes("UTF-8").length + midParams.getBytes("UTF-8").length
                    + tailParams.getBytes("UTF-8").length + fileName.getBytes("UTF-8").length;
            Log.d(LOG_TAG, "String Length: " + stringLength);
            int fixedLength = (int) fileInputStream.getChannel().size() + stringLength;
            Log.d(LOG_TAG, "Content Length: " + fixedLength);
            conn.setFixedLengthStreamingMode(fixedLength);
        }

        dos = new DataOutputStream(conn.getOutputStream());
        dos.write(extraParams.getBytes("UTF-8"));
        //We don't want to chagne encoding, we just want this to write for all Unicode.
        dos.write(fileName.getBytes("UTF-8"));
        dos.write(midParams.getBytes("UTF-8"));

        // create a buffer of maximum size
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        totalBytes = 0;

        while (bytesRead > 0) {
            totalBytes += bytesRead;
            result.setBytesSent(totalBytes);
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.write(tailParams.getBytes("UTF-8"));

        // close streams
        fileInputStream.close();
        dos.flush();
        dos.close();

        //------------------ read the SERVER RESPONSE
        StringBuffer responseString = new StringBuffer("");
        DataInputStream inStream;
        try {
            inStream = new DataInputStream(conn.getInputStream());
        } catch (FileNotFoundException e) {
            Log.e(LOG_TAG, e.toString(), e);
            throw new IOException("Received error from server");
        }

        String line;
        while ((line = inStream.readLine()) != null) {
            responseString.append(line);
        }
        Log.d(LOG_TAG, "got response from server");
        Log.d(LOG_TAG, responseString.toString());

        // send request and retrieve response
        result.setResponseCode(conn.getResponseCode());
        result.setResponse(responseString.toString());

        inStream.close();

        // Revert back to the proper verifier and socket factories
        if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
            ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
            HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
        }

        Log.d(LOG_TAG, "****** About to return a result from upload");
        return new PluginResult(PluginResult.Status.OK, result.toJSONObject());

    } catch (FileNotFoundException e) {
        JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (MalformedURLException e) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (IOException e) {
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    } catch (Throwable t) {
        // Shouldn't happen, but will
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        Log.wtf(LOG_TAG, error.toString(), t);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}