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.alfaariss.oa.sso.web.profile.ssoquery.SSOQueryProfile.java

/**
 * @see com.alfaariss.oa.api.IService#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from   w  ww  .j  a v  a  2s  .c om
public void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws OAException {
    try {
        if (!_bEnabled) {
            _logger.debug("Component is disabled");
            throw new UserException(UserEvent.INTERNAL_ERROR);
        }

        _logger.debug("Performing 'sso query' request sent from IP: " + servletRequest.getRemoteAddr());

        String responseUrl = servletRequest.getParameter(PARAM_RESPONSE_URL);
        if (responseUrl == null) {
            _logger.debug("No parameter '" + PARAM_RESPONSE_URL + "' available in request");
            throw new UserException(UserEvent.REQUEST_INVALID);
        }

        if (_whitelist != null) {
            try {
                URL urlResponse = new URL(responseUrl);

                if (!_whitelist.isWhitelisted(urlResponse.getHost())) {
                    _logger.debug("Hostname isn't whitelisted: " + urlResponse.getHost());
                    throw new UserException(UserEvent.REQUEST_INVALID);
                }
            } catch (MalformedURLException e) {
                StringBuffer sbError = new StringBuffer("Invalid parameter '");
                sbError.append(PARAM_RESPONSE_URL);
                sbError.append("' available in request: ");
                sbError.append(responseUrl);
                _logger.debug(sbError.toString());

                throw new UserException(UserEvent.REQUEST_INVALID);
            }
        }

        String sResult = "false";
        String sTGTCookie = _cookieTool.getCookieValue(WebSSOServlet.TGT_COOKIE_NAME, servletRequest);
        if (sTGTCookie != null) {
            ITGT tgt = _tgtFactory.retrieve(sTGTCookie);
            if (tgt != null && !tgt.isExpired())
                sResult = "true";
        }

        StringBuffer sbRedirect = new StringBuffer(responseUrl);
        if (responseUrl.contains("?"))
            sbRedirect.append("&");
        else
            sbRedirect.append("?");

        sbRedirect.append(PARAM_RESULT);
        sbRedirect.append("=");
        sbRedirect.append(sResult);

        _eventLogger.info(new RequestorEventLogItem(null, sTGTCookie, null, RequestorEvent.QUERY_SUCCESSFUL,
                null, servletRequest.getRemoteAddr(), null, this, sResult));

        _logger.debug("Redirecting user to: " + sbRedirect.toString());
        servletResponse.sendRedirect(sbRedirect.toString());
    } catch (UserException e) {
        try {
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException e1) {
            _logger.debug("Could not respond", e1);
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }
    } catch (Exception e) {
        _logger.fatal("Internal error during sso request", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:com.docdoku.cli.helpers.FileHelper.java

public String uploadFile(File pLocalFile, String pURL)
        throws IOException, LoginException, NoSuchAlgorithmException {
    InputStream in = null;//  ww w  . ja  v a2  s .  c  o  m
    OutputStream out = null;
    HttpURLConnection conn = null;
    try {
        //Hack for NTLM proxy
        //perform a head method to negociate the NTLM proxy authentication
        URL url = new URL(pURL);
        System.out.println("Uploading file: " + pLocalFile.getName() + " to " + url.getHost());
        performHeadHTTPMethod(url);

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        byte[] encoded = Base64.encodeBase64((login + ":" + password).getBytes("ISO-8859-1"));
        conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII"));

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "--------------------" + Long.toString(System.currentTimeMillis(), 16);
        byte[] header = (twoHyphens + boundary + lineEnd + "Content-Disposition: form-data; name=\"upload\";"
                + " filename=\"" + pLocalFile + "\"" + lineEnd + lineEnd).getBytes("ISO-8859-1");
        byte[] footer = (lineEnd + twoHyphens + boundary + twoHyphens + lineEnd).getBytes("ISO-8859-1");

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        //conn.setRequestProperty("Content-Length",len + "");
        long len = header.length + pLocalFile.length() + footer.length;
        conn.setFixedLengthStreamingMode((int) len);
        out = new BufferedOutputStream(conn.getOutputStream(), BUFFER_CAPACITY);
        out.write(header);

        byte[] data = new byte[CHUNK_SIZE];
        int length;
        MessageDigest md = MessageDigest.getInstance("MD5");
        in = new ConsoleProgressMonitorInputStream(pLocalFile.length(), new DigestInputStream(
                new BufferedInputStream(new FileInputStream(pLocalFile), BUFFER_CAPACITY), md));
        while ((length = in.read(data)) != -1) {
            out.write(data, 0, length);
        }

        out.write(footer);
        out.flush();

        manageHTTPCode(conn);

        byte[] digest = md.digest();
        return Base64.encodeBase64String(digest);
    } finally {
        if (out != null)
            out.close();
        if (in != null)
            in.close();
        if (conn != null)
            conn.disconnect();
    }
}

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

private boolean isAlreadyRegistered(RegistrationRequest node) {

    HttpClient client = httpClientFactory.getHttpClient();
    try {/*w  ww .j a  v a  2s  . co m*/
        String tmp = "http://" + node.getConfiguration().get(RegistrationRequest.HUB_HOST) + ":"
                + node.getConfiguration().get(RegistrationRequest.HUB_PORT) + "/grid/api/proxy";
        URL api = new URL(tmp);
        HttpHost host = new HttpHost(api.getHost(), api.getPort());

        String id = (String) node.getConfiguration().get(RegistrationRequest.ID);
        if (id == null) {
            id = (String) node.getConfiguration().get(RegistrationRequest.REMOTE_HOST);
        }
        BasicHttpRequest r = new BasicHttpRequest("GET", api.toExternalForm() + "?id=" + id);

        HttpResponse response = client.execute(host, r);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new GridException("Hub is down or not responding.");
        }
        JSONObject o = extractObject(response);
        return (Boolean) o.get("success");
    } catch (Exception e) {
        throw new GridException("Hub is down or not responding: " + e.getMessage());
    }
}

