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:kuona.client.JenkinsHttpClient.java

/**
 * Create an authenticated Jenkins HTTP client
 *
 * @param uri      Location of the jenkins server (ex. http://localhost:8080)
 * @param username Username to use when connecting
 * @param password Password or auth token to use when connecting
 *///from ww  w  .j  a v  a  2  s .  com
public JenkinsHttpClient(Project project, URI uri, String username, String password) {
    this(project, uri);
    if (isNotBlank(username)) {
        CredentialsProvider provider = client.getCredentialsProvider();
        AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), "realm");
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(scope, credentials);

        localContext = new BasicHttpContext();
        localContext.setAttribute("preemptive-auth", new BasicScheme());
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
    }
}

From source file:chat.viska.xmpp.Connection.java

/**
 * Constructs a {@link Connection} with a full server URI. Convenient method
 * of {@link #Connection(Protocol, String, String, int, String)}.
 *//* w  ww.  ja v a 2s  . c om*/
public Connection(final Protocol protocol, final URI uri) {
    this(protocol, uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath());
}

From source file:org.attribyte.api.pubsub.impl.server.NotificationMetricsServlet.java

/**
 * Gets a metrics prefix for a topic.// w ww.  j a v a2 s.com
 * @param topicId The topic id.
 * @param joinString The string used to join parts of the topic URI.
 * @param allowSlash Is '/' allowed in the prefix?
 * @return The prefix.
 */
private String getTopicPrefix(final long topicId, final String joinString, final boolean allowSlash) {
    try {
        Topic topic = endpoint.getDatastore().getTopic(topicId);
        if (topic != null) {
            URI uri = new URI(topic.getURL());
            List<String> components = Lists.newArrayListWithCapacity(4);
            if (uri.getHost() != null)
                components.add(uri.getHost());
            if (uri.getPort() > 0)
                components.add(Integer.toString(uri.getPort()));
            String path = uri.getPath();
            if (path != null) {
                if (path.startsWith("/"))
                    path = path.substring(1);
                if (path.endsWith("/"))
                    path = path.substring(0, path.length() - 1);
                components.add(path);
            }
            String prefix = Joiner.on(joinString).skipNulls().join(components);
            if (!allowSlash)
                prefix = prefix.replace('/', '_');
            return prefix;
        } else {
            return null;
        }
    } catch (DatastoreException de) {
        log("Unable to resolve topic", de);
        return null;
    } catch (URISyntaxException use) {
        return null;
    }
}

From source file:com.jrodeo.remote.TestHttpCore.java

Stats execute(final URI target, final byte[] content, int n, int c) throws Exception {
    this.pool.setMaxTotal(2000);
    this.pool.setDefaultMaxPerRoute(c);
    HttpHost targetHost = new HttpHost(target.getHost(), target.getPort());
    StringBuilder buffer = new StringBuilder();
    buffer.append(target.getPath());/*from w w w . j ava 2s  .  co  m*/
    if (target.getQuery() != null) {
        buffer.append("?");
        buffer.append(target.getQuery());
    }
    String requestUri = buffer.toString();

    Stats stats = new Stats(n, c);
    WorkerThread[] workers = new WorkerThread[c];
    for (int i = 0; i < workers.length; i++) {
        workers[i] = new WorkerThread(stats, targetHost, requestUri, content);
    }
    for (int i = 0; i < workers.length; i++) {
        workers[i].start();
    }
    for (int i = 0; i < workers.length; i++) {
        workers[i].join();
    }
    return stats;
}

From source file:com.whizzosoftware.hobson.rest.v1.resource.device.MediaProxyResource.java

