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:org.wso2.carbon.http2.transport.util.Http2ConnectionFactory.java

/**
 * Generate hash-key for each clientHandler using uri
 *
 * @param uri/*from   w  w w.  j  av a  2s . c o  m*/
 * @return
 */
private String generateKey(URI uri) {
    String host = uri.getHost();
    int port = uri.getPort();
    String ssl;
    if (uri.getScheme().equalsIgnoreCase(Http2Constants.HTTPS2) || uri.getScheme().equalsIgnoreCase("https")) {
        ssl = "https://";
    } else
        ssl = "http://";
    return ssl + host + ":" + port;
}

From source file:org.mcxiaoke.commons.http.util.URIUtilsEx.java

/**
 * Extracts target host from the given {@link URI}.
 * //w ww  . j a v a2  s . c om
 * @param uri
 * @return the target host if the URI is absolute or
 *         <code>null</null> if the URI is
 * relative or does not contain a valid host name.
 * 
 * @since 4.1
 */
public static HttpHost extractHost(final URI uri) {
    if (uri == null) {
        return null;
    }
    HttpHost target = null;
    if (uri.isAbsolute()) {
        int port = uri.getPort(); // may be overridden later
        String host = uri.getHost();
        if (host == null) { // normal parse failed; let's do it ourselves
            // authority does not seem to care about the valid character-set
            // for host names
            host = uri.getAuthority();
            if (host != null) {
                // Strip off any leading user credentials
                int at = host.indexOf('@');
                if (at >= 0) {
                    if (host.length() > at + 1) {
                        host = host.substring(at + 1);
                    } else {
                        host = null; // @ on its own
                    }
                }
                // Extract the port suffix, if present
                if (host != null) {
                    int colon = host.indexOf(':');
                    if (colon >= 0) {
                        int pos = colon + 1;
                        int len = 0;
                        for (int i = pos; i < host.length(); i++) {
                            if (Character.isDigit(host.charAt(i))) {
                                len++;
                            } else {
                                break;
                            }
                        }
                        if (len > 0) {
                            try {
                                port = Integer.parseInt(host.substring(pos, pos + len));
                            } catch (NumberFormatException ex) {
                            }
                        }
                        host = host.substring(0, colon);
                    }
                }
            }
        }
        String scheme = uri.getScheme();
        if (host != null) {
            target = new HttpHost(host, port, scheme);
        }
    }
    return target;
}

From source file:com.adobe.acs.commons.replication.impl.AgentHostsImpl.java

@Override
public final List<String> getHosts(final AgentFilter agentFilter) {
    final List<String> hosts = new ArrayList<String>();
    final Map<String, Agent> agents = agentManager.getAgents();

    for (final Agent agent : agents.values()) {
        if (!agentFilter.isIncluded(agent)) {
            continue;
        }/*  www. jav a  2 s.c om*/

        try {
            final URI uri = new URI(agent.getConfiguration().getTransportURI());

            String tmp = StringUtils.defaultIfEmpty(uri.getScheme(), DEFAULT_SCHEME) + "://" + uri.getHost();
            if (uri.getPort() > 0) {
                tmp += ":" + uri.getPort();
            }

            hosts.add(tmp);
        } catch (URISyntaxException e) {
            log.error("Unable to extract a scheme/host/port from Agent transport URI [ {} ]",
                    agent.getConfiguration().getTransportURI());
        }
    }

    return hosts;
}

From source file:de.codecentric.boot.admin.discovery.DefaultServiceInstanceConverter.java

protected URI getManagementUrl(ServiceInstance instance) {
    String managamentPath = defaultIfEmpty(instance.getMetadata().get(KEY_MANAGEMENT_PATH),
            managementContextPath);//  w  w w .ja  va 2  s.c  o m
    managamentPath = stripStart(managamentPath, "/");

    URI serviceUrl = getServiceUrl(instance);
    String managamentPort = defaultIfEmpty(instance.getMetadata().get(KEY_MANAGEMENT_PORT),
            String.valueOf(serviceUrl.getPort()));

    return UriComponentsBuilder.fromUri(serviceUrl).port(managamentPort).pathSegment(managamentPath).build()
            .toUri();
}

From source file:edu.infsci2560.DatabaseConfig.java

@Bean
public BasicDataSource dataSource() throws URISyntaxException {
    URI dbUri = new URI(System.getenv("DATABASE_URL"));

    String username = dbUri.getUserInfo().split(":")[0];
    String password = dbUri.getUserInfo().split(":")[1];
    String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath()
            + "?sslmode=require";

    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setUrl(dbUrl);//from   w w w  .ja v  a2  s  .  c  o m
    basicDataSource.setUsername(username);
    basicDataSource.setPassword(password);

    return basicDataSource;
}

From source file:org.fishwife.jrugged.httpclient.PerHostServiceWrappedHttpClient.java

