Example usage for java.net URI getHost

List of usage examples for java.net URI getHost

Introduction

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

Prototype

public String getHost() 

Source Link

Document

Returns the host component of this URI.

Usage

From source file:com.springsource.insight.plugin.ldap.LdapOperationCollectionAspectTestSupport.java

protected static final Collection<ExternalResourceDescriptor> assertExternalResourceAnalysis(String testName,
        Operation op, String ldapUrl) throws URISyntaxException {
    Frame frame = new SimpleFrame(FrameId.valueOf("0"), null, op, TimeRange.FULL_RANGE,
            Collections.<Frame>emptyList());
    Trace trace = new Trace(ServerName.valueOf("fake-server"), ApplicationName.valueOf("fake-app"),
            new Date(System.currentTimeMillis()), TraceId.valueOf("0"), frame);
    Collection<ExternalResourceDescriptor> result = analyzer.locateExternalResourceName(trace);
    assertNotNull(testName + ": No external resources recovered", result);
    assertEquals(testName + ": Mismatched number of results", 1, result.size());

    ExternalResourceDescriptor desc = result.iterator().next();
    assertSame(testName + ": Mismatched result frame", frame, desc.getFrame());
    assertEquals(testName + ": Mismathed name", MD5NameGenerator.getName(ldapUrl), desc.getName());
    assertEquals(testName + ": Mismatched vendor", ldapUrl, desc.getVendor());
    assertEquals(testName + ": Mismatched label", ldapUrl, desc.getLabel());
    assertEquals(testName + ": Mismatched type", ExternalResourceType.LDAP.name(), desc.getType());

    URI uri = new URI(ldapUrl);
    assertEquals(testName + ": Mismatched host", uri.getHost(), desc.getHost());
    assertEquals(testName + ": Mismatched port", LdapExternalResourceAnalyzer.resolvePort(uri), desc.getPort());
    return result;
}

From source file:net.adamcin.recap.replication.RecapReplicationUtil.java

/**
 * Builds a RecapAddress from related properties of the provided AgentConfig
 * @param config//from   ww  w  .  j  a  v a  2s .c  om
 * @return
 * @throws com.day.cq.replication.ReplicationException
 */
public static RecapAddress getAgentAddress(AgentConfig config) throws ReplicationException {

    final String uri = config.getTransportURI();

    if (!uri.startsWith(TRANSPORT_URI_SCHEME_PREFIX)) {
        throw new ReplicationException("uri must start with " + TRANSPORT_URI_SCHEME_PREFIX);
    }

    final String user = config.getTransportUser();
    final String pass = config.getTransportPassword();

    try {

        final URI parsed = new URI(uri.substring(TRANSPORT_URI_SCHEME_PREFIX.length()));
        final boolean https = "https".equals(parsed.getScheme());
        final String host = parsed.getHost();
        final int port = parsed.getPort() < 0 ? (https ? 443 : 80) : parsed.getPort();
        final String prefix = StringUtils.isEmpty(parsed.getPath()) ? null : parsed.getPath();

        return new DefaultRecapAddress() {
            @Override
            public boolean isHttps() {
                return https;
            }

            @Override
            public String getHostname() {
                return host;
            }

            @Override
            public Integer getPort() {
                return port;
            }

            @Override
            public String getUsername() {
                return user;
            }

            @Override
            public String getPassword() {
                return pass;
            }

            @Override
            public String getServletPath() {
                return prefix;
            }
        };
    } catch (URISyntaxException e) {
        throw new ReplicationException(e);
    }
}

From source file:com.google.caja.precajole.StaticPrecajoleMap.java

public static String normalizeUri(String uri) {
    try {//from   w w  w  .  j av a2  s  .  c  o  m
        URI u = new URI(uri).normalize();
        if (u.getHost() != null) {
            u = new URI(lowercase(u.getScheme()), u.getUserInfo(), lowercase(u.getHost()), u.getPort(),
                    u.getPath(), u.getQuery(), u.getFragment());
        } else if (u.getScheme() != null) {
            u = new URI(lowercase(u.getScheme()), u.getSchemeSpecificPart(), u.getFragment());
        }
        return u.toString();
    } catch (URISyntaxException e) {
        return uri;
    }
}

