Example usage for java.net URI getHost

List of usage examples for java.net URI getHost

Introduction

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

Prototype

public String getHost() 

Source Link

Document

Returns the host component of this URI.

Usage

From source file:org.apache.jena.jdbc.remote.RemoteEndpointDriver.java

/**
 * Get the URI with irrelevant components (Fragment and Querystring)
 * stripped off//from w  w w  . j  av  a 2s .c  o  m
 * 
 * @param input
 *            URI
 * @return URI with irrelevant components stripped off or null if stripping
 *         is impossible
 */
private static String stripIrrelevantComponents(String input) {
    try {
        URI orig = new URI(input);
        return new URI(orig.getScheme(), orig.getUserInfo(), orig.getHost(), orig.getPort(), orig.getPath(),
                null, null).toString();
    } catch (URISyntaxException e) {
        return null;
    }
}

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.//from   w  w w.j  a v  a2  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.
 * @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.
 */
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  a v a2 s.com
 * @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.");
    }

    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:com.inmobi.conduit.distcp.tools.util.DistCpUtils.java

public static boolean compareFs(FileSystem srcFs, FileSystem destFs) {
    URI srcUri = srcFs.getUri();
    URI dstUri = destFs.getUri();
    if (srcUri.getScheme() == null) {
        return false;
    }/*www  .ja  v  a2s .  c  o m*/
    if (!srcUri.getScheme().equals(dstUri.getScheme())) {
        return false;
    }
    String srcHost = srcUri.getHost();
    String dstHost = dstUri.getHost();
    if ((srcHost != null) && (dstHost != null)) {
        try {
            srcHost = InetAddress.getByName(srcHost).getCanonicalHostName();
            dstHost = InetAddress.getByName(dstHost).getCanonicalHostName();
        } catch (UnknownHostException ue) {
            return false;
        }
        if (!srcHost.equals(dstHost)) {
            return false;
        }
    } else if (srcHost == null && dstHost != null) {
        return false;
    } else if (srcHost != null) {
        return false;
    }
    //check for ports
    if (srcUri.getPort() != dstUri.getPort()) {
        return false;
    }
    return true;
}

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./*from  w ww  .  ja  v  a2  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 (>=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.jets3t.service.utils.SignatureUtils.java

/**
 * Replace the hostname of the given URI endpoint to match the given region.
 *
 * @param uri/*w  w w  . j  a va 2s.  c om*/
 * @param region
 *
 * @return
 * URI with hostname that may or may not have been changed to be appropriate
 * for the given region. For example, the hostname "s3.amazonaws.com" is
 * unchanged for the "us-east-1" region but for the "eu-central-1" region
 * becomes "s3-eu-central-1.amazonaws.com".
 */
public static URI awsV4CorrectHostnameForRegion(URI uri, String region) {
    String[] hostSplit = uri.getHost().split("\\.");
    if (region.equals("us-east-1")) {
        hostSplit[hostSplit.length - 3] = "s3";
    } else {
        hostSplit[hostSplit.length - 3] = "s3-" + region;
    }
    String newHost = ServiceUtils.join(hostSplit, ".");
    try {
        String rawPathAndQuery = uri.getRawPath();
        if (uri.getRawQuery() != null) {
            rawPathAndQuery += "?" + uri.getRawQuery();
        }
        return new URL(uri.getScheme(), newHost, uri.getPort(), rawPathAndQuery).toURI();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}

From source file:hsyndicate.hadoop.dfs.HSyndicateDFS.java

private static SyndicateFileSystem createHSyndicateFS(URI uri, Configuration conf) throws IOException {
    if (uri == null) {
        throw new IllegalArgumentException("uri is null");
    }/* w w  w.  j  av a 2s.  c om*/

    SyndicateFSConfiguration sconf = null;
    String ugHost = "";
    if (uri.getHost() != null && !uri.getHost().isEmpty()) {
        ugHost = uri.getHost();

        if (uri.getPort() > 0) {
            ugHost = ugHost + ":" + uri.getPort();
        }

        sconf = HSyndicateConfigUtils.createSyndicateConf(conf, ugHost);
    } else {
        sconf = HSyndicateConfigUtils.createSyndicateConf(conf);
    }

    try {
        return new SyndicateFileSystem(sconf, conf);
    } catch (InstantiationException ex) {
        throw new IOException(ex.getCause());
    }
}

From source file:org.jets3t.service.utils.SignatureUtils.java

/**
 * Determine the AWS Region to which a request will be sent based on the
 * request's Host endpoint. See/*from  w ww .ja  va 2s.  c o m*/
 * {@link "http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region"}
 *
 * @param requestURI
 * @return AWS region name corresponding to the request's Host endpoint.
 */
public static String awsRegionForRequest(URI requestURI) {
    String host = requestURI.getHost().toLowerCase();
    // Recognise default/legacy endpoints where the Host does not
    // correspond to the region name.
    if (host.endsWith("s3.amazonaws.com") || host.endsWith("s3-external-1.amazonaws.com")) {
        return null;
    }
    // Host names of the following forms include the region name as a
    // component of the Host name:
    //   s3-<regionName>.amazonaws.com
    //   s3.<regionName>.amazonaws.com
    //   s3.<regionName>.amazonaws.com.cn
    else if (host.endsWith(".amazonaws.com") || host.contains(".amazonaws.com.")) {
        String[] hostSplit = host.split("\\.");
        // Work forwards from start of host name to find the portion
        // immediately preceding the "amazonaws" part, which will either be
        // a region name or can be converted into a region name by removing
        // a "s3-" prefix.
        String regionNameCandidate = null;
        boolean wasS3PrefixFound = false;
        for (String portion : hostSplit) {
            if (portion.equals("amazonaws")) {
                break;
            } else if (portion.equals("s3")) {
                wasS3PrefixFound = true;
            }
            regionNameCandidate = portion;
        }
        if (null == regionNameCandidate) {
            return null;
        }
        if (regionNameCandidate.startsWith("s3-")) {
            return regionNameCandidate.substring("s3-".length());
        } else if (wasS3PrefixFound) {
            return regionNameCandidate;
        }
    }
    // No specific Host-to-region mappings available
    return null;
}