private HttpHost getCanonicalHost(HttpHost host) {
    URI uri;
    try {/*from   www  . jav  a2  s.c om*/
        uri = new URI(host.toURI());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    String hostname = uri.getHost();
    int port = uri.getPort();
    String scheme = uri.getScheme();
    boolean isHttps = "HTTPS".equalsIgnoreCase(scheme);
    String schemePart = isHttps ? (scheme + "://") : "";
    if (port == -1) {
        port = isHttps ? 443 : 80;
    }
    return new HttpHost(schemePart + hostname + ":" + port);
}

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;
    }/*from ww w . j av  a 2  s  . 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.smartitengineering.cms.ws.resources.workspace.WorkspaceFriendliesResource.java

protected WorkspaceResource getWorkspaceResource(final String uri)
        throws IllegalArgumentException, ContainerException, ClassCastException, UriBuilderException {
    final URI checkUri;
    if (uri.startsWith("http:")) {
        checkUri = URI.create(uri);
    } else {// w ww .ja  v a  2  s  .co  m
        URI absUri = getAbsoluteURIBuilder().build();
        checkUri = UriBuilder.fromPath(uri).host(absUri.getHost()).port(absUri.getPort())
                .scheme(absUri.getScheme()).build();
    }
    WorkspaceResource resource = getResourceContext().matchResource(checkUri, WorkspaceResource.class);
    return resource;
}

From source file:com.yahoo.gondola.container.LocalTestRoutingServer.java

public LocalTestRoutingServer(Gondola gondola, RoutingHelper routingHelper,
        ProxyClientProvider proxyClientProvider, Map<String, RoutingService> services,
        ChangeLogProcessor changeLogProcessor) throws Exception {
    routingFilter = new RoutingFilter(gondola, routingHelper, proxyClientProvider, services,
            changeLogProcessor);//from   w  w w  .  ja  v  a2s.c  o  m
    routingFilter.start();
    localTestServer = new LocalTestServer((request, response, context) -> {
        try {
            URI requestUri = URI.create(request.getRequestLine().getUri());
            URI baseUri = URI
                    .create(requestUri.getScheme() + "://" + requestUri.getHost() + ":" + requestUri.getPort());
            ContainerRequest containerRequest = new ContainerRequest(baseUri, requestUri,
                    request.getRequestLine().getMethod(), null, new MapPropertiesDelegate());
            routingFilter.filter(containerRequest);

            Response abortResponse = containerRequest.getAbortResponse();
            Response jaxrsResponse;
            if (abortResponse != null) {
                jaxrsResponse = abortResponse;
            } else {
                jaxrsResponse = new OutboundJaxrsResponse.Builder(null).status(200).build();
            }

            ContainerResponse containerResponse = new ContainerResponse(containerRequest, jaxrsResponse);
            routingFilter.filter(containerRequest, containerResponse);
            response.setStatusCode(containerResponse.getStatus());
            response.setEntity(new StringEntity(containerResponse.getEntity().toString()));

            Set<Map.Entry<String, List<Object>>> entries = containerResponse.getHeaders().entrySet();
            for (Map.Entry<String, List<Object>> e : entries) {
                String headerName = e.getKey();
                for (Object o : e.getValue()) {
                    String headerValue = o.toString();
                    response.setHeader(headerName, headerValue);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    });
    host = localTestServer.start();
}

From source file:com.mirth.connect.connectors.file.FileConnectorServlet.java

protected ConnectionTestResponse testReadOrWrite(String channelId, String channelName, String host,
        String username, String password, SchemeProperties schemeProperties, FileScheme scheme,
        String timeoutString, boolean secure, boolean passive, boolean read) {
    try {// w  ww.  jav a 2s  .c o m
        host = replacer.replaceValues(host, channelId, channelName);
        username = replacer.replaceValues(username, channelId, channelName);
        password = replacer.replaceValues(password, channelId, channelName);

        SftpSchemeProperties sftpProperties = null;
        if (schemeProperties instanceof SftpSchemeProperties) {
            sftpProperties = (SftpSchemeProperties) schemeProperties;

            sftpProperties
                    .setKeyFile(replacer.replaceValues(sftpProperties.getKeyFile(), channelId, channelName));
            sftpProperties.setPassPhrase(
                    replacer.replaceValues(sftpProperties.getPassPhrase(), channelId, channelName));
            sftpProperties.setKnownHostsFile(
                    replacer.replaceValues(sftpProperties.getKnownHostsFile(), channelId, channelName));
            sftpProperties.setConfigurationSettings(
                    replacer.replaceValues(sftpProperties.getConfigurationSettings(), channelId, channelName));
        }

        int timeout = Integer.parseInt(timeoutString);

        URI address = FileConnector.getEndpointURI(host, scheme, secure);
        String addressHost = address.getHost();
        int port = address.getPort();
        String dir = address.getPath();

        String hostDisplayName = "";
        if (!scheme.equals(FileScheme.FILE)) {
            hostDisplayName = scheme.getDisplayName() + "://" + address.getHost();
        }
        hostDisplayName += dir;

        FileSystemConnectionFactory factory = new FileSystemConnectionFactory(scheme,
                new FileSystemConnectionOptions(username, password, sftpProperties), addressHost, port, passive,
                secure, timeout);

        FileSystemConnection connection = null;

        try {
            connection = ((PooledObject<FileSystemConnection>) factory.makeObject()).getObject();

            if (read && connection.canRead(dir) || !read && connection.canWrite(dir)) {
                return new ConnectionTestResponse(ConnectionTestResponse.Type.SUCCESS,
                        "Successfully connected to: " + hostDisplayName);
            } else {
                return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE,
                        "Unable to connect to: " + hostDisplayName);
            }
        } catch (Exception e) {
            return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE,
                    "Unable to connect to: " + hostDisplayName + ", Reason: " + e.getMessage());
        } finally {
            if (connection != null) {
                connection.destroy();
            }
        }
    } catch (Exception e) {
        throw new MirthApiException(e);
    }
}