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:ac.simons.oembed.Oembed.java

private OembedProvider autodiscoverOembedURIForUrl(final String url) {
    OembedProvider rv = null;//from  ww  w  .ja  va2 s.  c o m

    try {
        final HttpGet request = new HttpGet(url);
        final HttpResponse httpResponse = this.httpClient.execute(request);
        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
            logger.warn(String.format("Autodiscovery for %s failed, server returned error %d: %s", url,
                    httpResponse.getStatusLine().getStatusCode(),
                    EntityUtils.toString(httpResponse.getEntity())));
        else {
            final URI uri = request.getURI();
            final Document document = Jsoup.parse(EntityUtils.toString(httpResponse.getEntity(), "UTF-8"),
                    String.format("%s://%s:%d", uri.getScheme(), uri.getHost(), uri.getPort()));
            for (Element alternate : document.getElementsByAttributeValue("rel", "alternate")) {
                if (alternate.attr("type").equalsIgnoreCase("application/json+oembed"))
                    rv = new AutodiscoveredOembedProvider(url, new URI(alternate.absUrl("href")), "json");
                else if (alternate.attr("type").equalsIgnoreCase("text/xml+oembed"))
                    rv = new AutodiscoveredOembedProvider(url, new URI(alternate.absUrl("href")), "xml");
                if (rv != null)
                    break;
            }
        }
    } catch (Exception e) {
        logger.warn(String.format("Autodiscovery for %s failedd: %s", url, e.getMessage()), e);
    }

    return rv;
}

From source file:microsoft.aspnet.signalr.client.http.android.AndroidHttpConnection.java

@Override
public HttpConnectionFuture execute(final Request request, final ResponseCallback responseCallback) {

    mLogger.log("Create new AsyncTask for HTTP Connection", LogLevel.Verbose);

    final HttpConnectionFuture future = new HttpConnectionFuture();

    final RequestTask requestTask = new RequestTask() {

        AndroidHttpClient mClient;/*from w w  w.j a  v a2  s.c o  m*/
        InputStream mResponseStream;

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

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

            try {
                mLogger.log("Create an Android-specific request", LogLevel.Verbose);
                request.log(mLogger);
                HttpRequest realRequest = createRealRequest(request);
                uri = new URI(request.getUrl());

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

                mLogger.log("Execute the HTTP Request", LogLevel.Verbose);
                HttpResponse response;

                try {
                    response = mClient.execute(host, realRequest);
                } catch (SocketTimeoutException timeoutException) {
                    closeStreamAndClient();
                    mLogger.log("Timeout executing request: " + timeoutException.getMessage(),
                            LogLevel.Information);

                    future.triggerTimeout(timeoutException);

                    return null;
                }

                mLogger.log("Request executed", LogLevel.Verbose);

                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);
                    }
                }

                responseCallback.onResponse(new StreamResponse(mResponseStream,
                        response.getStatusLine().getStatusCode(), headersMap));
                future.setResult(null);
                closeStreamAndClient();
            } catch (Exception e) {
                closeStreamAndClient();
                mLogger.log("Error executing request: " + e.getMessage(), LogLevel.Critical);

                future.triggerError(e);
            }

            return null;
        }

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

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

    future.onCancelled(new Runnable() {

        @Override
        public void run() {
            AsyncTask<Void, Void, Void> cancelTask = new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    requestTask.closeStreamAndClient();
                    return null;
                }
            };

            executeTask(cancelTask);
        }
    });

    executeTask(requestTask);

    return future;
}

From source file:edu.stanford.junction.provider.jx.Junction.java

public Junction(URI uri, ActivityScript script, final JunctionActor actor) throws JunctionException {
    this.setActor(actor);

    mAcceptedInvitation = uri;/*from w  w w . j ava 2 s . c  o  m*/
    mActivityScript = script;
    mSession = uri.getPath().substring(1);
    String host = uri.getHost();
    int port = uri.getPort();
    if (port == -1)
        port = JXServer.SERVER_PORT;

    // TODO: one connection per host (multiple subscriptions through one socket)
    // handle in Provider
    try {
        try {
            String my_ip = JunctionProvider.getLocalIpAddress();
            if (my_ip.equals(host)) {
                Log.d(TAG, "Starting local switchboard service");
                mSwitchboardServer = new JXServer();
                mSwitchboardServer.start();
            }
        } catch (Exception e) {
            Log.e(TAG, "Could not start local switchboard service", e);
        }

        Socket socket = new Socket(host, port);
        mConnectedThread = new ConnectedThread(socket);
        mConnectedThread.start();
    } catch (IOException e) {
        Log.e(TAG, "Error connecting to socket", e);
    }

    int MAX_TIME = 20000;
    synchronized (mJoinLock) {
        if (!mJoinComplete) {
            try {
                mJoinLock.wait(MAX_TIME);
            } catch (InterruptedException e) {
                // Ignored
            }
        }
    }
    if (!mJoinComplete) {
        throw new JunctionException("Timeout while joining Junction session.");
    }

    triggerActorJoin(mActivityCreator);
}

From source file:biocode.fims.ezid.EzidService.java

/**
 * Log into the EZID service using account credentials provided by EZID. The cookie
 * returned by EZID is cached in a local CookieStore for the duration of the EzidService,
 * and so subsequent calls using this instance of the service will function as
 * fully authenticated. An exception is thrown if authentication fails.
 *
 * @param username to identify the user account from EZID
 * @param password the secret password for this account
 *
 * @throws EzidException if authentication fails for any reason
 */// w w  w  .  j a va2  s .c  om
