Example usage for org.apache.http.client.utils URIBuilder setPort

List of usage examples for org.apache.http.client.utils URIBuilder setPort

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIBuilder setPort.

Prototype

public URIBuilder setPort(final int port) 

Source Link

Document

Sets URI port.

Usage

From source file:org.opennms.netmgt.poller.monitors.HttpPostMonitor.java

/**
 * {@inheritDoc}/*  w w w. j  a  v  a2  s .c o m*/
 *
 * Poll the specified address for service availability.
 *
 * During the poll an attempt is made to execute the named method (with optional input) connect on the specified port. If
 * the exec on request is successful, the banner line generated by the
 * interface is parsed and if the banner text indicates that we are talking
 * to Provided that the interface's response is valid we set the service
 * status to SERVICE_AVAILABLE and return.
 */
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    NetworkInterface<InetAddress> iface = svc.getNetInterface();

    // Process parameters

    // Get interface address from NetworkInterface
    if (iface.getType() != NetworkInterface.TYPE_INET)
        throw new NetworkInterfaceNotSupportedException(
                "Unsupported interface type, only TYPE_INET currently supported");

    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);

    // Port
    int port = ParameterMap.getKeyedInteger(parameters, PARAMETER_PORT, DEFAULT_PORT);

    //URI
    String strURI = ParameterMap.getKeyedString(parameters, PARAMETER_URI, DEFAULT_URI);

    //Username
    String strUser = ParameterMap.getKeyedString(parameters, PARAMETER_USERNAME, null);

    //Password
    String strPasswd = ParameterMap.getKeyedString(parameters, PARAMETER_PASSWORD, null);

    //BannerMatch
    String strBannerMatch = ParameterMap.getKeyedString(parameters, PARAMETER_BANNER, null);

    //Scheme
    String strScheme = ParameterMap.getKeyedString(parameters, PARAMETER_SCHEME, DEFAULT_SCHEME);

    //Payload
    String strPayload = ParameterMap.getKeyedString(parameters, PARAMETER_PAYLOAD, null);

    //Mimetype
    String strMimetype = ParameterMap.getKeyedString(parameters, PARAMETER_MIMETYPE, DEFAULT_MIMETYPE);

    //Charset
    String strCharset = ParameterMap.getKeyedString(parameters, PARAMETER_CHARSET, DEFAULT_CHARSET);

    //SSLFilter
    boolean boolSSLFilter = ParameterMap.getKeyedBoolean(parameters, PARAMETER_SSLFILTER, DEFAULT_SSLFILTER);

    // Get the address instance.
    InetAddress ipv4Addr = (InetAddress) iface.getAddress();

    final String hostAddress = InetAddressUtils.str(ipv4Addr);

    LOG.debug("poll: address = " + hostAddress + ", port = " + port + ", " + tracker);

    // Give it a whirl
    PollStatus serviceStatus = PollStatus.unavailable();

    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        HttpClientWrapper clientWrapper = null;
        try {
            tracker.startAttempt();

            clientWrapper = HttpClientWrapper.create().setConnectionTimeout(tracker.getSoTimeout())
                    .setSocketTimeout(tracker.getSoTimeout()).setRetries(DEFAULT_RETRY);

            if (boolSSLFilter) {
                clientWrapper.trustSelfSigned(strScheme);
            }
            HttpEntity postReq;

            if (strUser != null && strPasswd != null) {
                clientWrapper.addBasicCredentials(strUser, strPasswd);
            }

            try {
                postReq = new StringEntity(strPayload, ContentType.create(strMimetype, strCharset));
            } catch (final UnsupportedCharsetException e) {
                serviceStatus = PollStatus
                        .unavailable("Unsupported encoding encountered while constructing POST body " + e);
                break;
            }

            URIBuilder ub = new URIBuilder();
            ub.setScheme(strScheme);
            ub.setHost(hostAddress);
            ub.setPort(port);
            ub.setPath(strURI);

            LOG.debug("HttpPostMonitor: Constructed URL is " + ub.toString());

            HttpPost post = new HttpPost(ub.build());
            post.setEntity(postReq);
            CloseableHttpResponse response = clientWrapper.execute(post);

            LOG.debug("HttpPostMonitor: Status Line is " + response.getStatusLine());

            if (response.getStatusLine().getStatusCode() > 399) {
                LOG.info("HttpPostMonitor: Got response status code "
                        + response.getStatusLine().getStatusCode());
                LOG.debug("HttpPostMonitor: Received server response: " + response.getStatusLine());
                LOG.debug("HttpPostMonitor: Failing on bad status code");
                serviceStatus = PollStatus
                        .unavailable("HTTP(S) Status code " + response.getStatusLine().getStatusCode());
                break;
            }

            LOG.debug("HttpPostMonitor: Response code is valid");
            double responseTime = tracker.elapsedTimeInMillis();

            HttpEntity entity = response.getEntity();
            InputStream responseStream = entity.getContent();
            String Strresponse = IOUtils.toString(responseStream);

            if (Strresponse == null)
                continue;

            LOG.debug("HttpPostMonitor: banner = " + Strresponse);
            LOG.debug("HttpPostMonitor: responseTime= " + responseTime + "ms");

            //Could it be a regex?
            if (strBannerMatch.charAt(0) == '~') {
                if (!Strresponse.matches(strBannerMatch.substring(1))) {
                    serviceStatus = PollStatus
                            .unavailable("Banner does not match Regex '" + strBannerMatch + "'");
                    break;
                } else {
                    serviceStatus = PollStatus.available(responseTime);
                }
            } else {
                if (Strresponse.indexOf(strBannerMatch) > -1) {
                    serviceStatus = PollStatus.available(responseTime);
                } else {
                    serviceStatus = PollStatus
                            .unavailable("Did not find expected Text '" + strBannerMatch + "'");
                    break;
                }
            }

        } catch (final URISyntaxException e) {
            final String reason = "URISyntaxException for URI: " + strURI + " " + e.getMessage();
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            break;
        } catch (final Exception e) {
            final String reason = "Exception: " + e.getMessage();
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            break;
        } finally {
            IOUtils.closeQuietly(clientWrapper);
        }
    }

    // return the status of the service
    return serviceStatus;
}

