Example usage for android.util Base64 encodeToString

List of usage examples for android.util Base64 encodeToString

Introduction

In this page you can find the example usage for android.util Base64 encodeToString.

Prototype

public static String encodeToString(byte[] input, int flags) 

Source Link

Document

Base64-encode the given data and return a newly allocated String with the result.

Usage

From source file:com.vanda.beivandalibnetwork.utils.HttpUtils.java

/**
 * //from  ww w  . jav  a 2 s  .c  o m
 * 
 * @param request
 * @param username
 * @param password
 * @return
 */
@TargetApi(Build.VERSION_CODES.FROYO)
public static HttpUriRequest authenticate(HttpUriRequest request, String username, String password) {
    request.addHeader(HEADER_AUTHORIZATION,
            AUTH_METHOD_BASIC + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
    return request;
}

From source file:fm.krui.kruifm.TwitterManager.java

/**
 * Encodes consumer key and consumer secret using RFC 1783 and formats the result according
 * to Twitter's requirements for authorization.
 * @param consumerKey Consumer Key/*w  w  w . j a  v  a2 s  .c o m*/
 * @param consumerSecret Consumer Secret
 * @return Processed string
 */
private String encodeCredentials(String consumerKey, String consumerSecret) {

    // Encode credentials according to RFC 1739
    String consumerKey1379 = null;
    String consumerSecret1379 = null;
    try {
        consumerKey1379 = URLEncoder.encode(consumerKey, "UTF-8");
        consumerSecret1379 = URLEncoder.encode(consumerSecret, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "Could not encode auth credentials!");
        e.printStackTrace();
    }

    // Concatenate the encoded consumer key and secret with a colon
    String singleKey = consumerKey1379 + ":" + consumerSecret1379;

    // Encode single key using base64 and return result
    byte[] keyBytes = singleKey.getBytes();
    String finalKey = Base64.encodeToString(keyBytes, Base64.NO_WRAP);
    Log.v(TAG, "Final key created: " + finalKey);
    return finalKey;
}

From source file:de.tum.frm2.nicos_android.nicos.NicosClient.java

public void connect(ConnectionData connData, Object[] eventmask) throws RuntimeException {
    if (connected) {
        throw new RuntimeException("client already connected");
    }//from   www  .ja v a2s. c  o  m
    disconnecting = false;

    SocketAddress sockaddr;
    try {
        // If ANY code of this scope failes, communication is entirely impossible.
        // That means, no need to catch all exceptions one by one.
        InetAddress addr = InetAddress.getByName(connData.getHost());
        sockaddr = new InetSocketAddress(addr, connData.getPort());

        // Initialize empty socket.
        socket = new Socket();

        // Connects this socket to the server with a specified timeout value
        // If timeout occurs, SocketTimeoutException is thrown
        socket.connect(sockaddr, TIMEOUT);
        socketOut = socket.getOutputStream();
        socketIn = socket.getInputStream();

        // Write client identification: we are a new client
        socketOut.write(client_id);
    } catch (Exception e) {
        String msg;
        if (e instanceof IOException) {
            // "null reference" error messages won't help the user.
            msg = "Socket communication failed (server not responding).";
        } else {
            msg = "Server connection failed: " + e.getMessage() + ".";
        }
        signal("failed", msg);
        return;
    }

    // read banner
    try {
        TupleOfTwo<Byte, Object> response = _read();
        byte ret = response.getFirst();
        if (ret != daemon.STX) {
            throw new ProtocolError("invalid response format");
        }
        nicosBanner = (HashMap) response.getSecond();
        if (!nicosBanner.containsKey("daemon_version")) {
            throw new ProtocolError("daemon version missing from response");
        }
        int daemon_proto = (int) nicosBanner.get("protocol_version");
        if (!daemon.isProtoVersionCompatible(daemon_proto)) {
            throw new ProtocolError("daemon uses protocol " + String.valueOf(daemon_proto)
                    + ", but this client requires protocol " + String.valueOf(daemon.PROTO_VERSIONS[0]));
        }
    } catch (Exception e) {
        signal("failed", "Server(" + connData.getHost() + ":" + String.valueOf(connData.getPort())
                + ") handshake failed: " + e.getMessage());
        return;
    }

    // log-in sequence
    char[] password = connData.getPassword();
    Object unwrap = nicosBanner.get("pw_hashing");
    String pw_hashing = "sha1";
    if (unwrap != null) {
        pw_hashing = unwrap.toString();
    }

    String encryptedPassword = null;
    boolean supportsRSA = false;
    try {
        String rsaSupportString = pw_hashing.substring(0, 4);
        supportsRSA = rsaSupportString.equals("rsa,");
    } catch (StringIndexOutOfBoundsException e) {
        // Does not start with "rsa," -> does not support RSA encryption.
        // boolean supportsRSA stays at false.
    }
    if (supportsRSA) {
        byte[] keyBytes = Base64.decode(nicosBanner.get("rsakey").toString(), Base64.DEFAULT);
        String publicKeyString = new String(keyBytes, StandardCharsets.UTF_8);
        PublicKey publicKey = extractPublicKey(publicKeyString);

        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
        } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) {
            // Cannot happen.
        }
        try {
            if (cipher != null) {
                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            } else {
                throw new InvalidKeyException();
            }
        } catch (InvalidKeyException e) {
            throw new RuntimeException("The server's RSA key is invalid or incompatible.");
        }

        byte[] encrypted;
        try {
            encrypted = cipher.doFinal(String.valueOf(password).getBytes());
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
            encrypted = new byte[0];
        }
        encryptedPassword = "RSA:" + Base64.encodeToString(encrypted, Base64.DEFAULT);
    }

    if (pw_hashing.equals("sha1")) {
        encryptedPassword = new String(Hex.encodeHex(DigestUtils.sha1(String.valueOf(password))));
    }

    else if (pw_hashing.equals("md5")) {
        encryptedPassword = new String(Hex.encodeHex(DigestUtils.md5(String.valueOf(password))));
    }

    HashMap<String, String> credentials = new HashMap<>();
    credentials.put("login", connData.getUser());
    credentials.put("passwd", encryptedPassword);
    credentials.put("display", "");

    // Server requires credentials to be wrapped in a tuple with 1 item
    // e.g. python: payload = (credentials,)
    // Pyrolite library matches java.lang.Object arrays to tuples with the array's length.
    Object[] data = { credentials };
    Object untypedAuthResponse = ask("authenticate", data);
    if (untypedAuthResponse == null) {
        return;
    }

    // Login was successful.
    HashMap authResponse = (HashMap) untypedAuthResponse;
    user_level = (int) authResponse.get("user_level");

    if (eventmask != null) {
        tell("eventmask", eventmask);
    }

    // connect to event port
    eventSocket = new Socket();
    try {
        eventSocket.connect(sockaddr);
        OutputStream eventSocketOut = eventSocket.getOutputStream();
        eventSocketIn = eventSocket.getInputStream();
        eventSocketOut.write(client_id);
    } catch (IOException e) {
        signal("failed", "Event connection failed: " + e.getMessage() + ".", e);
        return;
    }

    // Start event handler
    final Thread event_thread = new Thread(new Runnable() {
        @Override
        public void run() {
            // equals event_handler.
            event_handler();
        }
    });
    event_thread.start();

    connected = true;
    viewonly = connData.getViewonly();
    signal("connected");
}