From source file:net.solarnetwork.node.price.delimited.DelimitedPriceDatumDataSource.java

@Override
public String toString() {
    String host = "";
    try {//from ww w  . j  a va2  s . c o  m
        URL theUrl = getFormattedUrl();
        host = theUrl.getHost();
    } catch (Exception e) {
        host = "unknown";
    }
    return "DelimitedPriceDatumDataSource{" + host + "}";
}

From source file:com.celamanzi.liferay.portlets.rails286.HeadProcessor.java

protected HeadProcessor(String servlet, java.net.URL baseUrl, String namespace) {
    this.servlet = servlet;
    this.baseUrl = baseUrl;
    this.namespace = namespace;
    this.location = baseUrl.getProtocol() + "://" + baseUrl.getHost() + ":" + baseUrl.getPort() + servlet;
    log.debug("Initializing HeadProcessor @: " + this.location);
}

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

public void delete(String targetLocation, String name, String username, String password)
        throws TransportException {

    targetLocation = addTrailingSlash(targetLocation) + "deletefile.php";

    PostMethod post = new PostMethod(targetLocation);
    post.addParameter("fileToDelete", name);

    //This part is wrapped in a try/finally so that we can ensure
    //the connection to the HTTP server is always closed cleanly 
    try {/*from w ww .ja  v  a 2s  .co m*/

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

        int status = client.executeMethod(post);
        if (status != HttpStatus.SC_OK) {
            throw new TransportException(
                    "There's been some kind of problem deleting a file on the HTTP server.\n\nThe HTTP error message is ["
                            + HttpStatus.getStatusText(status) + "]");
        }

        if (!post.getResponseBodyAsString().equals("OK")) {
            throw new TransportException(
                    "There's been some kind of problem deleting a file to the HTTP server.\n\nThe error message is ["
                            + post.getResponseBodyAsString() + "]");
        }

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

}

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

private HttpHost getHttpHost(URL host) {
    HttpHost httpHost = new HttpHost(host.getHost(), host.getPort(), host.getProtocol());
    return httpHost;
}

From source file:com.digitalpebble.storm.crawler.indexing.AbstractIndexerBolt.java

/**
 * Returns the value to be used as the URL for indexing purposes, if present
 * the canonical value is used instead/* w  w  w . ja v  a 2 s.  c  o m*/
 */
protected String valueForURL(Tuple tuple) {

    String url = tuple.getStringByField("url");
    Metadata metadata = (Metadata) tuple.getValueByField("metadata");

    // functionality deactivated
    if (StringUtils.isBlank(canonicalMetadataParamName)) {
        return url;
    }

    String canonicalValue = metadata.getFirstValue(canonicalMetadataName);

    // no value found?
    if (StringUtils.isBlank(canonicalValue)) {
        return url;
    }

    try {
        URL sURL = new URL(url);
        URL canonical = URLUtil.resolveURL(sURL, canonicalValue);

        // check is the same host
        if (sURL.getHost().equals(canonical.getHost())) {
            return canonical.toExternalForm();
        } else {
            LOG.info("Canonical URL references a different host, ignoring in {} ", url);
        }
    } catch (MalformedURLException e) {
        LOG.error("Malformed canonical URL {} was found in {} ", canonicalValue, url);
    }

    return url;
}

From source file:com.zimbra.cs.zimlet.ProxyServlet.java

private boolean checkPermissionOnTarget(URL target, AuthToken auth) {
    String host = target.getHost().toLowerCase();
    ZimbraLog.zimlet.debug("checking allowedDomains permission on target host: " + host);
    Set<String> domains;
    try {//from  w  ww . j  av  a 2  s. c  o m
        domains = getAllowedDomains(auth);
    } catch (ServiceException se) {
        ZimbraLog.zimlet.info("error getting allowedDomains: " + se.getMessage());
        return false;
    }
    for (String domain : domains) {
        if (domain.equals("*")) {
            return true;
        }
        if (domain.charAt(0) == '*') {
            domain = domain.substring(1);
        }
        if (host.endsWith(domain)) {
            return true;
        }
    }
    return false;
}

From source file:no.kantega.kwashc.server.test.SSLCipherSuiteTest.java

private HttpResponse checkClientForCiphers(Site site, int httpsPort, HttpClient httpclient, String[] ciphers)
        throws NoSuchAlgorithmException, KeyManagementException, IOException {
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { allowAllTrustManager }, null);

    SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000);

    SSLSocket socket = (SSLSocket) sf.createSocket(params);
    socket.setEnabledCipherSuites(ciphers);

    URL url = new URL(site.getAddress());

    InetSocketAddress address = new InetSocketAddress(url.getHost(), httpsPort);
    sf.connectSocket(socket, address, null, params);

    Scheme sch = new Scheme("https", httpsPort, sf);
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);

    HttpGet request = new HttpGet(
            "https://" + url.getHost() + ":" + site.getSecureport() + url.getPath() + "blog");

    return httpclient.execute(request);
}