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.appeligo.search.actions.ToolbarUpdateAction.java

public String execute() throws Exception {
    Integer toolbarRevision = (Integer) getSession().get("toolbarRevision");
    if (toolbarRevision == null) {
        revision = 0;/*from   w  w  w .j av  a 2 s.c o  m*/
    } else {
        revision = toolbarRevision.intValue() + 1;
    }
    getSession().put("toolbarRevision", new Integer(revision));
    try {
        URL u = new URL(url);
        String host = u.getHost();
        if (host.startsWith("www.")) {
            host = host.substring(4);
        }
        log.debug(host);
        log.debug(u.getPort());
        log.debug(u.getPath());
        SearchEngine searchEngine = searchEngineMap.get(host);
        if ((searchEngine != null)
                && (u.getPort() == searchEngine.getPort()
                        || ((u.getPort() == -1) && (searchEngine.getPort() == 80)))
                && (u.getPath().indexOf(searchEngine.getPath()) == 0)) {
            String query = u.getQuery();
            if (query != null) {
                String[] params = query.split("&");
                for (String param : params) {
                    if (param.startsWith(searchEngine.getParam())) {
                        log.debug(param);
                        String q = param.substring(searchEngine.getParam().length());
                        q = URLDecoder.decode(q, "UTF-8");
                        log.debug(q);
                        setQuery(q);
                        String indexDir = ConfigUtils.getSystemConfig().getString("luceneIndex");
                        String compositeIndexDir = ConfigUtils.getSystemConfig().getString("compositeIndex");
                        if (IndexReader.indexExists(indexDir)) {
                            String lineup = getLineup();
                            searchResults = new SearchResults(indexDir, compositeIndexDir, 10, lineup);
                            searchResults.setLineup(lineup);
                            searchResults.setQuery(getQuery());
                            searchResults.setSearchType(getSearchTypeAsSearchType());
                            hits = searchResults.getSearchResults(0);
                        }
                        break;
                    }
                }
            }
        }
    } catch (MalformedURLException e) {
        //ignore;
    }

    return SUCCESS;
}

From source file:com.k42b3.aletheia.protocol.http.Request.java

private void parseUrl(URL url) {
    this.host = url.getHost();
    this.path = url.getPath().isEmpty() ? "/" : url.getPath();

    if (url.getQuery() != null) {
        this.path += "?" + url.getQuery();
    }/*from   w  ww. j a  v  a 2  s .  c  o  m*/

    if (url.getRef() != null) {
        this.path += "#" + url.getRef();
    }
}

From source file:org.jboss.as.test.integration.web.security.servlet3.ServletSecurityRoleNamesCommon.java

/**
 * Method that needs to be overridden with the HTTPClient code.
 *
 * @param user         username/*  w  ww . ja va2  s  .  co m*/
 * @param pass         password
 * @param expectedCode http status code
 * @throws Exception
 */
protected void makeCall(String user, String pass, int expectedCode, URL url) throws Exception {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(user, pass));
    try (CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credentialsProvider).build()) {

        HttpGet httpget = new HttpGet(url.toExternalForm());

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        StatusLine statusLine = response.getStatusLine();
        assertEquals(expectedCode, statusLine.getStatusCode());

        EntityUtils.consume(entity);
    }
}

From source file:com.ibm.mf.geofence.demo.SlackHTTPService.java

@Override
protected Uri getBaseQueryURI() throws Exception {
    URL url = new URL(getServerURL());
    int port = url.getPort();
    String portStr = (port < 0) ? "" : ":" + port;
    Uri.Builder builder = new Uri.Builder().scheme(url.getProtocol()).encodedAuthority(url.getHost() + portStr);
    return builder.build();
}

From source file:com.beyondjservlet.gateway.servlet.ProxyDetails.java

public ProxyDetails(boolean valid, String stringProxyURL, HttpProxyRule proxyRule) {
    this.valid = valid;
    this.stringProxyURL = stringProxyURL;
    this.proxyRule = proxyRule;

    int port = 0;
    String host = "";

    try {/*from   www.  java2 s  . c  o  m*/
        URL url = new URL(stringProxyURL);
        proxyPath = url.getPath();
        protocol = url.getProtocol();
        proxyHostAndPort = url.getHost() + ":" + url.getPort();
    } catch (Exception e) {
        while (proxyHostAndPort.startsWith("/")) {
            proxyHostAndPort = proxyHostAndPort.substring(1);
        }
        host = proxyHostAndPort;
        int idx = indexOf(proxyHostAndPort, ":", "/");
        if (idx > 0) {
            host = proxyHostAndPort.substring(0, idx);
            String portText = proxyHostAndPort.substring(idx + 1);
            idx = portText.indexOf("/");
            if (idx >= 0) {
                proxyPath = portText.substring(idx);
                portText = portText.substring(0, idx);
            }

            if (StringUtils.isNotBlank(portText)) {
                // portText may be a port unless its default
                try {
                    port = Integer.parseInt(portText);
                    proxyHostAndPort = host + ":" + port;
                } catch (NumberFormatException ex) {
                    port = 80;
                    // we do not have a port, so proxyPath is the portText
                    proxyPath = "/" + portText + proxyPath;
                    proxyHostAndPort = host;
                }
            } else {
                proxyHostAndPort = host;
            }
        }
    }
}

