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:com.t3.macro.api.views.MacroButtonView.java

public static Object executeLink(String link) throws MacroException {
    try {/*www .j  a  v  a  2  s  .c  o m*/
        URI u = new URI(link);
        MacroButtonProperties mbp;
        Token t = null;

        //campaign macro
        if ("CampaignPanel".equals(u.getHost())) {
            CampaignFunctions cf = new CampaignFunctions();
            MacroButtonView mv = cf.getCampaignMacro(URLDecoder.decode(u.getPath(), "utf8").substring(1));
            if (mv == null)
                throw new IllegalArgumentException(
                        "Campaign macro '" + URLDecoder.decode(u.getPath(), "utf8") + " not found.");
            else
                mbp = mv.macro;
        }
        //global macro
        else if ("GlobalPanel".equals(u.getHost())) {
            CampaignFunctions cf = new CampaignFunctions();
            MacroButtonView mv = cf.getGlobalMacro(URLDecoder.decode(u.getPath(), "utf8").substring(1));
            if (mv == null)
                throw new IllegalArgumentException(
                        "Global macro '" + URLDecoder.decode(u.getPath(), "utf8").substring(1) + " not found.");
            else
                mbp = mv.macro;
        }
        //token macro
        else {
            t = TabletopTool.getFrame().findToken(new GUID(u.getHost()));
            mbp = t.getMacro(URLDecoder.decode(u.getPath(), "utf8").substring(1), false);
        }
        HashMap<String, Object> arguments = new HashMap<String, Object>();
        if (u.getQuery() != null) {
            for (String a : StringUtils.split(u.getQuery(), '&')) {
                String[] aps = StringUtils.split(a, '=');
                arguments.put(aps[0], URLDecoder.decode(aps[1], "utf8"));
            }
        }
        return mbp.executeMacro(t, arguments);
    } catch (UnsupportedEncodingException | URISyntaxException e) {
        throw new MacroException(e);
    }
}

From source file:sh.calaba.driver.server.CalabashNodeConfiguration.java

/**
 * Reads the the driver configuration from the specified URI. The file is expected to be in JSON
 * format.// w w  w .ja  v  a 2s .  com
 * 
 * @param driverConfigFileURI The file name of the driver configuration file URI.
 * @return The Calabash node configuration.
 * @throws CalabashConfigurationException On IO and Parsing errors.
 * @throws InvalidParameterException if parameter is null or empty
 */