protected HttpProps createHttpGet(String varValue) throws ParseException, URISyntaxException {
    URIInfo uriInfo = URLVariableParser.parse(varValue);
    HttpGet get = new HttpGet(uriInfo.getURI());

    // populate the GET request with headers if specified
    if (uriInfo.hasHeaders()) {
        Map<String, String> headers = uriInfo.getHeaders();
        for (String name : headers.keySet()) {
            uriInfo.addHeader(name, headers.get(name));
        }//from   w  ww  .  j  a v a 2  s .  c om
    }

    CloseableHttpClient httpClient;

    // populate the GET request with auth information if specified
    if (uriInfo.hasAuthInfo()) {
        URI uri = uriInfo.getURI();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(uri.getHost(), (uri.getPort() > 0) ? uri.getPort() : DEFAULT_REALM_PORT),
                new UsernamePasswordCredentials(uriInfo.getAuthInfo().getUsername(),
                        uriInfo.getAuthInfo().getPassword()));
        httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    } else {
        httpClient = HttpClients.createDefault();
    }

    return new HttpProps(httpClient, get);
}

From source file:com.abiquo.abiserver.pojo.service.RemoteService.java

/**
 * Sets the uri.//from ww  w  .j a  va  2 s .  c  o  m
 * 
 * @param uri the new uri
 */
public void setUri(final String uri) {
    this.uri = uri;
    URI u = URI.create(uri);

    this.protocol = fixProtocol(u.getScheme());
    this.domainName = u.getHost();
    this.port = u.getPort();
    if (port == -1) {
        port = 80;
    }
    this.serviceMapping = u.getPath();
    if (serviceMapping.startsWith("/")) {
        serviceMapping = serviceMapping.replaceFirst("/", "");
    }
}

From source file:eionet.cr.util.virtuoso.VirtuosoJdbcDriverTest.java

/**
 * Test if CR uses correct Virtuoso JDBC driver. It shouldn't get "Too many open statements" error.
 *
 * @throws SQLException When problem with connecting to Virtuoso.
 *//*from   w ww.  ja  va2s  . c  om*/
