Example usage for java.net URI getPort

List of usage examples for java.net URI getPort

Introduction

In this page you can find the example usage for java.net URI getPort.

Prototype

public int getPort() 

Source Link

Document

Returns the port number of this URI.

Usage

From source file:com.resenworkspace.data.Download.HttpUtils.java

/**
 * A helper method to send or retrieve data through HTTP protocol.
 *
 * @param token The token to identify the sending progress.
 * @param url The URL used in a GET request. Null when the method is
 *         HTTP_POST_METHOD./*w  ww .j a  va  2  s .  c  o m*/
 * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD.
 * @param method HTTP_POST_METHOD or HTTP_GET_METHOD.
 * @return A byte array which contains the response data.
 *         If an HTTP error code is returned, an IOException will be thrown.
 * @throws IOException if any error occurred on network interface or
 *         an HTTP error code(>=400) returned from the server.
 */
protected static byte[] httpConnection(Context context, long token, String url, byte[] pdu, int method,
        boolean isProxySet, String proxyHost, int proxyPort) throws IOException {
    if (url == null) {
        throw new IllegalArgumentException("URL must not be null.");
    }
    {
        Log.i(TAG, "httpConnection: params list");
        Log.i(TAG, "\ttoken\t\t= " + token);
        Log.i(TAG, "\turl\t\t= " + url);
        Log.i(TAG, "\tmethod\t\t= "
                + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN")));
        Log.i(TAG, "\tisProxySet\t= " + isProxySet);
        Log.i(TAG, "\tproxyHost\t= " + proxyHost);
        Log.i(TAG, "\tproxyPort\t= " + proxyPort);
        // TODO Print out binary data more readable.
        //Log.v(TAG, "\tpdu\t\t= " + Arrays.toString(pdu));
    }

    AndroidHttpClient client = null;
    try {
        // Make sure to use a proxy which supports CONNECT.
        URI hostUrl = new URI(url);
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        client = createHttpClient(context);
        HttpRequest req = null;
        switch (method) {
        case HTTP_POST_METHOD:
            ProgressCallbackEntity entity = new ProgressCallbackEntity(context, token, pdu);
            // Set request content type.
            entity.setContentType("application/vnd.wap.mms-message");
            HttpPost post = new HttpPost(url);
            post.setEntity(entity);
            req = post;
            break;
        case HTTP_GET_METHOD:
            req = new HttpGet(url);
            break;
        default:
            Log.e(TAG, "Unknown HTTP method: " + method + ". Must be one of POST[" + HTTP_POST_METHOD
                    + "] or GET[" + HTTP_GET_METHOD + "].");
            return null;
        }

        // Set route parameters for the request.
        HttpParams params = client.getParams();
        if (isProxySet) {
            ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort));
        }
        req.setParams(params);
        // Set necessary HTTP headers for  transmission.
        //            req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);
        //            {
        //                String xWapProfileTagName = MmsConfig.getUaProfTagName();
        //                String xWapProfileUrl = MmsConfig.getUaProfUrl();
        //
        //                if (xWapProfileUrl != null) {
        //                    if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
        //                        Log.d(LogTag.TRANSACTION,
        //                                "[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl);
        //                    }
        //                    req.addHeader(xWapProfileTagName, xWapProfileUrl);
        //                }
        //            }

        // Extra http parameters. Split by '|' to get a list of value pairs.
        // Separate each pair by the first occurrence of ':' to obtain a name and
        // value. Replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside
        // the value.
        //            String extraHttpParams = MmsConfig.getHttpParams();

        //            if (extraHttpParams != null) {
        //                String line1Number = ((TelephonyManager)context
        //                        .getSystemService(Context.TELEPHONY_SERVICE))
        //                        .getLine1Number();
        //                String line1Key = MmsConfig.getHttpParamsLine1Key();
        //                String paramList[] = extraHttpParams.split("\\|");
        //
        //                for (String paramPair : paramList) {
        //                    String splitPair[] = paramPair.split(":", 2);
        //
        //                    if (splitPair.length == 2) {
        //                        String name = splitPair[0].trim();
        //                        String value = splitPair[1].trim();
        //
        //                        if (line1Key != null) {
        //                            value = value.replace(line1Key, line1Number);
        //                        }
        //                        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
        //                            req.addHeader(name, value);
        //                        }
        //                    }
        //                }
        //            }
        req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE);

        HttpResponse response = client.execute(target, req);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) { // HTTP 200 is success.
            throw new IOException("HTTP error: " + status.getReasonPhrase());
        }

        HttpEntity entity = response.getEntity();
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Error closing input stream: " + e.getMessage());
                        }
                    }
                }
                if (entity.isChunked()) {
                    Log.i(TAG, "httpConnection: transfer encoding is chunked");
                    //int bytesTobeRead = MmsConfig.getMaxMessageSize();
                    int bytesTobeRead = 500 * 1024;
                    byte[] tempBody = new byte[bytesTobeRead];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        int bytesRead = 0;
                        int offset = 0;
                        boolean readError = false;
                        do {
                            try {
                                bytesRead = dis.read(tempBody, offset, bytesTobeRead);
                            } catch (IOException e) {
                                readError = true;
                                Log.e(TAG, "httpConnection: error reading input stream" + e.getMessage());
                                break;
                            }
                            if (bytesRead > 0) {
                                bytesTobeRead -= bytesRead;
                                offset += bytesRead;
                            }
                        } while (bytesRead >= 0 && bytesTobeRead > 0);
                        if (bytesRead == -1 && offset > 0 && !readError) {
                            // offset is same as total number of bytes read
                            // bytesRead will be -1 if the data was read till the eof
                            body = new byte[offset];
                            System.arraycopy(tempBody, 0, body, 0, offset);
                            Log.i(TAG, "httpConnection: Chunked response length [" + Integer.toString(offset)
                                    + "]");
                        } else {
                            Log.e(TAG, "httpConnection: Response entity too large or empty");
                        }
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Error closing input stream: " + e.getMessage());
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        return body;
    } catch (URISyntaxException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalStateException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalArgumentException e) {
        handleHttpConnectionException(e, url);
    } catch (SocketException e) {
        handleHttpConnectionException(e, url);
    } catch (Exception e) {
        handleHttpConnectionException(e, url);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

From source file:com.vuze.android.remote.rpc.RestJsonClient.java

public static Map<?, ?> connect(String id, String url, Map<?, ?> jsonPost, Header[] headers,
        UsernamePasswordCredentials creds, boolean sendGzip) throws RPCException {
    long readTime = 0;
    long connSetupTime = 0;
    long connTime = 0;
    int bytesRead = 0;
    if (DEBUG_DETAILED) {
        Log.d(TAG, id + "] Execute " + url);
    }/*w  w w .j ava 2 s.c  om*/
    long now = System.currentTimeMillis();
    long then;

    Map<?, ?> json = Collections.EMPTY_MAP;

    try {

        URI uri = new URI(url);
        int port = uri.getPort();

        BasicHttpParams basicHttpParams = new BasicHttpParams();
        HttpProtocolParams.setUserAgent(basicHttpParams, "Vuze Android Remote");

        DefaultHttpClient httpclient;
        if ("https".equals(uri.getScheme())) {
            httpclient = MySSLSocketFactory.getNewHttpClient(port);
        } else {
            httpclient = new DefaultHttpClient(basicHttpParams);
        }

        //AndroidHttpClient.newInstance("Vuze Android Remote");

        // This doesn't set the "Authorization" header!?
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), creds);

        // Prepare a request object
        HttpRequestBase httpRequest = jsonPost == null ? new HttpGet(uri) : new HttpPost(uri); // IllegalArgumentException

        if (creds != null) {
            byte[] toEncode = (creds.getUserName() + ":" + creds.getPassword()).getBytes();
            String encoding = Base64Encode.encodeToString(toEncode, 0, toEncode.length);
            httpRequest.setHeader("Authorization", "Basic " + encoding);
        }

        if (jsonPost != null) {
            HttpPost post = (HttpPost) httpRequest;
            String postString = JSONUtils.encodeToJSON(jsonPost);
            if (AndroidUtils.DEBUG_RPC) {
                Log.d(TAG, id + "]  Post: " + postString);
            }

            AbstractHttpEntity entity = (sendGzip && Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
                    ? getCompressedEntity(postString)
                    : new StringEntity(postString);
            post.setEntity(entity);

            post.setHeader("Accept", "application/json");
            post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
            setupRequestFroyo(httpRequest);
        }

        if (headers != null) {
            for (Header header : headers) {
                httpRequest.setHeader(header);
            }
        }

        // Execute the request
        HttpResponse response;

        then = System.currentTimeMillis();
        if (AndroidUtils.DEBUG_RPC) {
            connSetupTime = (then - now);
            now = then;
        }

        httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
                if (i < 2) {
                    return true;
                }
                return false;
            }
        });
        response = httpclient.execute(httpRequest);

        then = System.currentTimeMillis();
        if (AndroidUtils.DEBUG_RPC) {
            connTime = (then - now);
            now = then;
        }

        HttpEntity entity = response.getEntity();

        // XXX STATUSCODE!

        StatusLine statusLine = response.getStatusLine();
        if (AndroidUtils.DEBUG_RPC) {
            Log.d(TAG, "StatusCode: " + statusLine.getStatusCode());
        }

        if (entity != null) {

            long contentLength = entity.getContentLength();
            if (contentLength >= Integer.MAX_VALUE - 2) {
                throw new RPCException("JSON response too large");
            }

            // A Simple JSON Response Read
            InputStream instream = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
                    ? getUngzippedContent(entity)
                    : entity.getContent();
            InputStreamReader isr = new InputStreamReader(instream, "utf8");

            StringBuilder sb = null;
            BufferedReader br = null;
            // JSONReader is 10x slower, plus I get more OOM errors.. :(
            //            final boolean useStringBuffer = contentLength > (4 * 1024 * 1024) ? false
            //                  : DEFAULT_USE_STRINGBUFFER;
            final boolean useStringBuffer = DEFAULT_USE_STRINGBUFFER;

            if (useStringBuffer) {
                // Setting capacity saves StringBuffer from going through many
                // enlargeBuffers, and hopefully allows toString to not make a copy
                sb = new StringBuilder(contentLength > 512 ? (int) contentLength + 2 : 512);
            } else {
                if (AndroidUtils.DEBUG_RPC) {
                    Log.d(TAG, "Using BR. ContentLength = " + contentLength);
                }
                br = new BufferedReader(isr, 8192);
                br.mark(32767);
            }

            try {

                // 9775 files on Nexus 7 (~2,258,731 bytes)
                // fastjson 1.1.46 (String)       :  527- 624ms
                // fastjson 1.1.39 (String)       :  924-1054ms
                // fastjson 1.1.39 (StringBuilder): 1227-1463ms
                // fastjson 1.1.39 (BR)           : 2233-2260ms
                // fastjson 1.1.39 (isr)          :      2312ms
                // GSON 2.2.4 (String)            : 1539-1760ms
                // GSON 2.2.4 (BufferedReader)    : 2646-3060ms
                // JSON-SMART 1.3.1 (String)      :  572- 744ms (OOMs more often than fastjson)

                if (useStringBuffer) {
                    char c[] = new char[8192];
                    while (true) {
                        int read = isr.read(c);
                        if (read < 0) {
                            break;
                        }
                        sb.append(c, 0, read);
                    }

                    if (AndroidUtils.DEBUG_RPC) {
                        then = System.currentTimeMillis();
                        if (DEBUG_DETAILED) {
                            if (sb.length() > 2000) {
                                Log.d(TAG, id + "] " + sb.substring(0, 2000) + "...");
                            } else {
                                Log.d(TAG, id + "] " + sb.toString());
                            }
                        }
                        bytesRead = sb.length();
                        readTime = (then - now);
                        now = then;
                    }

                    json = JSONUtils.decodeJSON(sb.toString());
                    //json = JSONUtilsGSON.decodeJSON(sb.toString());
                } else {

                    //json = JSONUtils.decodeJSON(isr);
                    json = JSONUtils.decodeJSON(br);
                    //json = JSONUtilsGSON.decodeJSON(br);
                }

            } catch (Exception pe) {

                //               StatusLine statusLine = response.getStatusLine();
                if (statusLine != null && statusLine.getStatusCode() == 409) {
                    throw new RPCException(response, "409");
                }

                try {
                    String line;
                    if (useStringBuffer) {
                        line = sb.subSequence(0, Math.min(128, sb.length())).toString();
                    } else {
                        br.reset();
                        line = br.readLine().trim();
                    }

                    isr.close();

                    if (AndroidUtils.DEBUG_RPC) {
                        Log.d(TAG, id + "]line: " + line);
                    }
                    Header contentType = entity.getContentType();
                    if (line.startsWith("<") || line.contains("<html")
                            || (contentType != null && contentType.getValue().startsWith("text/html"))) {
                        // TODO: use android strings.xml
                        throw new RPCException(response,
                                "Could not retrieve remote client location information.  The most common cause is being on a guest wifi that requires login before using the internet.");
                    }
                } catch (IOException ignore) {

                }

                Log.e(TAG, id, pe);
                if (statusLine != null) {
                    String msg = statusLine.getStatusCode() + ": " + statusLine.getReasonPhrase() + "\n"
                            + pe.getMessage();
                    throw new RPCException(msg, pe);
                }
                throw new RPCException(pe);
            } finally {
                closeOnNewThread(useStringBuffer ? isr : br);
            }

            if (AndroidUtils.DEBUG_RPC) {
                //               Log.d(TAG, id + "]JSON Result: " + json);
            }

        }
    } catch (RPCException e) {
        throw e;
    } catch (Throwable e) {
        Log.e(TAG, id, e);
        throw new RPCException(e);
    }

    if (AndroidUtils.DEBUG_RPC) {
        then = System.currentTimeMillis();
        Log.d(TAG, id + "] conn " + connSetupTime + "/" + connTime + "ms. Read " + bytesRead + " in " + readTime
                + "ms, parsed in " + (then - now) + "ms");
    }
    return json;
}