From source file:au.com.wallaceit.reddinator.RedditData.java

private JSONObject getJSONFromPost(String url, ArrayList<NameValuePair> data, boolean addOauthHeaders)
        throws RedditApiException {
    JSONObject jObj = new JSONObject();
    String json;/* w  w  w . j a v a2s.c o  m*/
    InputStream is = null;
    // create client if null
    if (httpclient == null) {
        createHttpClient();
    }
    try {
        HttpPost httppost = new HttpPost(url);
        if (addOauthHeaders) {
            // For oauth token retrieval and refresh
            httppost.addHeader("Authorization", "Basic " + Base64
                    .encodeToString((OAUTH_CLIENTID + ":").getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
        } else if (isLoggedIn()) {
            if (isTokenExpired()) {
                refreshToken();
            }
            String tokenStr = getTokenValue("token_type") + " " + getTokenValue("access_token");
            //System.out.println("Logged In, setting token header: " + tokenStr);
            httppost.addHeader("Authorization", tokenStr);
        }
        if (data != null)
            httppost.setEntity(new UrlEncodedFormEntity(data));

        HttpResponse httpResponse = httpclient.execute(httppost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Pattern p = Pattern.compile("<h2>(\\S+)</h2>");
            Matcher m = p.matcher(getStringFromStream(is));
            String details = "";
            if (m.find()) {
                details = m.group(1);
            }
            throw new RedditApiException(
                    String.valueOf(httpResponse.getStatusLine().getStatusCode()) + ": " + details);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    json = getStringFromStream(is);
    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        System.out.println("Error parsing data " + e.toString());
    }
    // return json response
    return jObj;
}

From source file:io.winch.phonegap.plugin.WinchPlugin.java

private void getBase64(CallbackContext callbackContext, JSONArray args) {
    try {/*from  w  w  w .j a  va  2  s.  c  o m*/
        String namespace = args.getString(0);
        String key = args.getString(1);
        byte[] value = mWinch.getNamespace(namespace).get(key);
        String base64 = Base64.encodeToString(value, Base64.NO_WRAP);

        PluginResult pr = new PluginResult(PluginResult.Status.OK, base64);
        callbackContext.sendPluginResult(pr);
    } catch (WinchError e) {
        e.printStackTrace();
        PluginResult r = buildErrorResult(e.getErrorCode(), e.getMessage());
        callbackContext.sendPluginResult(r);
    } catch (JSONException e1) {
        e1.printStackTrace();
    }
}

From source file:com.mobiperf_library.measurements.HttpTask.java

/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi
 *  is not turned off *///from w  w w  .  j ava  2 s  .  c om
@Override
public MeasurementResult[] call() throws MeasurementError {

    int statusCode = HttpTask.DEFAULT_STATUS_CODE;
    long duration = 0;
    long originalHeadersLen = 0;
    long originalBodyLen;
    String headers = null;
    ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD);
    //    boolean success = false;
    TaskProgress taskProgress = TaskProgress.FAILED;
    String errorMsg = "";
    InputStream inputStream = null;

    try {
        // set the download URL, a URL that points to a file on the Internet
        // this is the file to be downloaded
        HttpDesc task = (HttpDesc) this.measurementDesc;
        String urlStr = task.url;

        // TODO(Wenjie): Need to set timeout for the HTTP methods
        httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent());
        HttpRequestBase request = null;
        if (task.method.compareToIgnoreCase("head") == 0) {
            request = new HttpHead(urlStr);
        } else if (task.method.compareToIgnoreCase("get") == 0) {
            request = new HttpGet(urlStr);
        } else if (task.method.compareToIgnoreCase("post") == 0) {
            request = new HttpPost(urlStr);
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(new StringEntity(task.body));
        } else {
            // Use GET by default
            request = new HttpGet(urlStr);
        }

        if (task.headers != null && task.headers.trim().length() > 0) {
            for (String headerLine : task.headers.split("\r\n")) {
                String tokens[] = headerLine.split(":");
                if (tokens.length == 2) {
                    request.addHeader(tokens[0], tokens[1]);
                } else {
                    throw new MeasurementError("Incorrect header line: " + headerLine);
                }
            }
        }

        byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE];
        int readLen;
        int totalBodyLen = 0;

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(request);

        /* TODO(Wenjie): HttpClient does not automatically handle the following codes
         * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
         * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
         * 303 See Other. HttpStatus.SC_SEE_OTHER
         * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT
         * 
         * We may want to fetch instead from the redirected page. 
         */
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null) {
            statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                taskProgress = TaskProgress.COMPLETED;
            } else {
                taskProgress = TaskProgress.FAILED;
            }
        }

        /* For HttpClient to work properly, we still want to consume the entire
         * response even if the status code is not 200 
         */
        HttpEntity responseEntity = response.getEntity();
        originalBodyLen = responseEntity.getContentLength();
        long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE;
        // getContentLength() returns negative number if body length is unknown
        if (originalBodyLen > 0) {
            expectedResponseLen = originalBodyLen;
        }

        if (responseEntity != null) {
            inputStream = responseEntity.getContent();
            while ((readLen = inputStream.read(readBuffer)) > 0
                    && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) {
                totalBodyLen += readLen;
                // Fill in the body to report up to MAX_BODY_SIZE
                if (body.remaining() > 0) {
                    int putLen = body.remaining() < readLen ? body.remaining() : readLen;
                    body.put(readBuffer, 0, putLen);
                }
            }
            duration = System.currentTimeMillis() - startTime;//TODO check this
        }

        Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            headers = "";
            for (Header hdr : responseHeaders) {
                /*
                 * TODO(Wenjie): There can be preceding and trailing white spaces in
                 * each header field. I cannot find internal methods that return the
                 * number of bytes in a header. The solution here assumes the encoding
                 * is one byte per character.
                 */
                originalHeadersLen += hdr.toString().length();
                headers += hdr.toString() + "\r\n";
            }
        }

        PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

        MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
                phoneUtils.getDeviceProperty(), HttpTask.TYPE, System.currentTimeMillis() * 1000, taskProgress,
                this.measurementDesc);

        result.addResult("code", statusCode);

        if (taskProgress == TaskProgress.COMPLETED) {
            result.addResult("time_ms", duration);
            result.addResult("headers_len", originalHeadersLen);
            result.addResult("body_len", totalBodyLen);
            result.addResult("headers", headers);
            result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT));
        }

        Logger.i(MeasurementJsonConvertor.toJsonString(result));
        MeasurementResult[] mrArray = new MeasurementResult[1];
        mrArray[0] = result;
        return mrArray;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Logger.e("Fails to close the input stream from the HTTP response");
            }
        }
        if (httpClient != null) {
            httpClient.close();
        }

    }
    throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg);
}