From source file:org.zaizi.manifoldcf.authorities.authorities.alfresco.AlfrescoAuthorityConnector.java

/**
 * Obtain the access tokens for a given user name.
 * //  w  ww .  j  a v  a2s .  c  om
 * @param userName is the user name or identifier.
 * @return the response tokens (according to the current authority). (Should throws an exception only when a
 *         condition cannot be properly described within the authorization response object.)
 */
@Override
public AuthorizationResponse getAuthorizationResponse(String userName) throws ManifoldCFException {
    // String[] tokens = new String[] { userName };
    // return new AuthorizationResponse(tokens, AuthorizationResponse.RESPONSE_OK);

    List<String> tokens = new ArrayList<String>();
    try {
        URIBuilder uri = new URIBuilder();
        uri.setScheme(protocol);
        uri.setHost(server);
        uri.setPort(Integer.parseInt(port));
        uri.setPath(path + USER_AUTHORITIES_URI);
        uri.setParameter(USERNAME_PARAM, userName);

        HttpGet get = new HttpGet(uri.build());

        HttpResponse response = httpClient.execute(get);

        JSONObject json = new JSONObject(EntityUtils.toString(response.getEntity(), UTF8));

        JSONArray auths = (JSONArray) json.get(AUTHORITIES_JSON);
        if (auths != null) {
            int len = auths.length();
            for (int i = 0; i < len; i++) {
                tokens.add(auths.get(i).toString());
            }
        }

        EntityUtils.consume(response.getEntity());

    } catch (Exception e) {
        return new AuthorizationResponse(null, AuthorizationResponse.RESPONSE_UNREACHABLE);
    }

    return new AuthorizationResponse(tokens.toArray(new String[] {}), AuthorizationResponse.RESPONSE_OK);
}

From source file:io.kamax.mxisd.dns.ClientDnsOverwrite.java

public URIBuilder transform(URI initial) {
    URIBuilder builder = new URIBuilder(initial);
    Entry mapping = mappings.get(initial.getHost());
    if (mapping == null) {
        throw new InternalServerError("No DNS client override for " + initial.getHost());
    }/*from w  ww. j a  va 2s  .c o  m*/

    try {
        URL target = new URL(mapping.getValue());
        builder.setScheme(target.getProtocol());
        builder.setHost(target.getHost());
        if (target.getPort() != -1) {
            builder.setPort(target.getPort());
        }

        return builder;
    } catch (MalformedURLException e) {
        log.warn("Skipping DNS overwrite entry {} due to invalid value [{}]: {}", mapping.getName(),
                mapping.getValue(), e.getMessage());
        throw new ConfigurationException(
                "Invalid DNS overwrite entry in homeserver client: " + mapping.getName(), e.getMessage());
    }
}

From source file:com.liferay.ide.core.remote.RemoteConnection.java