public static CalabashNodeConfiguration readFromURI(URI driverConfigFileURI)
        throws CalabashConfigurationException {
    if (driverConfigFileURI == null) {
        throw new InvalidParameterException("Calabash-Driver Configuration-URI is missing.");
    }
    if (driverConfigFileURI.getHost() == null || driverConfigFileURI.getPath() == null) {
        throw new InvalidParameterException("Calabash-Driver Configuration-URI is invalid.");
    }
    String driverConfiguration;
    try {
        HttpClient client = getDefaultHttpClient();
        HttpGet request = new HttpGet(driverConfigFileURI);
        HttpResponse response = client.execute(request);

        driverConfiguration = IOUtils.toString(response.getEntity().getContent());
    } catch (IOException e1) {
        logger.error("Error occured while reading config from URI:", e1);
        throw new CalabashConfigurationException(
                "Error reading file content. Did you have specified the right URI?", e1);
    } catch (KeyManagementException e) {
        logger.error("Error occured while creating httpclient:", e);
        throw new CalabashConfigurationException("Error occured while creating httpclient", e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("Error occured while creating httpclient:", e);
        throw new CalabashConfigurationException("Error occured while creating httpclient", e);
    }

    try {
        return new CalabashNodeConfiguration(new JSONObject(driverConfiguration));
    } catch (JSONException e) {
        logger.error("Error occured while parsing config file: ", e);
        throw new CalabashConfigurationException("Error occured during parsing json file from URI: '"
                + driverConfigFileURI + "'. Pls make sure you are using a valid JSON file!", e);
    }
}

From source file:models.NotificationMail.java

/**
 * Make every link to be absolute and to have 'rel=noreferrer' if
 * necessary.//from   ww  w . j ava  2s .  c om
 */
public static void handleLinks(Document doc) {
    String hostname = Config.getHostname();
    String[] attrNames = { "src", "href" };
    Boolean noreferrer = play.Configuration.root().getBoolean("application.noreferrer", false);

    for (String attrName : attrNames) {
        Elements tags = doc.select("*[" + attrName + "]");
        for (Element tag : tags) {
            boolean isNoreferrerRequired = false;
            String uriString = tag.attr(attrName);

            if (noreferrer && attrName.equals("href")) {
                isNoreferrerRequired = true;
            }

            try {
                URI uri = new URI(uriString);

                if (!uri.isAbsolute()) {
                    tag.attr(attrName, Url.create(uriString));
                }

                if (uri.getHost() == null || uri.getHost().equals(hostname)) {
                    isNoreferrerRequired = false;
                }
            } catch (URISyntaxException e) {
                play.Logger.info("A malformed URI is detected while" + " checking an email to send", e);
            }

            if (isNoreferrerRequired) {
                tag.attr("rel", tag.attr("rel") + " noreferrer");
            }
        }
    }
}

From source file:com.microsoft.gittf.client.clc.connection.GitTFHTTPClientFactory.java

/**
 * Determines whether the given host should be proxied or not, based on the
 * comma-separated list of wildcards to not proxy (generally taken from the
 * <code>http.nonProxyHosts</code> system property.
 * //from  w  w w .  ja v a 2s  .com
 * @param host
 *        the host to query (not <code>null</code>)
 * @param nonProxyHosts
 *        the pipe-separated list of hosts (or wildcards) that should not be
 *        proxied, or <code>null</code> if all hosts are proxied
 * @return <code>true</code> if the host should be proxied,
 *         <code>false</code> otherwise
 */
static boolean hostExcludedFromProxyEnvironment(URI serverURI, String nonProxyHosts) {
    if (serverURI == null || serverURI.getHost() == null || nonProxyHosts == null) {
        return false;
    }

    nonProxyHosts = nonProxyHosts.trim();
    if (nonProxyHosts.length() == 0) {
        return false;
    }

    /*
     * The no_proxy setting may be '*' to indicate nothing is proxied.
     * However, this is the only allowable use of a wildcard.
     */
    if ("*".equals(nonProxyHosts)) //$NON-NLS-1$
    {
        return true;
    }

    String serverHost = serverURI.getHost();

    /* Map default ports to the appropriate default. */
    int serverPort = serverURI.getPort();

    if (serverPort == -1) {
        try {
            serverPort = Protocol.getProtocol(serverURI.getScheme().toLowerCase()).getDefaultPort();
        } catch (IllegalStateException e) {
            serverPort = 80;
        }
    }

    for (String nonProxyHost : nonProxyHosts.split(",")) //$NON-NLS-1$
    {
        int nonProxyPort = -1;

        if (nonProxyHost.contains(":")) //$NON-NLS-1$
        {
            String[] nonProxyParts = nonProxyHost.split(":", 2); //$NON-NLS-1$

            nonProxyHost = nonProxyParts[0];

            try {
                nonProxyPort = Integer.parseInt(nonProxyParts[1]);
            } catch (Exception e) {
                log.warn(MessageFormat.format("Could not parse port in non_proxy setting: {0}, ignoring port", //$NON-NLS-1$
                        nonProxyParts[1]));
            }
        }

        /*
         * If the no_proxy entry specifies a port, match it exactly. If it
         * does not, this means to match all ports.
         */
        if (nonProxyPort != -1 && serverPort != nonProxyPort) {
            continue;
        }

        /*
         * Otherwise, the nonProxyHost portion is treated as the trailing
         * DNS entry
         */
        if (LocaleInvariantStringHelpers.caseInsensitiveEndsWith(serverHost, nonProxyHost)) {
            return true;
        }
    }

    return false;
}

From source file:com.microsoft.tfs.client.clc.CLCHTTPClientFactory.java

/**
 * Determines whether the given host should be proxied or not, based on the
 * comma-separated list of wildcards to not proxy (generally taken from the
 * <code>http.nonProxyHosts</code> system property.
 *
 * @param host/*from w  ww  . j a va2s.c  om*/
 *        the host to query (not <code>null</code>)
 * @param nonProxyHosts
 *        the pipe-separated list of hosts (or wildcards) that should not be
 *        proxied, or <code>null</code> if all hosts are proxied
 * @return <code>true</code> if the host should be proxied,
 *         <code>false</code> otherwise
 */
static boolean hostExcludedFromProxyEnvironment(final URI serverURI, String nonProxyHosts) {
    if (serverURI == null || serverURI.getHost() == null || nonProxyHosts == null) {
        return false;
    }

    nonProxyHosts = nonProxyHosts.trim();
    if (nonProxyHosts.length() == 0) {
        return false;
    }

    /*
     * The no_proxy setting may be '*' to indicate nothing is proxied.
     * However, this is the only allowable use of a wildcard.
     */
    if ("*".equals(nonProxyHosts)) //$NON-NLS-1$
    {
        return true;
    }

    final String serverHost = serverURI.getHost();

    /* Map default ports to the appropriate default. */
    int serverPort = serverURI.getPort();

    if (serverPort == -1) {
        try {
            serverPort = Protocol.getProtocol(serverURI.getScheme().toLowerCase()).getDefaultPort();
        } catch (final IllegalStateException e) {
            serverPort = 80;
        }
    }

    for (String nonProxyHost : nonProxyHosts.split(",")) //$NON-NLS-1$
    {
        int nonProxyPort = -1;

        if (nonProxyHost.contains(":")) //$NON-NLS-1$
        {
            final String[] nonProxyParts = nonProxyHost.split(":", 2); //$NON-NLS-1$

            nonProxyHost = nonProxyParts[0];

            try {
                nonProxyPort = Integer.parseInt(nonProxyParts[1]);
            } catch (final Exception e) {
                log.warn(MessageFormat.format("Could not parse port in non_proxy setting: {0}, ignoring port", //$NON-NLS-1$
                        nonProxyParts[1]));
            }
        }

        /*
         * If the no_proxy entry specifies a port, match it exactly. If it
         * does not, this means to match all ports.
         */
        if (nonProxyPort != -1 && serverPort != nonProxyPort) {
            continue;
        }

        /*
         * Otherwise, the nonProxyHost portion is treated as the trailing
         * DNS entry
         */
        if (LocaleInvariantStringHelpers.caseInsensitiveEndsWith(serverHost, nonProxyHost)) {
            return true;
        }
    }

    return false;
}

From source file:password.pwm.http.servlet.oauth.OAuthMachine.java

public static String figureOauthSelfEndPointUrl(final PwmRequest pwmRequest) {
    final String debugSource;
    final String redirect_uri;

    {// w ww  .  ja v a  2  s .  c o  m
        final String returnUrlOverride = pwmRequest.getConfig()
                .readAppProperty(AppProperty.OAUTH_RETURN_URL_OVERRIDE);
        final String siteURL = pwmRequest.getConfig().readSettingAsString(PwmSetting.PWM_SITE_URL);
        if (returnUrlOverride != null && !returnUrlOverride.trim().isEmpty()) {
            debugSource = "AppProperty(\"" + AppProperty.OAUTH_RETURN_URL_OVERRIDE.getKey() + "\")";
            redirect_uri = returnUrlOverride + PwmServletDefinition.OAuthConsumer.servletUrl();
        } else if (siteURL != null && !siteURL.trim().isEmpty()) {
            debugSource = "SiteURL Setting";
            redirect_uri = siteURL + PwmServletDefinition.OAuthConsumer.servletUrl();
        } else {
            debugSource = "Input Request URL";
            final String inputURI = pwmRequest.getHttpServletRequest().getRequestURL().toString();
            try {
                final URI requestUri = new URI(inputURI);
                final int port = requestUri.getPort();
                redirect_uri = requestUri.getScheme() + "://" + requestUri.getHost()
                        + (port > 0 && port != 80 && port != 443 ? ":" + requestUri.getPort() : "")
                        + pwmRequest.getContextPath() + PwmServletDefinition.OAuthConsumer.servletUrl();
            } catch (URISyntaxException e) {
                throw new IllegalStateException(
                        "unable to parse inbound request uri while generating oauth redirect: "
                                + e.getMessage());
            }
        }
    }

    LOGGER.trace("calculated oauth self end point URI as '" + redirect_uri + "' using method " + debugSource);
    return redirect_uri;
}

From source file:org.hl7.fhir.client.ResourceAddress.java

public static URI buildEndpointUriFromString(String endpointPath) {
    URI uri = null;
    try {//from  w  w  w . java 2s  .  co m
        URIBuilder uriBuilder = new URIBuilder(endpointPath);
        uri = uriBuilder.build();
        String scheme = uri.getScheme();
        String host = uri.getHost();
        if (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https")) {
            throw new EFhirClientException("Scheme must be 'http' or 'https': " + uri);
        }
        if (StringUtils.isBlank(host)) {
            throw new EFhirClientException("host cannot be blank: " + uri);
        }
    } catch (URISyntaxException e) {
        throw new EFhirClientException("Invalid URI", e);
    }
    return uri;
}

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

private static Node readNode(String nodeId, JsonParser parser, Scheme scheme) throws IOException {
    HttpHost publishedHost = null;//  w w w.java2 s .  com
    /*
     * 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.code4bones.utils.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 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.");
    }

    NetLog.v("httpConnection: params list");
    NetLog.v("\ttoken\t\t= " + token);
    NetLog.v("\turl\t\t= " + url);
    NetLog.v("\tmethod\t\t= "
            + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN")));
    NetLog.v("\tisProxySet\t= " + isProxySet);
    NetLog.v("\tproxyHost\t= " + proxyHost);
    NetLog.v("\tproxyPort\t= " + proxyPort);
    //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);
        {
            //TODO: MmsConfig.getUaProfTagName();
            String xWapProfileTagName = "x-wap-profile";//MmsConfig.getUaProfTagName();
            String xWapProfileUrl = "mms.beeline.ru"; //MmsConfig.getUaProfUrl();

            if (xWapProfileUrl != null) {
                NetLog.v("[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.
        //TODO: MmsConfig.getHttpParams();
        String extraHttpParams = null; //MmsConfig.getHttpParams();

        if (extraHttpParams != null) {
            String line1Number = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
                    .getLine1Number();
            String line1Key = "key"; //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");
                    //TODO: MmsConfig.getMaxMessageSize();
                    int bytesTobeRead = 4096; //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.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./* ww  w .j a va  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.
 * @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.");
    }
    {
        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;
}