From source file:com.mobilyzer.measurements.HttpTask.java

/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi
 *  is not turned off *///from   w ww  . j av  a  2  s .  c  o  m
@Override
public MeasurementResult[] call() throws MeasurementError {

    int statusCode = HttpTask.DEFAULT_STATUS_CODE;
    long duration = 0;
    long originalHeadersLen = 0;
    long originalBodyLen;
    String headers = null;
    ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD);
    //    boolean success = false;
    TaskProgress taskProgress = TaskProgress.FAILED;
    String errorMsg = "";
    InputStream inputStream = null;

    long currentRxTx = Util.getCurrentRxTxBytes();

    try {
        // set the download URL, a URL that points to a file on the Internet
        // this is the file to be downloaded
        HttpDesc task = (HttpDesc) this.measurementDesc;
        String urlStr = task.url;

        // TODO(Wenjie): Need to set timeout for the HTTP methods
        httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent());
        HttpRequestBase request = null;
        if (task.method.compareToIgnoreCase("head") == 0) {
            request = new HttpHead(urlStr);
        } else if (task.method.compareToIgnoreCase("get") == 0) {
            request = new HttpGet(urlStr);
        } else if (task.method.compareToIgnoreCase("post") == 0) {
            request = new HttpPost(urlStr);
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(new StringEntity(task.body));
        } else {
            // Use GET by default
            request = new HttpGet(urlStr);
        }

        if (task.headers != null && task.headers.trim().length() > 0) {
            for (String headerLine : task.headers.split("\r\n")) {
                String tokens[] = headerLine.split(":");
                if (tokens.length == 2) {
                    request.addHeader(tokens[0], tokens[1]);
                } else {
                    throw new MeasurementError("Incorrect header line: " + headerLine);
                }
            }
        }

        byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE];
        int readLen;
        int totalBodyLen = 0;

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(request);

        /* TODO(Wenjie): HttpClient does not automatically handle the following codes
         * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
         * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
         * 303 See Other. HttpStatus.SC_SEE_OTHER
         * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT
         * 
         * We may want to fetch instead from the redirected page. 
         */
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null) {
            statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                taskProgress = TaskProgress.COMPLETED;
            } else {
                taskProgress = TaskProgress.FAILED;
            }
        }

        /* For HttpClient to work properly, we still want to consume the entire
         * response even if the status code is not 200 
         */
        HttpEntity responseEntity = response.getEntity();
        originalBodyLen = responseEntity.getContentLength();
        long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE;
        // getContentLength() returns negative number if body length is unknown
        if (originalBodyLen > 0) {
            expectedResponseLen = originalBodyLen;
        }

        if (responseEntity != null) {
            inputStream = responseEntity.getContent();
            while ((readLen = inputStream.read(readBuffer)) > 0
                    && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) {
                totalBodyLen += readLen;
                // Fill in the body to report up to MAX_BODY_SIZE
                if (body.remaining() > 0) {
                    int putLen = body.remaining() < readLen ? body.remaining() : readLen;
                    body.put(readBuffer, 0, putLen);
                }
            }
            duration = System.currentTimeMillis() - startTime;//TODO check this
        }

        Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            headers = "";
            for (Header hdr : responseHeaders) {
                /*
                 * TODO(Wenjie): There can be preceding and trailing white spaces in
                 * each header field. I cannot find internal methods that return the
                 * number of bytes in a header. The solution here assumes the encoding
                 * is one byte per character.
                 */
                originalHeadersLen += hdr.toString().length();
                headers += hdr.toString() + "\r\n";
            }
        }

        PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

        MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
                phoneUtils.getDeviceProperty(this.getKey()), HttpTask.TYPE, System.currentTimeMillis() * 1000,
                taskProgress, this.measurementDesc);

        result.addResult("code", statusCode);

        dataConsumed += (Util.getCurrentRxTxBytes() - currentRxTx);

        if (taskProgress == TaskProgress.COMPLETED) {
            result.addResult("time_ms", duration);
            result.addResult("headers_len", originalHeadersLen);
            result.addResult("body_len", totalBodyLen);
            result.addResult("headers", headers);
            result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT));
        }

        Logger.i(MeasurementJsonConvertor.toJsonString(result));
        MeasurementResult[] mrArray = new MeasurementResult[1];
        mrArray[0] = result;
        return mrArray;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Logger.e("Fails to close the input stream from the HTTP response");
            }
        }
        if (httpClient != null) {
            httpClient.close();
        }

    }
    throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg);
}