From source file:ru.ivanovpv.gorets.psm.mms.transaction.HttpUtils.java

/**
 * A helper method to send or retrieve data through HTTP protocol.
 *
 * @param token The token to identify the sending progress.
 * @param url The URL used in a GET request. Null when the method is
 *         HTTP_POST_METHOD.// ww w  .  ja v  a2  s. co m
 * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD.
 * @param method HTTP_POST_METHOD or HTTP_GET_METHOD.
 * @return A byte array which contains the response data.
 *         If an HTTP error code is returned, an IOException will be thrown.
 * @throws IOException if any error occurred on network interface or
 *         an HTTP error code(&gt;=400) returned from the server.
 */
public static byte[] httpConnection(Context context, long token, String url, byte[] pdu, int method,
        boolean isProxySet, String proxyHost, int proxyPort) throws IOException {
    if (url == null) {
        throw new IllegalArgumentException("URL must not be null.");
    }

    if (DEBUG) {
        Log.v(TAG, "httpConnection: params list");
        Log.v(TAG, "\ttoken\t\t= " + token);
        Log.v(TAG, "\turl\t\t= " + url);
        Log.v(TAG, "\tmethod\t\t= "
                + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN")));
        Log.v(TAG, "\tisProxySet\t= " + isProxySet);
        Log.v(TAG, "\tproxyHost\t= " + proxyHost);
        Log.v(TAG, "\tproxyPort\t= " + proxyPort);
        // TODO Print out binary data more readable.
        //Log.v(TAG, "\tpdu\t\t= " + Arrays.toString(pdu));
    }

    AndroidHttpClient client = null;

    try {
        // Make sure to use a proxy which supports CONNECT.
        URI hostUrl = new URI(url);
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);

        client = createHttpClient(context);
        HttpRequest req = null;
        switch (method) {
        case HTTP_POST_METHOD:
            ProgressCallbackEntity entity = new ProgressCallbackEntity(context, token, pdu);
            // Set request content type.
            entity.setContentType("application/vnd.wap.mms-message");

            HttpPost post = new HttpPost(url);
            post.setEntity(entity);
            req = post;
            break;
        case HTTP_GET_METHOD:
            req = new HttpGet(url);
            break;
        default:
            Log.e(TAG, "Unknown HTTP method: " + method + ". Must be one of POST[" + HTTP_POST_METHOD
                    + "] or GET[" + HTTP_GET_METHOD + "].");
            return null;
        }

        // Set route parameters for the request.
        HttpParams params = client.getParams();
        if (isProxySet) {
            ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort));
        }
        req.setParams(params);

        // Set necessary HTTP headers for MMS transmission.
        req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);
        {
            String xWapProfileTagName = MmsConfig.getUaProfTagName();
            String xWapProfileUrl = MmsConfig.getUaProfUrl();

            if (xWapProfileUrl != null) {
                if (DEBUG) {
                    Log.d(TAG, "[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl);
                }
                req.addHeader(xWapProfileTagName, xWapProfileUrl);
            }
        }

        // Extra http parameters. Split by '|' to get a list of value pairs.
        // Separate each pair by the first occurrence of ':' to obtain a name and
        // value. Replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside
        // the value.
        String extraHttpParams = MmsConfig.getHttpParams();

        if (extraHttpParams != null) {
            String line1Number = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
                    .getLine1Number();
            String line1Key = MmsConfig.getHttpParamsLine1Key();
            String paramList[] = extraHttpParams.split("\\|");

            for (String paramPair : paramList) {
                String splitPair[] = paramPair.split(":", 2);

                if (splitPair.length == 2) {
                    String name = splitPair[0].trim();
                    String value = splitPair[1].trim();

                    if (line1Key != null) {
                        value = value.replace(line1Key, line1Number);
                    }
                    if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
                        req.addHeader(name, value);
                    }
                }
            }
        }
        req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE);

        HttpResponse response = client.execute(target, req);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) { // HTTP 200 is success.
            throw new IOException("HTTP error: " + status.getReasonPhrase());
        }

        HttpEntity entity = response.getEntity();
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Error closing input stream: " + e.getMessage());
                        }
                    }
                }
                if (entity.isChunked()) {
                    Log.v(TAG, "httpConnection: transfer encoding is chunked");
                    int bytesTobeRead = MmsConfig.getMaxMessageSize();
                    byte[] tempBody = new byte[bytesTobeRead];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        int bytesRead = 0;
                        int offset = 0;
                        boolean readError = false;
                        do {
                            try {
                                bytesRead = dis.read(tempBody, offset, bytesTobeRead);
                            } catch (IOException e) {
                                readError = true;
                                Log.e(TAG, "httpConnection: error reading input stream" + e.getMessage());
                                break;
                            }
                            if (bytesRead > 0) {
                                bytesTobeRead -= bytesRead;
                                offset += bytesRead;
                            }
                        } while (bytesRead >= 0 && bytesTobeRead > 0);
                        if (bytesRead == -1 && offset > 0 && !readError) {
                            // offset is same as total number of bytes read
                            // bytesRead will be -1 if the data was read till the eof
                            body = new byte[offset];
                            System.arraycopy(tempBody, 0, body, 0, offset);
                            Log.v(TAG, "httpConnection: Chunked response length [" + Integer.toString(offset)
                                    + "]");
                        } else {
                            Log.e(TAG, "httpConnection: Response entity too large or empty");
                        }
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Error closing input stream: " + e.getMessage());
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        return body;
    } catch (URISyntaxException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalStateException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalArgumentException e) {
        handleHttpConnectionException(e, url);
    } catch (SocketException e) {
        handleHttpConnectionException(e, url);
    } catch (Exception e) {
        handleHttpConnectionException(e, url);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

From source file:com.aliyun.oss.integrationtests.TestUtils.java

public static String composeLocation(OSSClient client, String endpoint, String bucketName, String key) {
    try {/*from  ww w.  j a  va 2  s  . c o  m*/
        URI baseUri = URI.create(endpoint);
        URI resultUri = null;
        if (client.getClientConfiguration().isSLDEnabled()) {
            resultUri = new URI(baseUri.getScheme(), null, baseUri.getHost(), baseUri.getPort(),
                    String.format("/%s/%s", bucketName, HttpUtil.urlEncode(key, DEFAULT_CHARSET_NAME)), null,
                    null);
        } else {
            resultUri = new URI(baseUri.getScheme(), null, bucketName + "." + baseUri.getHost(),
                    baseUri.getPort(), String.format("/%s", HttpUtil.urlEncode(key, DEFAULT_CHARSET_NAME)),
                    null, null);
        }

        return URLDecoder.decode(resultUri.toString(), DEFAULT_CHARSET_NAME);
    } catch (Exception e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}

From source file:com.geocine.mms.com.android.mms.transaction.HttpUtils.java

/**
 * A helper method to send or retrieve data through HTTP protocol.
 *
 * @param token The token to identify the sending progress.
 * @param url The URL used in a GET request. Null when the method is
 *         HTTP_POST_METHOD.//from w  w  w.j av  a 2 s  .  c o m
 * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD.
 * @param method HTTP_POST_METHOD or HTTP_GET_METHOD.
 * @return A byte array which contains the response data.
 *         If an HTTP error code is returned, an IOException will be thrown.
 * @throws IOException if any error occurred on network interface or
 *         an HTTP error code(&gt;=400) returned from the server.
 */
protected static byte[] httpConnection(Context context, long token, String url, byte[] pdu, int method,
        boolean isProxySet, String proxyHost, int proxyPort) throws IOException {
    if (url == null) {
        throw new IllegalArgumentException("URL must not be null.");
    }

    if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
        Log.v(TAG, "httpConnection: params list");
        Log.v(TAG, "\ttoken\t\t= " + token);
        Log.v(TAG, "\turl\t\t= " + url);
        Log.v(TAG, "\tmethod\t\t= "
                + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN")));
        Log.v(TAG, "\tisProxySet\t= " + isProxySet);
        Log.v(TAG, "\tproxyHost\t= " + proxyHost);
        Log.v(TAG, "\tproxyPort\t= " + proxyPort);
        // TODO Print out binary data more readable.
        //Log.v(TAG, "\tpdu\t\t= " + Arrays.toString(pdu));
    }

    AndroidHttpClient client = null;

    try {
        // Make sure to use a proxy which supports CONNECT.
        URI hostUrl = new URI(url);
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);

        client = createHttpClient(context);
        HttpRequest req = null;
        switch (method) {
        case HTTP_POST_METHOD:
            ProgressCallbackEntity entity = new ProgressCallbackEntity(context, token, pdu);
            // Set request content type.
            entity.setContentType("application/vnd.wap.mms-message");

            HttpPost post = new HttpPost(url);
            post.setEntity(entity);
            req = post;
            break;
        case HTTP_GET_METHOD:
            req = new HttpGet(url);
            break;
        default:
            Log.e(TAG, "Unknown HTTP method: " + method + ". Must be one of POST[" + HTTP_POST_METHOD
                    + "] or GET[" + HTTP_GET_METHOD + "].");
            return null;
        }

        // Set route parameters for the request.
        HttpParams params = client.getParams();
        if (isProxySet) {
            ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort));
        }
        req.setParams(params);

        // Set necessary HTTP headers for MMS transmission.
        req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);
        {
            String xWapProfileTagName = MmsConfig.getUaProfTagName();
            String xWapProfileUrl = MmsConfig.getUaProfUrl();

            if (xWapProfileUrl != null) {
                if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
                    Log.d(LogTag.TRANSACTION, "[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl);
                }
                req.addHeader(xWapProfileTagName, xWapProfileUrl);
            }
        }

        // Extra http parameters. Split by '|' to get a list of value pairs.
        // Separate each pair by the first occurrence of ':' to obtain a name and
        // value. Replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside
        // the value.
        String extraHttpParams = MmsConfig.getHttpParams();

        if (extraHttpParams != null) {
            String line1Number = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
                    .getLine1Number();
            String line1Key = MmsConfig.getHttpParamsLine1Key();
            String paramList[] = extraHttpParams.split("\\|");

            for (String paramPair : paramList) {
                String splitPair[] = paramPair.split(":", 2);

                if (splitPair.length == 2) {
                    String name = splitPair[0].trim();
                    String value = splitPair[1].trim();

                    if (line1Key != null) {
                        value = value.replace(line1Key, line1Number);
                    }
                    if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
                        req.addHeader(name, value);
                    }
                }
            }
        }
        req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE);

        HttpResponse response = client.execute(target, req);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) { // HTTP 200 is success.
            throw new IOException("HTTP error: " + status.getReasonPhrase());
        }

        HttpEntity entity = response.getEntity();
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Error closing input stream: " + e.getMessage());
                        }
                    }
                }
                if (entity.isChunked()) {
                    Log.v(TAG, "httpConnection: transfer encoding is chunked");
                    int bytesTobeRead = MmsConfig.getMaxMessageSize();
                    byte[] tempBody = new byte[bytesTobeRead];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        int bytesRead = 0;
                        int offset = 0;
                        boolean readError = false;
                        do {
                            try {
                                bytesRead = dis.read(tempBody, offset, bytesTobeRead);
                            } catch (IOException e) {
                                readError = true;
                                Log.e(TAG, "httpConnection: error reading input stream" + e.getMessage());
                                break;
                            }
                            if (bytesRead > 0) {
                                bytesTobeRead -= bytesRead;
                                offset += bytesRead;
                            }
                        } while (bytesRead >= 0 && bytesTobeRead > 0);
                        if (bytesRead == -1 && offset > 0 && !readError) {
                            // offset is same as total number of bytes read
                            // bytesRead will be -1 if the data was read till the eof
                            body = new byte[offset];
                            System.arraycopy(tempBody, 0, body, 0, offset);
                            Log.v(TAG, "httpConnection: Chunked response length [" + Integer.toString(offset)
                                    + "]");
                        } else {
                            Log.e(TAG, "httpConnection: Response entity too large or empty");
                        }
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Error closing input stream: " + e.getMessage());
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        return body;
    } catch (URISyntaxException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalStateException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalArgumentException e) {
        handleHttpConnectionException(e, url);
    } catch (SocketException e) {
        handleHttpConnectionException(e, url);
    } catch (Exception e) {
        handleHttpConnectionException(e, url);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

From source file:org.elasticsearch.client.sniff.ElasticsearchNodesSniffer.java

private static Node readNode(String nodeId, JsonParser parser, Scheme scheme) throws IOException {
    HttpHost publishedHost = null;//from ww  w . j a  v  a  2  s.co m
    /*
     * We sniff the bound hosts so we can look up the node based on any
     * address on which it is listening. This is useful in Elasticsearch's
     * test framework where we sometimes publish ipv6 addresses but the
     * tests contact the node on ipv4.
     */
    Set<HttpHost> boundHosts = new HashSet<>();
    String name = null;
    String version = null;
    /*
     * Multi-valued attributes come with key = `real_key.index` and we
     * unflip them after reading them because we can't rely on the order
     * that they arive.
     */
    final Map<String, String> protoAttributes = new HashMap<String, String>();

    boolean sawRoles = false;
    boolean master = false;
    boolean data = false;
    boolean ingest = false;

    String fieldName = null;
    while (parser.nextToken() != JsonToken.END_OBJECT) {
        if (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
            fieldName = parser.getCurrentName();
        } else if (parser.getCurrentToken() == JsonToken.START_OBJECT) {
            if ("http".equals(fieldName)) {
                while (parser.nextToken() != JsonToken.END_OBJECT) {
                    if (parser.getCurrentToken() == JsonToken.VALUE_STRING
                            && "publish_address".equals(parser.getCurrentName())) {
                        URI publishAddressAsURI = URI.create(scheme + "://" + parser.getValueAsString());
                        publishedHost = new HttpHost(publishAddressAsURI.getHost(),
                                publishAddressAsURI.getPort(), publishAddressAsURI.getScheme());
                    } else if (parser.currentToken() == JsonToken.START_ARRAY
                            && "bound_address".equals(parser.getCurrentName())) {
                        while (parser.nextToken() != JsonToken.END_ARRAY) {
                            URI boundAddressAsURI = URI.create(scheme + "://" + parser.getValueAsString());
                            boundHosts.add(new HttpHost(boundAddressAsURI.getHost(),
                                    boundAddressAsURI.getPort(), boundAddressAsURI.getScheme()));
                        }
                    } else if (parser.getCurrentToken() == JsonToken.START_OBJECT) {
                        parser.skipChildren();
                    }
                }
            } else if ("attributes".equals(fieldName)) {
                while (parser.nextToken() != JsonToken.END_OBJECT) {
                    if (parser.getCurrentToken() == JsonToken.VALUE_STRING) {
                        String oldValue = protoAttributes.put(parser.getCurrentName(),
                                parser.getValueAsString());
                        if (oldValue != null) {
                            throw new IOException("repeated attribute key [" + parser.getCurrentName() + "]");
                        }
                    } else {
                        parser.skipChildren();
                    }
                }
            } else {
                parser.skipChildren();
            }
        } else if (parser.currentToken() == JsonToken.START_ARRAY) {
            if ("roles".equals(fieldName)) {
                sawRoles = true;
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    switch (parser.getText()) {
                    case "master":
                        master = true;
                        break;
                    case "data":
                        data = true;
                        break;
                    case "ingest":
                        ingest = true;
                        break;
                    default:
                        logger.warn("unknown role [" + parser.getText() + "] on node [" + nodeId + "]");
                    }
                }
            } else {
                parser.skipChildren();
            }
        } else if (parser.currentToken().isScalarValue()) {
            if ("version".equals(fieldName)) {
                version = parser.getText();
            } else if ("name".equals(fieldName)) {
                name = parser.getText();
            }
        }
    }
    //http section is not present if http is not enabled on the node, ignore such nodes
    if (publishedHost == null) {
        logger.debug("skipping node [" + nodeId + "] with http disabled");
        return null;
    }

    Map<String, List<String>> realAttributes = new HashMap<>(protoAttributes.size());
    List<String> keys = new ArrayList<>(protoAttributes.keySet());
    for (String key : keys) {
        if (key.endsWith(".0")) {
            String realKey = key.substring(0, key.length() - 2);
            List<String> values = new ArrayList<>();
            int i = 0;
            while (true) {
                String value = protoAttributes.remove(realKey + "." + i);
                if (value == null) {
                    break;
                }
                values.add(value);
                i++;
            }
            realAttributes.put(realKey, unmodifiableList(values));
        }
    }
    for (Map.Entry<String, String> entry : protoAttributes.entrySet()) {
        realAttributes.put(entry.getKey(), singletonList(entry.getValue()));
    }

    if (version.startsWith("2.")) {
        /*
         * 2.x doesn't send roles, instead we try to read them from
         * attributes.
         */
        boolean clientAttribute = v2RoleAttributeValue(realAttributes, "client", false);
        Boolean masterAttribute = v2RoleAttributeValue(realAttributes, "master", null);
        Boolean dataAttribute = v2RoleAttributeValue(realAttributes, "data", null);
        master = masterAttribute == null ? false == clientAttribute : masterAttribute;
        data = dataAttribute == null ? false == clientAttribute : dataAttribute;
    } else {
        assert sawRoles : "didn't see roles for [" + nodeId + "]";
    }
    assert boundHosts.contains(publishedHost) : "[" + nodeId
            + "] doesn't make sense! publishedHost should be in boundHosts";
    logger.trace("adding node [" + nodeId + "]");
    return new Node(publishedHost, boundHosts, name, version, new Roles(master, data, ingest),
            unmodifiableMap(realAttributes));
}

