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:Main.java

/**
 * Parse the URI and use the details to connect to the IMAP(S) server and login.
 *
 * @param uri the URI to use, e.g. imaps://user:pass@imap.mail.yahoo.com/folder
 * or imaps://user:pass@imap.googlemail.com/folder
 * @param defaultTimeout initial timeout (in milliseconds)
 * @param listener for tracing protocol IO (may be null)
 * @return the IMAP client - connected and logged in
 * @throws IOException if any problems occur
 *//*from  ww  w  .j a  va  2  s .  c om*/
static IMAPClient imapLogin(URI uri, int defaultTimeout, ProtocolCommandListener listener) throws IOException {
    final String userInfo = uri.getUserInfo();
    if (userInfo == null) {
        throw new IllegalArgumentException("Missing userInfo details");
    }

    String[] userpass = userInfo.split(":");
    if (userpass.length != 2) {
        throw new IllegalArgumentException("Invalid userInfo details: '" + userpass + "'");
    }

    String username = userpass[0];
    String password = userpass[1]; // TODO enable reading this secretly

    final IMAPClient imap;

    final String scheme = uri.getScheme();
    if ("imaps".equalsIgnoreCase(scheme)) {
        System.out.println("Using secure protocol");
        imap = new IMAPSClient(true); // implicit
    } else if ("imap".equalsIgnoreCase(scheme)) {
        imap = new IMAPClient();
    } else {
        throw new IllegalArgumentException("Invalid protocol: " + scheme);
    }
    final int port = uri.getPort();
    if (port != -1) {
        imap.setDefaultPort(port);
    }

    imap.setDefaultTimeout(defaultTimeout);

    if (listener != null) {
        imap.addProtocolCommandListener(listener);
    }

    final String server = uri.getHost();
    System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());

    try {
        imap.connect(server);
        System.out.println("Successfully connected");
    } catch (IOException e) {
        throw new RuntimeException("Could not connect to server.", e);
    }

    if (!imap.login(username, password)) {
        imap.disconnect();
        throw new RuntimeException("Could not login to server. Check login details.");
    }

    return imap;
}

From source file:com.github.brandtg.pantopod.crawler.CrawlingEventHandler.java

private URI getNextUri(URI url, String href, String chroot) throws Exception {
    //    if (href.contains("..")) {
    ////from w  ww.j ava2 s .  co  m
    //      throw new IllegalArgumentException("Relative URI not allowed: " + href);
    //    }

    URI hrefUri = URI.create(href.trim().replaceAll(" ", "+"));

    URIBuilder builder = new URIBuilder();

    builder.setScheme(hrefUri.getScheme() == null ? url.getScheme() : hrefUri.getScheme());
    builder.setHost(hrefUri.getHost() == null ? url.getHost() : hrefUri.getHost());
    builder.setPort(hrefUri.getPort() == -1 ? url.getPort() : hrefUri.getPort());

    if (hrefUri.getPath() != null) {
        StringBuilder path = new StringBuilder();
        if (hrefUri.getHost() == null && chroot != null) {
            path.append(chroot);
        }

        // Ensure no two slashes
        if (hrefUri.getPath() != null && hrefUri.getPath().length() > 0 && hrefUri.getPath().charAt(0) == '/'
                && path.length() > 0 && path.charAt(path.length() - 1) == '/') {
            path.setLength(path.length() - 1);
        }

        path.append(hrefUri.getPath());

        builder.setPath(chroot == null ? "" : chroot + hrefUri.getPath());
    }
    if (hrefUri.getQuery() != null) {
        builder.setCustomQuery(hrefUri.getQuery());
    }
    if (hrefUri.getFragment() != null) {
        builder.setFragment(hrefUri.getFragment());
    }

    return builder.build();
}

From source file:io.wcm.maven.plugins.contentpackage.AbstractContentPackageMojo.java

/**
 * Set up http client with credentials/* ww  w  . j a  va  2  s  . c om*/
 * @return Http client
 * @throws MojoExecutionException Mojo execution exception
 */
protected final CloseableHttpClient getHttpClient() throws MojoExecutionException {
    try {
        URI crxUri = new URI(getCrxPackageManagerUrl());

        final AuthScope authScope = new AuthScope(crxUri.getHost(), crxUri.getPort());
        final Credentials credentials = new UsernamePasswordCredentials(this.userId, this.password);
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(authScope, credentials);

        HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .addInterceptorFirst(new HttpRequestInterceptor() {
                    @Override
                    public void process(HttpRequest request, HttpContext context)
                            throws HttpException, IOException {
                        // enable preemptive authentication
                        AuthState authState = (AuthState) context
                                .getAttribute(HttpClientContext.TARGET_AUTH_STATE);
                        authState.update(new BasicScheme(), credentials);
                    }
                });

        if (this.relaxedSSLCheck) {
            SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    new NoopHostnameVerifier());
            httpClientBuilder.setSSLSocketFactory(sslsf);
        }

        return httpClientBuilder.build();
    } catch (URISyntaxException ex) {
        throw new MojoExecutionException("Invalid url: " + getCrxPackageManagerUrl(), ex);
    } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException ex) {
        throw new MojoExecutionException("Could not set relaxedSSLCheck", ex);
    }
}

From source file:com.qwazr.utils.json.client.JsonClientAbstract.java