protected Object httpJSONAPI(Object... args) throws APIException {
    if (!(args[0] instanceof HttpRequestBase)) {
        throw new IllegalArgumentException("First argument must be a HttpRequestBase."); //$NON-NLS-1$
    }/*w  ww . ja v  a 2  s. com*/

    Object retval = null;
    String api = null;
    Object[] params = new Object[0];

    final HttpRequestBase request = (HttpRequestBase) args[0];

    final boolean isPostRequest = request instanceof HttpPost;

    if (args[1] instanceof String) {
        api = args[1].toString();
    } else if (args[1] instanceof Object[]) {
        params = (Object[]) args[1];
        api = params[0].toString();
    } else {
        throw new IllegalArgumentException("2nd argument must be either String or Object[]"); //$NON-NLS-1$
    }

    try {
        final URIBuilder builder = new URIBuilder();
        builder.setScheme("http"); //$NON-NLS-1$
        builder.setHost(getHost());
        builder.setPort(getHttpPort());
        builder.setPath(api);

        List<NameValuePair> postParams = new ArrayList<NameValuePair>();

        if (params.length >= 3) {
            for (int i = 1; i < params.length; i += 2) {
                String name = null;
                String value = StringPool.EMPTY;

                if (params[i] != null) {
                    name = params[i].toString();
                }

                if (params[i + 1] != null) {
                    value = params[i + 1].toString();
                }

                if (isPostRequest) {
                    postParams.add(new BasicNameValuePair(name, value));
                } else {
                    builder.setParameter(name, value);
                }
            }
        }

        if (isPostRequest) {
            HttpPost postRequest = ((HttpPost) request);

            if (postRequest.getEntity() == null) {
                postRequest.setEntity(new UrlEncodedFormEntity(postParams));
            }
        }

        request.setURI(builder.build());

        String response = getHttpResponse(request);

        if (response != null && response.length() > 0) {
            Object jsonResponse = getJSONResponse(response);

            if (jsonResponse == null) {
                throw new APIException(api, "Unable to get response: " + response); //$NON-NLS-1$
            } else {
                retval = jsonResponse;
            }
        }
    } catch (APIException e) {
        throw e;
    } catch (Exception e) {
        throw new APIException(api, e);
    } finally {
        try {
            request.releaseConnection();
        } finally {
            // no need to log error
        }
    }

    return retval;
}

From source file:com.envirover.spl.SPLGroungControlTest.java

