Example usage for java.net URI getPort

List of usage examples for java.net URI getPort

Introduction

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

Prototype

public int getPort() 

Source Link

Document

Returns the port number of this URI.

Usage

From source file:com.microsoft.office365.http.FroyoHttpConnection.java

@Override
public ListenableFuture<Response> execute(final Request request) {

    final SettableFuture<Response> future = SettableFuture.create();

    final RequestTask requestTask = new RequestTask() {

        AndroidHttpClient mClient;//from ww w.jav  a2s  .  c  o m
        InputStream mResponseStream;

        @Override
        protected Void doInBackground(Void... voids) {
            if (request == null) {
                future.setException(new IllegalArgumentException("request"));
            }

            mClient = AndroidHttpClient.newInstance(Platform.getUserAgent());
            mResponseStream = null;
            URI uri;

            try {
                HttpRequest realRequest = createRealRequest(request);
                uri = new URI(request.getUrl());

                HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

                HttpResponse response;

                try {
                    response = mClient.execute(host, realRequest);
                } catch (SocketTimeoutException timeoutException) {
                    closeStreamAndClient();
                    future.setException(timeoutException);
                    return null;
                }

                mResponseStream = response.getEntity().getContent();
                Header[] headers = response.getAllHeaders();
                Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                for (Header header : headers) {
                    String headerName = header.getName();
                    if (headersMap.containsKey(headerName)) {
                        headersMap.get(headerName).add(header.getValue());
                    } else {
                        List<String> headerValues = new ArrayList<String>();
                        headerValues.add(header.getValue());
                        headersMap.put(headerName, headerValues);
                    }
                }

                future.set(new StreamResponse(mResponseStream, response.getStatusLine().getStatusCode(),
                        headersMap));
                closeStreamAndClient();
            } catch (Exception e) {
                closeStreamAndClient();

                future.setException(e);
            }

            return null;
        }

        protected void closeStreamAndClient() {
            if (mResponseStream != null) {
                try {
                    mResponseStream.close();
                } catch (IOException e) {
                }
            }

            if (mClient != null) {
                mClient.close();
            }
        }
    };

    Futures.addCallback(future, new FutureCallback<Response>() {
        @Override
        public void onFailure(Throwable arg0) {
            requestTask.closeStreamAndClient();

        }

        @Override
        public void onSuccess(Response response) {
        }
    });

    executeTask(requestTask);

    return future;
}

From source file:org.expath.httpclient.impl.ApacheHttpConnection.java

/**
 * Set the credentials on the client, based on the {@link HttpCredentials} object.
 *//*from   w  w  w  .j  ava 2s.c o m*/
private void setCredentials(HttpCredentials cred) throws HttpClientException {
    if (cred == null) {
        return;
    }
    URI uri = myRequest.getURI();
    int port = uri.getPort();
    if (port == -1) {
        String scheme = uri.getScheme();
        if ("http".equals(scheme)) {
            port = 80;
        } else if ("https".equals(scheme)) {
            port = 443;
        } else {
            throw new HttpClientException("Unknown scheme: " + uri);
        }
    }
    String host = uri.getHost();
    String user = cred.getUser();
    String pwd = cred.getPwd();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Set credentials for " + host + ":" + port + " - " + user + " - ***");
    }
    Credentials c = new UsernamePasswordCredentials(user, pwd);
    AuthScope scope = new AuthScope(host, port);
    myClient.getCredentialsProvider().setCredentials(scope, c);
}

From source file:com.taobao.gecko.service.impl.DefaultRemotingClient.java

private InetSocketAddress getSocketAddrFromGroup(String group) throws NotifyRemotingException {
    if (group == null) {
        throw new IllegalArgumentException("Null group");
    }//ww  w  . jav a 2 s  .  c o m
    group = group.trim();
    if (!group.startsWith(this.config.getWireFormatType().getScheme())) {
        throw new NotifyRemotingException(
                "Group" + this.config.getWireFormatType().getScheme() + "");
    }
    try {
        final URI uri = new URI(group);
        return new InetSocketAddress(uri.getHost(), uri.getPort());
    } catch (final Exception e) {
        throw new NotifyRemotingException("uri,url=" + group, e);
    }
}

From source file:com.epam.reportportal.apache.http.impl.execchain.MinimalClientExec.java