public void login(String username, String password) throws EzidException {
    String msg;
    try {
        URI serviceUri = new URI(LOGIN_SERVICE);
        HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.getScheme());
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        //System.out.println("authCache: " + authCache.toString());

        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
            public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };
        byte[] body = null;

        HttpGet httpget = new HttpGet(LOGIN_SERVICE);
        body = httpClient.execute(httpget, handler, localcontext);
        String message = new String(body);
        msg = parseIdentifierResponse(message);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        /*
                org.apache.http.client.CookieStore cookieStore = httpClient.getCookieStore();
        System.out.println("\n\nCookies : ");
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
        System.out.println("Cookie: " + cookies.get(i));
        } */

    } catch (URISyntaxException e) {
        //System.out.println("URI SyntaxError Exception in LOGIN");
        throw new EzidException("Bad syntax for uri: " + LOGIN_SERVICE, e);
    } catch (ClientProtocolException e) {
        //System.out.println("ClientProtocol Exception in LOGIN");
        throw new EzidException(e);
    } catch (IOException e) {
        //System.out.println("IO Exception in LOGIN");
        throw new EzidException(e);
    }
    //System.out.println("Seems to be a successful LOGIN, msg= " + msg.toString());
}

From source file:com.norconex.commons.lang.url.URLNormalizer.java

/**
 * Removes the default port (80 for http, and 443 for https).<p>
 * <code>http://www.example.com:80/bar.html &rarr; 
 *       http://www.example.com/bar.html</code>
 * @return this instance/*  w  w  w .  j a  va2s.  c om*/
 */
public URLNormalizer removeDefaultPort() {
    URI u = toURI(url);
    if ("http".equalsIgnoreCase(u.getScheme()) && u.getPort() == HttpURL.DEFAULT_HTTP_PORT) {
        url = url.replaceFirst(":" + HttpURL.DEFAULT_HTTP_PORT, "");
    } else if ("https".equalsIgnoreCase(u.getScheme()) && u.getPort() == HttpURL.DEFAULT_HTTPS_PORT) {
        url = url.replaceFirst(":" + HttpURL.DEFAULT_HTTPS_PORT, "");
    }
    return this;
}

From source file:com.abiquo.api.services.stub.TarantinoJobCreator.java

/**
 * Gets the configured DCHP in the datacenter to set its URL in the
 * {@link com.abiquo.commons.amqp.impl.tarantino.domain.VirtualMachineDefinition.NetworkConfiguration}
 *//*  w  w  w  .j  ava2  s . co m*/
private void addDhcpConfiguration(final Integer datacenterId, final VirtualMachineDescriptionBuilder vmDesc) {
    // TODO 2.0 will support manual DHCP configuration
    final RemoteService dhcp = remoteServiceService.getRemoteService(datacenterId,
            RemoteServiceType.DHCP_SERVICE);

    if (dhcp == null) {
        logger.debug("Tarantino Job Creator the datacenter id {} hasn't DHCP service");
        // The datacenter hasn't dhcp
        return;
    }
    try {
        final URI dhcpUri = new URI(dhcp.getUri());
        vmDesc.dhcp(dhcpUri.getHost(), dhcpUri.getPort());

    } catch (URISyntaxException e) {
        addConflictErrors(APIError.REMOTE_SERVICE_DHCP_WRONG_URI);
        flushErrors();
    }
}

From source file:com.mirth.connect.connectors.ws.WebServiceConnectorServlet.java

public URI getURIWithCredentials(URI wsdlUrl, String username, String password) throws URISyntaxException {
    /* add the username:password to the URL if using authentication */
    if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
        String hostWithCredentials = username + ":" + password + "@" + wsdlUrl.getHost();
        if (wsdlUrl.getPort() > -1) {
            hostWithCredentials += ":" + wsdlUrl.getPort();
        }/*w  w w.  j  a v  a2s  .co m*/
        wsdlUrl = new URI(wsdlUrl.getScheme(), hostWithCredentials, wsdlUrl.getPath(), wsdlUrl.getQuery(),
                wsdlUrl.getFragment());
    }

    return wsdlUrl;
}

From source file:de.tiqsolutions.hdfs.HadoopFileSystemProvider.java

private String getURIKey(URI uri) {
    String s = String.format("%s://%s@%s:%d", getScheme(), uri.getUserInfo() == null ? "" : uri.getUserInfo(),
            uri.getHost(), uri.getPort());
    try {/* w w w .j  a va2 s . c  om*/
        MessageDigest cript = MessageDigest.getInstance("SHA-1");
        cript.reset();
        cript.update(s.getBytes("utf8"));
        return new HexBinaryAdapter().marshal(cript.digest());
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
    }
    return null;

}

From source file:org.niord.core.keycloak.KeycloakUrlResolver.java

/**
 * This function has been copied (and modified) from the Keycloak AdapterDeploymentContext class.
 * It should be kept up-to-date with future versions of Keycloak.
 *//*from   w ww  . ja  v  a 2s .c o  m*/
private KeycloakUriBuilder getBaseBuilder(KeycloakDeployment deployment, HttpFacade.Request facadeRequest) {
    String base = deployment.getAuthServerBaseUrl();
    KeycloakUriBuilder builder = KeycloakUriBuilder.fromUri(base);
    URI request = URI.create(facadeRequest.getURI());
    String scheme = request.getScheme();
    if (deployment.getSslRequired().isRequired(facadeRequest.getRemoteAddr())) {
        scheme = "https";
        if (!request.getScheme().equals(scheme) && request.getPort() != -1) {
            throw new RuntimeException("Can't resolve relative url from adapter config.");
        }
    }
    builder.scheme(scheme);
    builder.host(request.getHost());
    if (request.getPort() != -1) {
        builder.port(request.getPort());
    }
    return builder;
}