@Test
public void testMOMessagePipeline()
        throws URISyntaxException, ClientProtocolException, IOException, InterruptedException {
    System.out.println("MO TEST: Testing MO message pipeline...");

    Thread.sleep(1000);/*  ww w.  ja v  a2s  .co  m*/

    Thread mavlinkThread = new Thread(new Runnable() {
        public void run() {
            Socket client = null;

            try {
                System.out.printf("MO TEST: Connecting to tcp://%s:%d",
                        InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());
                System.out.println();

                client = new Socket(InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());

                System.out.printf("MO TEST: Connected tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(),
                        config.getMAVLinkPort());
                System.out.println();

                Parser parser = new Parser();
                DataInputStream in = new DataInputStream(client.getInputStream());
                while (true) {
                    MAVLinkPacket packet;
                    do {
                        int c = in.readUnsignedByte();
                        packet = parser.mavlink_parse_char(c);
                    } while (packet == null);

                    System.out.printf("MO TEST: MAVLink message received: msgid = %d", packet.msgid);
                    System.out.println();

                    Thread.sleep(100);
                }
            } catch (InterruptedException ex) {
                return;
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    mavlinkThread.start();

    HttpClient httpclient = HttpClients.createDefault();

    URIBuilder builder = new URIBuilder();
    builder.setScheme("http");
    builder.setHost(InetAddress.getLocalHost().getHostAddress());
    builder.setPort(config.getRockblockPort());
    builder.setPath(config.getHttpContext());

    URI uri = builder.build();
    HttpPost httppost = new HttpPost(uri);

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("imei", config.getRockBlockIMEI()));
    params.add(new BasicNameValuePair("momsn", "12345"));
    params.add(new BasicNameValuePair("transmit_time", "12-10-10 10:41:50"));
    params.add(new BasicNameValuePair("iridium_latitude", "52.3867"));
    params.add(new BasicNameValuePair("iridium_longitude", "0.2938"));
    params.add(new BasicNameValuePair("iridium_cep", "9"));
    params.add(new BasicNameValuePair("data", Hex.encodeHexString(getSamplePacket().encodePacket())));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // Execute and get the response.
    System.out.printf("MO TEST: Sending test message to %s", uri.toString());
    System.out.println();

    HttpResponse response = httpclient.execute(httppost);

    if (response.getStatusLine().getStatusCode() != 200) {
        fail(String.format("RockBLOCK HTTP message handler status code = %d.",
                response.getStatusLine().getStatusCode()));
    }

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream responseStream = entity.getContent();
        try {
            String responseString = IOUtils.toString(responseStream);
            System.out.println(responseString);
        } finally {
            responseStream.close();
        }
    }

    Thread.sleep(1000);

    mavlinkThread.interrupt();
    System.out.println("MO TEST: Complete.");
}

From source file:org.apache.ignite.console.agent.handlers.RestHandler.java

/**
 * @param uri Url./*from w  w  w.  j  ava 2  s.  c  om*/
 * @param params Params.
 * @param demo Use demo node.
 * @param mtd Method.
 * @param headers Headers.
 * @param body Body.
 */
protected RestResult executeRest(String uri, Map<String, Object> params, boolean demo, String mtd,
        Map<String, Object> headers, String body) throws IOException, URISyntaxException {
    if (log.isDebugEnabled())
        log.debug("Start execute REST command [method=" + mtd + ", uri=/" + (uri == null ? "" : uri)
                + ", parameters=" + params + "]");

    final URIBuilder builder;

    if (demo) {
        // try start demo if needed.
        AgentClusterDemo.testDrive(cfg);

        // null if demo node not started yet.
        if (cfg.demoNodeUri() == null)
            return RestResult.fail("Demo node is not started yet.", 404);

        builder = new URIBuilder(cfg.demoNodeUri());
    } else
        builder = new URIBuilder(cfg.nodeUri());

    if (builder.getPort() == -1)
        builder.setPort(DFLT_NODE_PORT);

    if (uri != null) {
        if (!uri.startsWith("/") && !cfg.nodeUri().endsWith("/"))
            uri = '/' + uri;

        builder.setPath(uri);
    }

    if (params != null) {
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (entry.getValue() != null)
                builder.addParameter(entry.getKey(), entry.getValue().toString());
        }
    }

    HttpRequestBase httpReq = null;

    try {
        if ("GET".equalsIgnoreCase(mtd))
            httpReq = new HttpGet(builder.build());
        else if ("POST".equalsIgnoreCase(mtd)) {
            HttpPost post;

            if (body == null) {
                List<NameValuePair> nvps = builder.getQueryParams();

                builder.clearParameters();

                post = new HttpPost(builder.build());

                if (!nvps.isEmpty())
                    post.setEntity(new UrlEncodedFormEntity(nvps));
            } else {
                post = new HttpPost(builder.build());

                post.setEntity(new StringEntity(body));
            }

            httpReq = post;
        } else
            throw new IOException("Unknown HTTP-method: " + mtd);

        if (headers != null) {
            for (Map.Entry<String, Object> entry : headers.entrySet())
                httpReq.addHeader(entry.getKey(),
                        entry.getValue() == null ? null : entry.getValue().toString());
        }

        try (CloseableHttpResponse resp = httpClient.execute(httpReq)) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            resp.getEntity().writeTo(out);

            Charset charset = Charsets.UTF_8;

            Header encodingHdr = resp.getEntity().getContentEncoding();

            if (encodingHdr != null) {
                String encoding = encodingHdr.getValue();

                charset = Charsets.toCharset(encoding);
            }

            return RestResult.success(resp.getStatusLine().getStatusCode(),
                    new String(out.toByteArray(), charset));
        } catch (ConnectException e) {
            log.info("Failed connect to node and execute REST command [uri=" + builder.build() + "]");

            return RestResult.fail("Failed connect to node and execute REST command.", 404);
        }
    } finally {
        if (httpReq != null)
            httpReq.reset();
    }
}

From source file:org.nectarframework.base.service.nanohttp.NanoHttpService.java