public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    rewriteRequestURI(request, route);//w  ww . j av  a  2  s .c om

    final ConnectionRequest connRequest = connManager.requestConnection(route, null);
    if (execAware != null) {
        if (execAware.isAborted()) {
            connRequest.cancel();
            throw new RequestAbortedException("Request aborted");
        } else {
            execAware.setCancellable(connRequest);
        }
    }

    final RequestConfig config = context.getRequestConfig();

    final HttpClientConnection managedConn;
    try {
        final int timeout = config.getConnectionRequestTimeout();
        managedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS);
    } catch (final InterruptedException interrupted) {
        Thread.currentThread().interrupt();
        throw new RequestAbortedException("Request aborted", interrupted);
    } catch (final ExecutionException ex) {
        Throwable cause = ex.getCause();
        if (cause == null) {
            cause = ex;
        }
        throw new RequestAbortedException("Request execution failed", cause);
    }

    final ConnectionHolder releaseTrigger = new ConnectionHolder(log, connManager, managedConn);
    try {
        if (execAware != null) {
            if (execAware.isAborted()) {
                releaseTrigger.close();
                throw new RequestAbortedException("Request aborted");
            } else {
                execAware.setCancellable(releaseTrigger);
            }
        }

        if (!managedConn.isOpen()) {
            final int timeout = config.getConnectTimeout();
            this.connManager.connect(managedConn, route, timeout > 0 ? timeout : 0, context);
            this.connManager.routeComplete(managedConn, route, context);
        }
        final int timeout = config.getSocketTimeout();
        if (timeout >= 0) {
            managedConn.setSocketTimeout(timeout);
        }

        HttpHost target = null;
        final HttpRequest original = request.getOriginal();
        if (original instanceof HttpUriRequest) {
            final URI uri = ((HttpUriRequest) original).getURI();
            if (uri.isAbsolute()) {
                target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
            }
        }
        if (target == null) {
            target = route.getTargetHost();
        }

        context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
        context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
        context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn);
        context.setAttribute(HttpClientContext.HTTP_ROUTE, route);

        httpProcessor.process(request, context);
        final HttpResponse response = requestExecutor.execute(request, managedConn, context);
        httpProcessor.process(response, context);

        // The connection is in or can be brought to a re-usable state.
        if (reuseStrategy.keepAlive(response, context)) {
            // Set the idle duration of this connection
            final long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
            releaseTrigger.setValidFor(duration, TimeUnit.MILLISECONDS);
            releaseTrigger.markReusable();
        } else {
            releaseTrigger.markNonReusable();
        }

        // check for entity, release connection if possible
        final HttpEntity entity = response.getEntity();
        if (entity == null || !entity.isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            releaseTrigger.releaseConnection();
            return Proxies.enhanceResponse(response, null);
        } else {
            return Proxies.enhanceResponse(response, releaseTrigger);
        }
    } catch (final ConnectionShutdownException ex) {
        final InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down");
        ioex.initCause(ex);
        throw ioex;
    } catch (final HttpException ex) {
        releaseTrigger.abortConnection();
        throw ex;
    } catch (final IOException ex) {
        releaseTrigger.abortConnection();
        throw ex;
    } catch (final RuntimeException ex) {
        releaseTrigger.abortConnection();
        throw ex;
    }
}

From source file:com.jaeksoft.searchlib.crawler.rest.RestCrawlThread.java

private void callback(HttpDownloader downloader, URI uri, String query) throws URISyntaxException,
        ClientProtocolException, IllegalStateException, IOException, SearchLibException {
    uri = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), query, uri.getFragment());
    DownloadItem dlItem = downloader.request(uri, restCrawlItem.getCallbackMethod(),
            restCrawlItem.getCredential(), null, null, null);
    dlItem.checkNoErrorList(200, 201, 202, 203);
}

From source file:org.soyatec.windowsazure.authenticate.SharedKeyCredentialsWrapper.java

/**
 * Replace the uri container name./* w  ww.j ava  2 s.c o m*/
 * 
 * @param uri
 * @param accountName
 * @return The uri after be replaced the account name with the input
 *         accountName.
 */
private URI replaceAccountName(URI uri, String accountName) {
    try {
        String host = uri.getHost();
        String[] temp = host.split("\\.");
        temp[0] = accountName;
        return URIUtils.createURI(uri.getScheme(), join(".", temp), uri.getPort(),
                HttpUtilities.getNormalizePath(uri),
                (uri.getQuery() == null ? Utilities.emptyString() : uri.getQuery()), uri.getFragment());
    } catch (URISyntaxException e) {
        Logger.error("", e);
    }
    return uri;
}

From source file:com.subgraph.vega.internal.http.requests.HttpRequestBuilder.java

@Override
public synchronized void setFromUri(URI uri) {
    if (uri.getScheme() != null) {
        scheme = uri.getScheme();/* www.  j av a 2s. c  o m*/
        if (uri.getHost() != null) {
            host = uri.getHost();
            hostPort = uri.getPort();
            if (hostPort == -1) {
                hostPort = getSchemeDefaultPort(scheme);
            }
        }
    }

    setPathFromUri(uri);
}