protected JsonClientAbstract(String url, Integer msTimeOut, Credentials credentials) throws URISyntaxException {
    this.url = url;
    URI u = new URI(url);
    String path = u.getPath();/*from  www  .j a va  2  s . co  m*/
    if (path != null && path.endsWith("/"))
        u = new URI(u.getScheme(), null, u.getHost(), u.getPort(), path.substring(0, path.length() - 1),
                u.getQuery(), u.getFragment());
    this.scheme = u.getScheme() == null ? "http" : u.getScheme();
    this.host = u.getHost();
    this.fragment = u.getFragment();
    this.path = u.getPath();
    this.port = u.getPort() == -1 ? 80 : u.getPort();
    this.timeout = msTimeOut == null ? DEFAULT_TIMEOUT : msTimeOut;
    this.executor = credentials == null ? Executor.newInstance() : Executor.newInstance().auth(credentials);

}

From source file:com.navercorp.pinpoint.plugin.httpclient4.interceptor.HttpClientExecuteMethodWithHttpUriRequestInterceptor.java

/**
 * copy/* ww w .  java  2 s  .c om*/
 * org.apache.http.client.utils.URIUtils#extractHost(java.net.URI)
 * @param uri
 * @return
 */
private NameIntValuePair<String> extractHost(final URI uri) {
    if (uri == null) {
        return null;
    }
    NameIntValuePair<String> 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 ignore) {
                                // skip
                            }
                        }
                        host = host.substring(0, colon);
                    }
                }
            }
        }
        if (host != null) {
            target = new NameIntValuePair<String>(host, port);
        }
    }
    return target;
}

From source file:com.brightcove.com.uploader.helper.MediaManagerHelper.java

public Long uploadFile(URI uri, File f, DefaultHttpClient client)
        throws HttpException, IOException, URISyntaxException, ParserConfigurationException, SAXException {
    mLog.info("using " + uri.getHost() + " on port " + uri.getPort() + " for MM upload");

    HttpPost method = new HttpPost(uri);
    MultipartEntity entityIn = new MultipartEntity();
    entityIn.addPart("FileName", new StringBody(f.getName(), Charset.forName("UTF-8")));

    FileBody fileBody = null;//www  . j a va  2 s .c o m

    if (f != null) {
        fileBody = new FileBody(f);
    }

    if (f != null) {
        entityIn.addPart(f.getName(), fileBody);
    }

    entityIn.addPart("Upload", new StringBody("Submit Query", Charset.forName("UTF-8")));
    method.setEntity(entityIn);

    if (client != null) {
        return executeUpload(method, client);
    }

    return null;
}

From source file:org.sonar.updatecenter.server.HttpDownloader.java

File downloadFile(URI fileURI, File toFile, String login, String password) {
    LOG.info("Download " + fileURI + " in " + toFile);
    DefaultHttpClient client = new DefaultHttpClient();
    try {/*from   w ww  .j  a v a  2s . c  o m*/
        if (StringUtils.isNotBlank(login)) {
            client.getCredentialsProvider().setCredentials(new AuthScope(fileURI.getHost(), fileURI.getPort()),
                    new UsernamePasswordCredentials(login, password));
        }
        HttpGet httpget = new HttpGet(fileURI);
        byte[] data = client.execute(httpget, new ByteResponseHandler());
        if (data != null) {
            FileUtils.writeByteArrayToFile(toFile, data);
        }

    } catch (Exception e) {
        LOG.error("Fail to download " + fileURI + " to " + toFile, e);
        FileUtils.deleteQuietly(toFile);

    } finally {
        client.getConnectionManager().shutdown();
    }
    return toFile;
}

From source file:com.alibaba.napoli.gecko.service.impl.DefaultRemotingClient.java

private InetSocketAddress getSocketAddrFromGroup(String group) throws NotifyRemotingException {
    if (group == null) {
        throw new IllegalArgumentException("Null group");
    }/*from   w  w w .  j  a v a2 s .com*/
    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:org.springframework.cloud.dataflow.rest.util.HttpClientConfigurer.java

/**
 * Configures the {@link HttpClientBuilder} with a proxy host. If the
 * {@code proxyUsername} and {@code proxyPassword} are not {@code null}
 * then a {@link CredentialsProvider} is also configured for the proxy host.
 *
 * @param proxyUri Must not be null and must be configured with a scheme (http or https).
 * @param proxyUsername May be null/*from   w  ww.ja  v  a  2  s . c  o  m*/
 * @param proxyPassword May be null
 * @return a reference to {@code this} to enable chained method invocation
 */
public HttpClientConfigurer withProxyCredentials(URI proxyUri, String proxyUsername, String proxyPassword) {

    Assert.notNull(proxyUri, "The proxyUri must not be null.");
    Assert.hasText(proxyUri.getScheme(), "The scheme component of the proxyUri must not be empty.");

    httpClientBuilder.setProxy(new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme()));
    if (proxyUsername != null && proxyPassword != null) {
        final CredentialsProvider credentialsProvider = this.getOrInitializeCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(proxyUri.getHost(), proxyUri.getPort()),
                new UsernamePasswordCredentials(proxyUsername, proxyPassword));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
                .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
    }
    return this;
}

From source file:com.esri.geoportal.commons.http.BotsHttpClient.java

private URI updateURI(URI uri, PHP php) throws URISyntaxException {
    return new URI(php.protocol != null ? php.protocol : uri.getScheme(), uri.getUserInfo(),
            php.host != null ? php.host : uri.getHost(),
            php.host != null ? php.port != null ? php.port : -1 : uri.getPort(), uri.getPath(), uri.getQuery(),
            uri.getFragment());//ww  w.  jav  a  2s  .  co m
}