From source file:com.android.mms.service.HttpUtils.java

/**
 * A helper method to send or retrieve data through HTTP protocol.
 *
 * @param url The URL used in a GET request. Null when the method is
 *         HTTP_POST_METHOD./* www  .j  av  a 2 s . c  om*/
 * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD.
 * @param method HTTP_POST_METHOD or HTTP_GET_METHOD.
 * @param isProxySet If proxy is set
 * @param proxyHost The host of the proxy
 * @param proxyPort The port of the proxy
 * @param resolver The custom name resolver to use
 * @param useIpv6 If we should use IPv6 address when the HTTP client resolves the host name
 * @param mmsConfig The MmsConfig to use
 * @return A byte array which contains the response data.
 *         If an HTTP error code is returned, an IOException will be thrown.
 * @throws com.android.mms.service.exception.MmsHttpException if HTTP request gets error response (&gt;=400)
 */
public static byte[] httpConnection(Context context, String url, byte[] pdu, int method, boolean isProxySet,
        String proxyHost, int proxyPort, NameResolver resolver, boolean useIpv6, MmsConfig.Overridden mmsConfig)
        throws MmsHttpException {
    final String methodString = getMethodString(method);
    Log.v(TAG,
            "HttpUtils: request param list\n" + "url=" + url + "\n" + "method=" + methodString + "\n"
                    + "isProxySet=" + isProxySet + "\n" + "proxyHost=" + proxyHost + "\n" + "proxyPort="
                    + proxyPort + "\n" + "size=" + (pdu != null ? pdu.length : 0));

    NetworkAwareHttpClient client = null;
    try {
        // Make sure to use a proxy which supports CONNECT.
        URI hostUrl = new URI(url);
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        client = createHttpClient(context, resolver, useIpv6, mmsConfig);
        HttpRequest req = null;

        switch (method) {
        case HTTP_POST_METHOD:
            ByteArrayEntity entity = new ByteArrayEntity(pdu);
            // Set request content type.
            entity.setContentType("application/vnd.wap.mms-message");
            HttpPost post = new HttpPost(url);
            post.setEntity(entity);
            req = post;
            break;
        case HTTP_GET_METHOD:
            req = new HttpGet(url);
            break;
        }

        // Set route parameters for the request.
        HttpParams params = client.getParams();
        if (isProxySet) {
            ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort));
        }
        req.setParams(params);

        // Set necessary HTTP headers for MMS transmission.
        req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);

        // UA Profile URL header
        String xWapProfileTagName = mmsConfig.getUaProfTagName();
        String xWapProfileUrl = mmsConfig.getUaProfUrl();
        if (xWapProfileUrl != null) {
            Log.v(TAG, "HttpUtils: xWapProfUrl=" + xWapProfileUrl);
            req.addHeader(xWapProfileTagName, xWapProfileUrl);
        }

        // Extra http parameters. Split by '|' to get a list of value pairs.
        // Separate each pair by the first occurrence of ':' to obtain a name and
        // value. Replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside
        // the value. And replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsNaiKey() with the users NAI(Network Access Identifier)
        // inside the value.
        String extraHttpParams = mmsConfig.getHttpParams();

        if (!TextUtils.isEmpty(extraHttpParams)) {
            // Parse the parameter list
            String paramList[] = extraHttpParams.split("\\|");
            for (String paramPair : paramList) {
                String splitPair[] = paramPair.split(":", 2);
                if (splitPair.length == 2) {
                    final String name = splitPair[0].trim();
                    final String value = resolveMacro(context, splitPair[1].trim(), mmsConfig);
                    if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
                        req.addHeader(name, value);
                    }
                }
            }
        }
        req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, getCurrentAcceptLanguage(Locale.getDefault()));

        final HttpResponse response = client.execute(target, req);
        final StatusLine status = response.getStatusLine();
        final HttpEntity entity = response.getEntity();
        Log.d(TAG,
                "HttpUtils: status=" + status + " size=" + (entity != null ? entity.getContentLength() : -1));
        for (Header header : req.getAllHeaders()) {
            if (header != null) {
                Log.v(TAG, "HttpUtils: header " + header.getName() + "=" + header.getValue());
            }
        }
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "HttpUtils: Error closing input stream: " + e.getMessage());
                        }
                    }
                }
                if (entity.isChunked()) {
                    Log.d(TAG, "HttpUtils: transfer encoding is chunked");
                    int bytesTobeRead = mmsConfig.getMaxMessageSize();
                    byte[] tempBody = new byte[bytesTobeRead];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        int bytesRead = 0;
                        int offset = 0;
                        boolean readError = false;
                        do {
                            try {
                                bytesRead = dis.read(tempBody, offset, bytesTobeRead);
                            } catch (IOException e) {
                                readError = true;
                                Log.e(TAG, "HttpUtils: error reading input stream", e);
                                break;
                            }
                            if (bytesRead > 0) {
                                bytesTobeRead -= bytesRead;
                                offset += bytesRead;
                            }
                        } while (bytesRead >= 0 && bytesTobeRead > 0);
                        if (bytesRead == -1 && offset > 0 && !readError) {
                            // offset is same as total number of bytes read
                            // bytesRead will be -1 if the data was read till the eof
                            body = new byte[offset];
                            System.arraycopy(tempBody, 0, body, 0, offset);
                            Log.d(TAG, "HttpUtils: Chunked response length " + offset);
                        } else {
                            Log.e(TAG, "HttpUtils: Response entity too large or empty");
                        }
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "HttpUtils: Error closing input stream", e);
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        if (status.getStatusCode() != 200) { // HTTP 200 is success.
            StringBuilder sb = new StringBuilder();
            if (body != null) {
                sb.append("response: text=").append(new String(body)).append('\n');
            }
            for (Header header : req.getAllHeaders()) {
                if (header != null) {
                    sb.append("req header: ").append(header.getName()).append('=').append(header.getValue())
                            .append('\n');
                }
            }
            for (Header header : response.getAllHeaders()) {
                if (header != null) {
                    sb.append("resp header: ").append(header.getName()).append('=').append(header.getValue())
                            .append('\n');
                }
            }
            Log.e(TAG,
                    "HttpUtils: error response -- \n" + "mStatusCode=" + status.getStatusCode() + "\n"
                            + "reason=" + status.getReasonPhrase() + "\n" + "url=" + url + "\n" + "method="
                            + methodString + "\n" + "isProxySet=" + isProxySet + "\n" + "proxyHost=" + proxyHost
                            + "\n" + "proxyPort=" + proxyPort + (sb != null ? "\n" + sb.toString() : ""));
            throw new MmsHttpException(status.getReasonPhrase());
        }
        return body;
    } catch (IOException e) {
        Log.e(TAG, "HttpUtils: IO failure", e);
        throw new MmsHttpException(e);
    } catch (URISyntaxException e) {
        Log.e(TAG, "HttpUtils: invalid url " + url);
        throw new MmsHttpException("Invalid url " + url);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:org.eclipse.mylyn.commons.http.HttpUtil.java

public static HttpHost createHost(HttpRequestBase method) {
    URI uri = method.getURI();
    return new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
}

From source file:org.dvbviewer.controller.io.ServerRequest.java

/**
 * Gets the Recording service auth scope.
 * //from   w w w.  ja va  2s  .  co  m
 * @return the rs auth scope
 * @author RayBa
 * @date 13.04.2012
 */
private static AuthScope getRsAuthScope() {
    if (rsAuthScope == null) {
        if (urlValidator.isValid(ServerConsts.REC_SERVICE_URL)) {
            URI uri;
            try {
                uri = new URI(ServerConsts.REC_SERVICE_URL);
                rsAuthScope = new AuthScope(uri.getHost(), uri.getPort());
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }
    }
    return rsAuthScope;
}

From source file:org.dvbviewer.controller.io.ServerRequest.java

/**
 * Gets the client auth scope.//from ww w.  ja v a2  s .  co  m
 * 
 * @return the client auth scope
 * @author RayBa
 * @date 13.04.2012
 */
private static AuthScope getClientAuthScope() {
    if (clientAuthScope == null) {
        if (urlValidator.isValid(ServerConsts.DVBVIEWER_URL)) {
            URI uri;
            try {
                uri = new URI(ServerConsts.DVBVIEWER_URL);
                clientAuthScope = new AuthScope(uri.getHost(), uri.getPort());
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }
    }
    return clientAuthScope;
}