From source file:com.sonymobile.tools.gerrit.gerritevents.workers.rest.AbstractRestCommandJob.java

@Override
public void run() {
    ReviewInput reviewInput = createReview();

    String reviewEndpoint = resolveEndpointURL();

    HttpPost httpPost = createHttpPostEntity(reviewInput, reviewEndpoint);

    if (httpPost == null) {
        return;/* ww w. j  a  v a 2  s. c om*/
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), config.getHttpCredentials());
    if (config.getGerritProxy() != null && !config.getGerritProxy().isEmpty()) {
        try {
            URL url = new URL(config.getGerritProxy());
            HttpHost proxy = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        } catch (MalformedURLException e) {
            logger.error("Could not parse proxy URL, attempting without proxy.", e);
            if (altLogger != null) {
                altLogger.print("ERROR Could not parse proxy URL, attempting without proxy. " + e.getMessage());
            }
        }
    }
    try {
        HttpResponse httpResponse = httpclient.execute(httpPost);
        String response = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");

        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            logger.error("Gerrit response: {}", httpResponse.getStatusLine().getReasonPhrase());
            if (altLogger != null) {
                altLogger.print("ERROR Gerrit response: " + httpResponse.getStatusLine().getReasonPhrase());
            }
        }
    } catch (Exception e) {
        logger.error("Failed to submit result to Gerrit", e);
        if (altLogger != null) {
            altLogger.print("ERROR Failed to submit result to Gerrit" + e.toString());
        }
    }
}

From source file:org.pentaho.reporting.platform.plugin.PentahoReportEnvironment.java

private String getBaseServerURL(final String fullyQualifiedServerUrl) {
    try {
        final URL url = new URL(fullyQualifiedServerUrl);
        return url.getProtocol() + "://" + url.getHost() + ":" + url.getPort(); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (Exception e) {
        // ignore
        logger.warn(Messages.getInstance().getString("ReportPlugin.warnNoBaseServerURL"), e);
    }/*  w w  w.j  av  a2  s  .c  o  m*/
    return null;
}

From source file:com.gargoylesoftware.htmlunit.CookieManager.java

/**
 * Helper that builds a CookieOrigin.//from  w w w.  ja v a  2  s . c o  m
 * @param url the url to be used
 * @return the new CookieOrigin
 */
public CookieOrigin buildCookieOrigin(final URL url) {
    final URL normalizedUrl = replaceForCookieIfNecessary(url);

    return new CookieOrigin(normalizedUrl.getHost(), getPort(normalizedUrl), normalizedUrl.getPath(),
            "https".equals(normalizedUrl.getProtocol()));
}

From source file:io.apiman.gateway.vertx.connector.HttpConnector.java

/**
 * Construct an {@link HttpConnector} instance. The {@link #resultHandler} must remain exclusive to a
 * given instance.//  www  .  j  a v a  2  s. com
 *
 * @param vertx a vertx
 * @param service a service
 * @param request a request with fields filled
 * @param resultHandler a handler, called when reading is permitted
 */
public HttpConnector(Vertx vertx, Container container, Service service, ServiceRequest request,
        IAsyncResultHandler<IServiceConnectionResponse> resultHandler) {
    this.vertx = vertx;
    this.logger = container.logger();
    this.serviceRequest = request;
    this.resultHandler = resultHandler;
    this.exceptionHandler = new ExceptionHandler();

    URL serviceEndpoint = parseServiceEndpoint(service);

    serviceHost = serviceEndpoint.getHost();
    servicePort = serviceEndpoint.getPort();
    servicePath = StringUtils.removeEnd(serviceEndpoint.getPath(), "/"); //$NON-NLS-1$

    doConnection();
}

From source file:org.gluu.oxtrust.service.UmaProtectionService.java

private String getHost(String uri) throws MalformedURLException {
    URL url = new URL(uri);

    return url.getHost();
}