private Response serveProxy(ProxyResolution proxyResolution, String uri, Method method,
        Map<String, String> headers, Map<String, List<String>> parms, String queryParameterString,
        Map<String, String> files) {

    String remoteTarget = uri.substring(proxyResolution.getPath().length() + 1);
    if (!remoteTarget.startsWith("/")) {
        remoteTarget = "/" + remoteTarget;
    }//from  w w w  .jav  a  2 s .c om

    CloseableHttpClient httpclient = HttpClients.createDefault();
    URIBuilder remoteUri = new URIBuilder();
    remoteUri.setScheme("http");
    remoteUri.setHost(proxyResolution.getHost());
    remoteUri.setPort(proxyResolution.getPort());
    remoteUri.setPath(proxyResolution.getRequestPath() + remoteTarget);
    remoteUri.setCharset(Charset.defaultCharset());
    for (String k : parms.keySet()) {
        remoteUri.addParameter(k, parms.get(k).get(0));
    }

    HttpGet httpget;
    try {
        httpget = new HttpGet(remoteUri.build());
    } catch (URISyntaxException e) {
        Log.warn(e);
        return newFixedLengthResponse(Status.INTERNAL_ERROR, NanoHttpService.MIME_PLAINTEXT,
                "SERVER INTERNAL ERROR: URISyntaxException" + e.getMessage());
    }

    CloseableHttpResponse response = null;
    Response resp = null;
    try {
        response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream is = entity.getContent();
            long isl = entity.getContentLength();
            resp = new Response(Status.lookup(response.getStatusLine().getStatusCode()), null, is, isl);
        } else {
            resp = new Response(Status.lookup(response.getStatusLine().getStatusCode()), null, null, 0);
        }

        Header[] remoteHeaders = response.getAllHeaders();
        for (Header h : remoteHeaders) {
            resp.addHeader(h.getName(), h.getValue());
        }

        resp.setProxyResponse(response);

    } catch (IOException e) {
        Log.warn(e);
        return newFixedLengthResponse(Status.INTERNAL_ERROR, NanoHttpService.MIME_PLAINTEXT,
                "SERVER INTERNAL ERROR: IOException" + e.getMessage());
    }

    return resp;
}

From source file:org.testmp.datastore.client.DataStoreClient.java

@SuppressWarnings("unused")
private URIBuilder getCustomURIBuilder() {
    URIBuilder builder = new URIBuilder();
    builder.setScheme(dataStoreURL.getScheme());
    builder.setHost(dataStoreURL.getHost());
    builder.setPort(dataStoreURL.getPort());
    builder.setPath(dataStoreURL.getPath());
    return builder;
}

From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java

private URI buildUri(HttpRequest request, Joiner joiner) {
    URI requestUri = request.getUri();

    Map<String, Collection<String>> queryParams = request.getQueryParams();
    if (queryParams != null && !queryParams.isEmpty()) {
        URIBuilder uriBuilder = new URIBuilder();
        StringBuilder queryStringBuilder = new StringBuilder();
        boolean hasQuery = !queryParams.isEmpty();
        for (Map.Entry<String, Collection<String>> stringCollectionEntry : queryParams.entrySet()) {
            String key = stringCollectionEntry.getKey();
            Collection<String> queryParamsValueList = stringCollectionEntry.getValue();
            if (request.isQueryParamsParseAsMultiValue()) {
                for (String queryParamsValue : queryParamsValueList) {
                    uriBuilder.addParameter(key, queryParamsValue);
                    queryStringBuilder.append(key).append("=").append(queryParamsValue).append("&");
                }/*from www.  j  a  v a2s  .c o  m*/
            } else {
                String value = joiner.join(queryParamsValueList);
                uriBuilder.addParameter(key, value);
                queryStringBuilder.append(key).append("=").append(value).append("&");
            }
        }
        uriBuilder.setFragment(requestUri.getFragment());
        uriBuilder.setHost(requestUri.getHost());
        uriBuilder.setPath(requestUri.getPath());
        uriBuilder.setPort(requestUri.getPort());
        uriBuilder.setScheme(requestUri.getScheme());
        uriBuilder.setUserInfo(requestUri.getUserInfo());
        try {

            if (!autoEncodeUri) {
                String urlPath = "";
                if (requestUri.getRawPath() != null && requestUri.getRawPath().startsWith("/")) {
                    urlPath = requestUri.getRawPath();
                } else {
                    urlPath = "/" + requestUri.getRawPath();
                }

                if (hasQuery) {
                    String query = queryStringBuilder.substring(0, queryStringBuilder.length() - 1);
                    requestUri = new URI(requestUri.getScheme() + "://" + requestUri.getHost() + ":"
                            + requestUri.getPort() + urlPath + "?" + query);
                } else {
                    requestUri = new URI(requestUri.getScheme() + "://" + requestUri.getHost() + ":"
                            + requestUri.getPort() + urlPath);
                }
            } else {
                requestUri = uriBuilder.build();
            }
        } catch (URISyntaxException e) {
            LOGGER.warn("could not update uri: {}", requestUri);
        }
    }
    return requestUri;
}