From source file:io.syndesis.rest.v1.handler.credential.CredentialHandler.java

static URI addFragmentTo(final URI uri, final CallbackStatus status) {
    try {//w ww  . j a v a2  s.c om
        final String fragment = SERIALIZER.writeValueAsString(status);

        return new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(),
                fragment);
    } catch (JsonProcessingException | URISyntaxException e) {
        throw new IllegalStateException("Unable to add fragment to URI: " + uri + ", for state: " + status, e);
    }
}

From source file:org.graylog2.alarmcallbacks.hipchat.HipChatTrigger.java

public static String buildStreamDetailsURL(URI baseUri, AlertCondition.CheckResult checkResult, Stream stream)
        throws AlarmCallbackException {
    if (baseUri != null && !Strings.isNullOrEmpty(baseUri.getHost())) {
        int time = 5;
        if (checkResult.getTriggeredCondition().getParameters().get("time") != null) {
            time = ((Integer) checkResult.getTriggeredCondition().getParameters().get("time")).intValue();
        }//from  w w w  .  ja  v  a2s  . c o m
        DateTime dateAlertEnd = checkResult.getTriggeredAt();
        DateTime dateAlertStart = dateAlertEnd.minusMinutes(time);
        String alertStart = Tools.getISO8601String(dateAlertStart);
        String alertEnd = Tools.getISO8601String(dateAlertEnd);
        return baseUri + "/streams/" + stream.getId() + "/messages?rangetype=absolute&from=" + alertStart
                + "&to=" + alertEnd + "&q=*";
    } else {
        throw new AlarmCallbackException(
                "Please configure a valid Graylog Base URL in the alarm callback parameters.");
    }
}

From source file:com.ibm.watson.developer_cloud.retrieve_and_rank.RetrieveAndRankSolrJExample.java

private static HttpClient createHttpClient(String uri, String username, String password) {
    final URI scopeUri = URI.create(uri);

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()),
            new UsernamePasswordCredentials(username, password));

    final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(//from  ww  w  .ja  v  a2 s . co  m
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build())
            .setDefaultCredentialsProvider(credentialsProvider)
            .addInterceptorFirst(new PreemptiveAuthInterceptor());
    return builder.build();
}

From source file:com.github.wolf480pl.mias4j.util.AbstractTransformingClassLoader.java

public static URL guessCodeSourceURL(String resourcePath, URL resourceURL) {
    // FIXME: Find a better way to do this
    @SuppressWarnings("restriction")
    String escaped = sun.net.www.ParseUtil.encodePath(resourcePath, false);
    String path = resourceURL.getPath();
    if (!path.endsWith(escaped)) {
        // Umm... whadda we do now? Maybe let's fallback to full resource URL.
        LOG.warn("Resource URL path \"" + path + "\" doesn't end with escaped resource path \"" + escaped
                + "\" for resource \"" + resourcePath + "\"");
        return resourceURL;
    }/*  www.j  a v  a 2  s.  co  m*/
    path = path.substring(0, path.length() - escaped.length());
    if (path.endsWith("!/")) { // JAR
        path = path.substring(0, path.length() - 2);
    }
    try {
        URI uri = resourceURL.toURI();
        return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), path, uri.getQuery(),
                uri.getFragment()).toURL();
    } catch (MalformedURLException | URISyntaxException e) {
        // Umm... whadda we do now? Maybe let's fallback to full resource URL.
        LOG.warn("Couldn't assemble CodeSource URL with modified path", e);
        return resourceURL;
    }
}

From source file:org.gytheio.messaging.amqp.AmqpNodeBootstrapUtils.java

