Example usage for java.net URL getHost

List of usage examples for java.net URL getHost

Introduction

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

Prototype

public String getHost() 

Source Link

Document

Gets the host name of this URL , if applicable.

Usage

From source file:com.devicehive.application.filter.SwaggerFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    URL requestUrl = new URL(request.getRequestURL().toString());
    logger.debug("Swagger filter triggered by '{}: {}'. Request will be redirected to swagger page",
            request.getMethod(), requestUrl);

    String swaggerJsonUrl = String.format("%s://%s:%s%s%s/swagger.json", requestUrl.getProtocol(),
            requestUrl.getHost(),
            requestUrl.getPort() == -1 ? requestUrl.getDefaultPort() : requestUrl.getPort(),
            request.getContextPath(), JerseyConfig.REST_PATH);
    String url = request.getContextPath() + "/swagger.html?url=" + swaggerJsonUrl;

    logger.debug("Request is being redirected to '{}'", url);
    response.sendRedirect(url);/*ww  w. j  a v  a2  s  .c  o  m*/
}

From source file:de.spqrinfo.cups4j.operations.IppOperation.java

/**
 * Removes the port number in the submitted URL
 *
 * @param url//ww  w . j  av  a2 s.  c o m
 * @return url without port number
 */
protected String stripPortNumber(URL url) {
    String protocol = url.getProtocol();
    if ("ipp".equals(protocol)) {
        protocol = "http";
    }

    return protocol + "://" + url.getHost() + url.getPath();
}

From source file:ch.sbb.releasetrain.utils.http.HttpUtilImpl.java

/**
 * authenticates the context if user and password are set
 *//*w w  w.  j a  va 2  s. c  om*/
private HttpClientContext initAuthIfNeeded(String url) {

    HttpClientContext context = HttpClientContext.create();
    if (this.user.isEmpty() || this.password.isEmpty()) {
        log.debug(
                "http connection without autentication, because no user / password ist known to HttpUtilImpl ...");
        return context;
    }

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(user, password));
    URL url4Host;
    try {
        url4Host = new URL(url);
    } catch (MalformedURLException e) {
        log.error(e.getMessage(), e);
        return context;
    }

    HttpHost targetHost = new HttpHost(url4Host.getHost(), url4Host.getPort(), url4Host.getProtocol());
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    return context;
}

From source file:com._17od.upm.transport.HTTPTransport.java

public byte[] get(String url, String username, String password) throws TransportException {

    byte[] retVal = null;

    GetMethod method = new GetMethod(url);

    //This part is wrapped in a try/finally so that we can ensure
    //the connection to the HTTP server is always closed cleanly 
    try {/*w w w.j av  a2  s .  co  m*/

        //Set the authentication details
        if (username != null) {
            Credentials creds = new UsernamePasswordCredentials(new String(username), new String(password));
            URL urlObj = new URL(url);
            AuthScope authScope = new AuthScope(urlObj.getHost(), urlObj.getPort());
            client.getState().setCredentials(authScope, creds);
            client.getParams().setAuthenticationPreemptive(true);
        }

        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            throw new TransportException("There's been some kind of problem getting the URL [" + url
                    + "].\n\nThe HTTP error message is [" + HttpStatus.getStatusText(statusCode) + "]");
        }

        retVal = method.getResponseBody();

    } catch (MalformedURLException e) {
        throw new TransportException(e);
    } catch (HttpException e) {
        throw new TransportException(e);
    } catch (IOException e) {
        throw new TransportException(e);
    } finally {
        method.releaseConnection();
    }

    return retVal;

}

From source file:it.tidalwave.bluemarine2.downloader.impl.SimpleHttpCacheStorage.java

/*******************************************************************************************************************
 *
 * /*from  w w w .  j  a va2 s .  c o  m*/
 *
 ******************************************************************************************************************/
@Nonnull
private Path getCacheItemPath(final @Nonnull URL url) throws MalformedURLException {
    final int port = url.getPort();
    final URL url2 = new URL(url.getProtocol(), url.getHost(), (port == 80) ? -1 : port, url.getFile());
    final Path cachePath = Paths.get(url2.toString().replaceAll(":", ""));
    return folderPath.resolve(cachePath);
}