@Test
public void testTooManyOpenStmts() throws SQLException {

    VirtuosoConnectionPoolDataSource dbsource = new VirtuosoConnectionPoolDataSource();

    String testDbURI = GeneralConfig.getRequiredProperty(GeneralConfig.VIRTUOSO_DB_URL);
    URI uri = URI.create(testDbURI.substring(5));

    dbsource.setServerName(uri.getHost());
    dbsource.setPortNumber(uri.getPort());
    dbsource.setPassword(GeneralConfig.getRequiredProperty(GeneralConfig.VIRTUOSO_DB_PWD));
    dbsource.setUser(GeneralConfig.getRequiredProperty(GeneralConfig.VIRTUOSO_DB_USR));
    dbsource.setCharset("UTF-8");
    VirtuosoPooledConnection pooledConnection = (VirtuosoPooledConnection) dbsource.getPooledConnection();
    virtuoso.jdbc4.VirtuosoConnection con = pooledConnection.getVirtuosoConnection();
    String jdbcComp = "DB.DBA.TTLP (?, ?, ?, ?)";
    CallableStatement stmt = null;
    int MAXIT = 10000;
    for (int i = 0; i < MAXIT; i++) {
        try {
            stmt = con.prepareCall(jdbcComp);
            stmt.setString(1, "");
            stmt.setString(2, "");
            stmt.setString(3, DUMMY_GRAPH_URI);
            stmt.setInt(4, 256);
            stmt.execute();
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            fail("can't add data to virtuoso. ");
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }
    }
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.Geoserver.java

/**
 * This method creates a new DataStore in the established workspace 
 * with the specified name and using the data from the entity table
 *
 * @param workspace the workspace name where the data store will be created
 * @param datastoreName the name of the new data store
 * @param schema schema to use to create the data store
 * /*from  w w w .  j a va2 s  .c o m*/
 * @return true if the data store was created successfully
 * 
 * @throws MalformedURLException thrown if the data base URL is not valid
 */
public boolean createDataStore(String workspace, String datastoreName, Schema schema)
        throws MalformedURLException {
    boolean createdDatastore = false;

    if (StringUtils.isEmpty(workspace) || StringUtils.isEmpty(datastoreName) || (schema == null)) {
        throw new IllegalArgumentException("No se han especificado todos los parmetros necesarios");
    }
    // gets datastore params
    DataBase database = schema.getDataBase();
    String connectionUrlString = database.getConnectionUrl();
    connectionUrlString = connectionUrlString.substring(5);

    //TODO: pillar el nombre de la url de conexion http......./nombd y ponerlo en el campo databaseName

    URI connectionUri = URI.create(connectionUrlString);
    String host = connectionUri.getHost();
    int port = connectionUri.getPort();
    //String databaseName = database.getAlias();
    String databaseName = getNameByUrlConecction(connectionUrlString);
    String schemaName = schema.getName();
    String user = schema.getUser();
    String password = schema.getPassword();
    boolean validateConnections = true;
    boolean enabled = true;

    // creates store
    GSPostGISDatastoreEncoder store = new GSPostGISDatastoreEncoder(datastoreName);
    store.setHost(host);
    store.setPort(port);
    store.setDatabase(databaseName);
    store.setSchema(schemaName);
    store.setUser(user);
    store.setPassword(password);
    store.setEnabled(enabled);
    store.setValidateConnections(validateConnections);

    // uses the API REST
    createdDatastore = gsManager.getStoreManager().create(workspace, store);

    return createdDatastore;
}

From source file:cn.ctyun.amazonaws.http.HttpRequestFactory.java

/** Configures the headers in the specified Apache HTTP request. */
private void configureHeaders(HttpRequestBase httpRequest, Request<?> request, ExecutionContext context,
        ClientConfiguration clientConfiguration) {
    /*//from   w  w w.  j  av a  2s  . com
     * Apache HttpClient omits the port number in the Host header (even if
     * we explicitly specify it) if it's the default port for the protocol
     * in use. To ensure that we use the same Host header in the request and
     * in the calculated string to sign (even if Apache HttpClient changed
     * and started honoring our explicit host with endpoint), we follow this
     * same behavior here and in the QueryString signer.
     */
    URI endpoint = request.getEndpoint();
    String hostHeader = endpoint.getHost();
    if (HttpUtils.isUsingNonDefaultPort(endpoint)) {
        hostHeader += ":" + endpoint.getPort();
    }
    httpRequest.addHeader("Host", hostHeader);

    // Copy over any other headers already in our request
    for (Entry<String, String> entry : request.getHeaders().entrySet()) {
        /*
         * HttpClient4 fills in the Content-Length header and complains if
         * it's already present, so we skip it here. We also skip the Host
         * header to avoid sending it twice, which will interfere with some
         * signing schemes.
         */
        if (entry.getKey().equalsIgnoreCase("Content-Length") || entry.getKey().equalsIgnoreCase("Host"))
            continue;

        httpRequest.addHeader(entry.getKey(), entry.getValue());
    }

    /* Set content type and encoding */
    if (httpRequest.getHeaders("Content-Type") == null || httpRequest.getHeaders("Content-Type").length == 0) {
        httpRequest.addHeader("Content-Type",
                "application/x-www-form-urlencoded; " + "charset=" + DEFAULT_ENCODING.toLowerCase());
    }

    // Override the user agent string specified in the client params if the context requires it
    if (context != null && context.getContextUserAgent() != null) {
        httpRequest.addHeader("User-Agent",
                createUserAgentString(clientConfiguration, context.getContextUserAgent()));
    }
}

From source file:org.apache.brooklyn.launcher.BrooklynLauncherTest.java

@Test(groups = "Integration")
public void testStartsWebServerOnExpectectedPort() throws Exception {
    launcher = newLauncherForTests(true).webconsolePort("10000+").installSecurityFilter(false).start();

    String webServerUrlStr = launcher.getServerDetails().getWebServerUrl();
    URI webServerUri = new URI(webServerUrlStr);

    assertEquals(launcher.getApplications(), ImmutableList.of());
    assertTrue(webServerUri.getPort() >= 10000 && webServerUri.getPort() < 10100,
            "port=" + webServerUri.getPort() + "; uri=" + webServerUri);
    HttpAsserts.assertUrlReachable(webServerUrlStr);
}