/**
 * Creates an AMQP endpoint (sender and receiver) from the given arguments
 * /*  w ww  .j a  v a  2 s  . c o m*/
 * @param messageConsumer the processor received messages are sent to
 * @param args
 * @return
 */
public static AmqpDirectEndpoint createEndpoint(MessageConsumer messageConsumer, String brokerUrl,
        String brokerUsername, String brokerPassword, String requestEndpoint, String replyEndpoint) {
    validate(brokerUrl, requestEndpoint, replyEndpoint);

    AmqpDirectEndpoint messageProducer = new AmqpDirectEndpoint();
    ObjectMapper objectMapper = ObjectMapperFactory.createInstance();

    URI broker = null;
    try {
        broker = new URI(brokerUrl);
    } catch (URISyntaxException e) {
        // This would have been caught by validation above
    }

    ((AmqpDirectEndpoint) messageProducer).setHost(broker.getHost());
    Integer brokerPort = broker.getPort();
    if (brokerPort != null) {
        ((AmqpDirectEndpoint) messageProducer).setPort(brokerPort);
    }
    if (brokerUsername != null) {
        ((AmqpDirectEndpoint) messageProducer).setUsername(brokerUsername);
    }
    if (brokerPassword != null) {
        ((AmqpDirectEndpoint) messageProducer).setPassword(brokerPassword);
    }
    ((AmqpDirectEndpoint) messageProducer).setReceiveEndpoint(requestEndpoint);
    ((AmqpDirectEndpoint) messageProducer).setSendEndpoint(replyEndpoint);

    ((AmqpDirectEndpoint) messageProducer).setMessageConsumer(messageConsumer);
    ((AmqpDirectEndpoint) messageProducer).setObjectMapper(objectMapper);

    return messageProducer;
}

From source file:com.ibm.jaggr.core.impl.deps.DepUtils.java

/**
 * Removes URIs containing duplicate and non-orthogonal paths so that the
 * collection contains only unique and non-overlapping paths.
 *
 * @param uris collection of URIs//  ww  w  . j  ava2  s  .c om
 *
 * @return a new collection with redundant paths removed
 */
static public Collection<URI> removeRedundantPaths(Collection<URI> uris) {
    List<URI> result = new ArrayList<URI>();
    for (URI uri : uris) {
        String path = uri.getPath();
        if (!path.endsWith("/")) { //$NON-NLS-1$
            path += "/"; //$NON-NLS-1$
        }
        boolean addIt = true;
        for (int i = 0; i < result.size(); i++) {
            URI testUri = result.get(i);
            if (!StringUtils.equals(testUri.getScheme(), uri.getScheme())
                    || !StringUtils.equals(testUri.getHost(), uri.getHost())
                    || testUri.getPort() != uri.getPort()) {
                continue;
            }
            String test = testUri.getPath();
            if (!test.endsWith("/")) { //$NON-NLS-1$
                test += "/"; //$NON-NLS-1$
            }
            if (path.equals(test) || path.startsWith(test)) {
                addIt = false;
                break;
            } else if (test.startsWith(path)) {
                result.remove(i);
            }
        }
        if (addIt)
            result.add(uri);
    }
    // Now copy the trimmed list back to the original
    return result;
}

From source file:io.lavagna.config.DataSourceConfig.java

/**
 * for supporting heroku style url://from   w ww.  jav a  2  s. com
 *
 * <pre>
 * [database type]://[username]:[password]@[host]:[port]/[database name]
 * </pre>
 *
 * @param dataSource
 * @param env
 * @throws URISyntaxException
 */
private static void urlWithCredentials(HikariDataSource dataSource, Environment env) throws URISyntaxException {
    URI dbUri = new URI(env.getRequiredProperty("datasource.url"));
    dataSource.setUsername(dbUri.getUserInfo().split(":")[0]);
    dataSource.setPassword(dbUri.getUserInfo().split(":")[1]);
    dataSource.setJdbcUrl(
            String.format("%s://%s:%s%s", scheme(dbUri), dbUri.getHost(), dbUri.getPort(), dbUri.getPath()));
}