From source file:org.jboss.as.test.integration.management.console.XFrameOptionsHeaderTestCase.java

private CredentialsProvider createCredentialsProvider(URL url) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(Authentication.USERNAME,
            Authentication.PASSWORD);//ww  w  . j  a v  a 2  s  .c  o m
    credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort(), "ManagementRealm"),
            credentials);
    return credentialsProvider;
}

From source file:org.openqa.grid.internal.utils.SelfRegisteringRemote.java

/**
 * uses the hub API to get some of its configuration.
 * @param parameters list of the parameter to be retrieved from the hub
 * @return/*from  ww w .  j a v  a 2  s  .  com*/
 * @throws Exception
 */
private JSONObject getHubConfiguration(String... parameters) throws Exception {
    String hubApi = "http://" + nodeConfig.getConfiguration().get(RegistrationRequest.HUB_HOST) + ":"
            + nodeConfig.getConfiguration().get(RegistrationRequest.HUB_PORT) + "/grid/api/hub";

    HttpClient client = httpClientFactory.getHttpClient();

    URL api = new URL(hubApi);
    HttpHost host = new HttpHost(api.getHost(), api.getPort());
    String url = api.toExternalForm();
    BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("GET", url);

    JSONObject j = new JSONObject();
    JSONArray keys = new JSONArray();

    j.put("configuration", keys);
    r.setEntity(new StringEntity(j.toString()));

    HttpResponse response = client.execute(host, r);
    return extractObject(response);
}

From source file:de.ecclesia.kipeto.RepositoryResolver.java

/**
 * Ermittelt anhand der Default-Repository-URL die IP-Adresse der
 * Netzwerkkarte, die Verbindung zum Repository hat.
 *//*from  w  ww. j a v  a 2  s  .  c  o m*/
private String determinateLocalIP() throws IOException {
    Socket socket = null;

    try {

        int port;
        String hostname;

        if (isSftp()) {
            port = 22;
            hostname = getHostname();
        } else {
            URL url = new URL(defaultRepositoryUrl);
            port = url.getPort() > -1 ? url.getPort() : url.getDefaultPort();
            hostname = url.getHost();
        }

        log.debug("Determinating local IP-Adress by connect to {}:{}", defaultRepositoryUrl, port);
        InetAddress address = Inet4Address.getByName(hostname);

        socket = new Socket();
        socket.connect(new InetSocketAddress(address, port), 3000);
        InputStream stream = socket.getInputStream();
        InetAddress localAddress = socket.getLocalAddress();
        stream.close();

        String localIp = localAddress.getHostAddress();

        log.info("Local IP-Adress is {}", localIp);

        return localIp;
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:com.blackducksoftware.integration.hub.global.HubProxyInfo.java

public boolean shouldUseProxyForUrl(final URL url) {
    final List<Pattern> ignoredProxyHostPatterns = getIgnoredProxyHostPatterns();
    boolean shouldUseProxy = !shouldIgnoreHost(url.getHost(), ignoredProxyHostPatterns);
    if (StringUtils.isBlank(host) || port <= 0) {
        shouldUseProxy = false;/*  w  w w.  j  a v  a2 s .  c om*/
    }
    return shouldUseProxy;
}

From source file:it.geosolutions.httpproxy.callback.HostNameChecker.java

public void onRequest(HttpServletRequest request, HttpServletResponse response, URL url) throws IOException {
    Set<String> hostNames = config.getHostnameWhitelist();

    // ////////////////////////////////
    // Check the whitelist of hosts
    // ////////////////////////////////

    if (hostNames != null && hostNames.size() > 0) {
        String hostName = url.getHost();

        if (!hostNames.contains(hostName)) {
            throw new HttpErrorException(403,
                    "Host Name " + hostName + " is not among the ones allowed for this proxy");
        }/*  w  w  w.  j a  v  a 2s .  c o m*/
    }
}