From source file:com.mobilyzer.measurements.HttpTask_original.java

/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi
 *  is not turned off *///from w  ww  .j a va  2  s  .  c  om
@Override
public MeasurementResult[] call() throws MeasurementError {

    int statusCode = HttpTask.DEFAULT_STATUS_CODE;
    long duration = 0;
    long originalHeadersLen = 0;
    long originalBodyLen;
    String headers = null;
    ByteBuffer body = ByteBuffer.allocate(HttpTask_original.MAX_BODY_SIZE_TO_UPLOAD);
    //    boolean success = false;
    TaskProgress taskProgress = TaskProgress.FAILED;
    String errorMsg = "";
    InputStream inputStream = null;

    long currentRxTx = Util.getCurrentRxTxBytes();

    try {
        // set the download URL, a URL that points to a file on the Internet
        // this is the file to be downloaded
        HttpDesc task = (HttpDesc) this.measurementDesc;
        String urlStr = task.url;

        // TODO(Wenjie): Need to set timeout for the HTTP methods
        httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent());
        HttpRequestBase request = null;
        if (task.method.compareToIgnoreCase("head") == 0) {
            request = new HttpHead(urlStr);
        } else if (task.method.compareToIgnoreCase("get") == 0) {
            request = new HttpGet(urlStr);
        } else if (task.method.compareToIgnoreCase("post") == 0) {
            request = new HttpPost(urlStr);
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(new StringEntity(task.body));
        } else {
            // Use GET by default
            request = new HttpGet(urlStr);
        }

        if (task.headers != null && task.headers.trim().length() > 0) {
            for (String headerLine : task.headers.split("\r\n")) {
                String tokens[] = headerLine.split(":");
                if (tokens.length == 2) {
                    request.addHeader(tokens[0], tokens[1]);
                } else {
                    throw new MeasurementError("Incorrect header line: " + headerLine);
                }
            }
        }

        byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE];
        int readLen;
        int totalBodyLen = 0;

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(request);

        /* TODO(Wenjie): HttpClient does not automatically handle the following codes
         * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
         * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
         * 303 See Other. HttpStatus.SC_SEE_OTHER
         * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT
         * 
         * We may want to fetch instead from the redirected page. 
         */
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null) {
            statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                taskProgress = TaskProgress.COMPLETED;
            } else {
                taskProgress = TaskProgress.FAILED;
            }
        }

        /* For HttpClient to work properly, we still want to consume the entire
         * response even if the status code is not 200 
         */
        HttpEntity responseEntity = response.getEntity();
        originalBodyLen = responseEntity.getContentLength();
        long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE;
        // getContentLength() returns negative number if body length is unknown
        if (originalBodyLen > 0) {
            expectedResponseLen = originalBodyLen;
        }

        if (responseEntity != null) {
            inputStream = responseEntity.getContent();
            while ((readLen = inputStream.read(readBuffer)) > 0
                    && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) {
                totalBodyLen += readLen;
                // Fill in the body to report up to MAX_BODY_SIZE
                if (body.remaining() > 0) {
                    int putLen = body.remaining() < readLen ? body.remaining() : readLen;
                    body.put(readBuffer, 0, putLen);
                }
            }
            duration = System.currentTimeMillis() - startTime;//TODO check this
        }

        Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            headers = "";
            for (Header hdr : responseHeaders) {
                /*
                 * TODO(Wenjie): There can be preceding and trailing white spaces in
                 * each header field. I cannot find internal methods that return the
                 * number of bytes in a header. The solution here assumes the encoding
                 * is one byte per character.
                 */
                originalHeadersLen += hdr.toString().length();
                headers += hdr.toString() + "\r\n";
            }
        }

        PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

        MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
                phoneUtils.getDeviceProperty(this.getKey()), HttpTask.TYPE, System.currentTimeMillis() * 1000,
                taskProgress, this.measurementDesc);

        result.addResult("code", statusCode);

        dataConsumed += (Util.getCurrentRxTxBytes() - currentRxTx);

        if (taskProgress == TaskProgress.COMPLETED) {
            result.addResult("time_ms", duration);
            result.addResult("headers_len", originalHeadersLen);
            result.addResult("body_len", totalBodyLen);
            result.addResult("headers", headers);
            result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT));
        }

        Logger.i(MeasurementJsonConvertor.toJsonString(result));
        MeasurementResult[] mrArray = new MeasurementResult[1];
        mrArray[0] = result;
        return mrArray;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Logger.e("Fails to close the input stream from the HTTP response");
            }
        }
        if (httpClient != null) {
            httpClient.close();
        }

    }
    throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg);
}

From source file:org.jboss.aerogear.android.unifiedpush.gcm.AeroGearGCMPushRegistrar.java

private String getHashedAuth(String username, char[] password) {
    StringBuilder headerValueBuilder = new StringBuilder(AUTHORIZATION_METHOD).append(" ");
    String unhashedCredentials = new StringBuilder(username).append(":").append(password).toString();
    String hashedCrentials = Base64.encodeToString(unhashedCredentials.getBytes(),
            Base64.DEFAULT | Base64.NO_WRAP);
    return headerValueBuilder.append(hashedCrentials).toString();
}

From source file:at.jclehner.rxdroid.Backup.java

private static String passwordToKey(String password) {
    if (password.length() == 0)
        return null;

    try {/*from   w w w .j  a v  a2s.  c  o  m*/
        final MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update("RxDroid".getBytes());
        return Base64.encodeToString(md.digest(password.getBytes("UTF-8")), Base64.NO_WRAP);
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        throw new WrappedCheckedException(e);
    }
}