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.jaspersoft.studio.server.protocol.restv2.RestV2Connection.java

@Override
public boolean connect(IProgressMonitor monitor, ServerProfile sp) throws Exception {
    this.sp = sp;

    URL url = sp.getURL();
    HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    exec = Executor.newInstance().auth(host, sp.getUser(), Pass.getPass(sp.getPass()));
    exec.authPreemptive(host);/* w  w w. j a  v a 2s  . co  m*/
    net.sf.jasperreports.eclipse.util.HttpUtils.setupProxy(exec, url.toURI());
    getServerInfo(monitor);

    return true;
}

From source file:org.fao.geonet.utils.GeonetHttpRequestFactory.java

/**
 * Ceate an XmlRequest from a url./*w  w w .  j  av a 2s  .c  om*/
 *
 * @param url the url of the request.
 * @return the XmlRequest.
 */
public final XmlRequest createXmlRequest(URL url) {
    final int port = url.getPort();
    final XmlRequest request = createXmlRequest(url.getHost(), port, url.getProtocol());

    request.setAddress(url.getPath());
    request.setQuery(url.getQuery());
    request.setFragment(url.getRef());
    request.setUserInfo(url.getUserInfo());
    request.setCookieStore(new BasicCookieStore());
    return request;
}

From source file:com.versatus.jwebshield.filter.SecurityTokenFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpRes = (HttpServletResponse) response;
    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);

    logger.debug("doFilter: request from IP address=" + httpReq.getRemoteAddr());

    if (httpReq.getSession(false) == null) {
        chain.doFilter(request, response);
        return;//w ww  .  jav  a  2 s .  c o m
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {

        logger.error("doFilter", e);
    }

    // Check the user session for the salt cache, if none is present we
    // create one
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache == null) {
        if (tokenTimeout == -1) {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000).build();
        } else {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000)
                    .expireAfterAccess(tokenTimeout, TimeUnit.SECONDS).build();
        }

        httpReq.getSession().setAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME, csrfPreventionSaltCache);

        String nameSalt = RandomStringUtils.random(10, 0, 0, true, true, null, new SecureRandom());
        httpReq.getSession().setAttribute(SecurityConstant.SALT_PARAM_NAME, nameSalt);
    }

    // Generate the salt and store it in the users cache
    String salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());

    String saltNameAttr = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);
    SecurityInfo si = new SecurityInfo(saltNameAttr, salt);

    if (SecurityTokenFilter.checkReferer) {
        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
        logger.debug("doFilter: refHeader=" + refHeader);
        if (StringUtils.isNotBlank(refHeader)) {
            try {
                URL refUrl = new URL(refHeader);
                refHeader = refUrl.getHost();
            } catch (MalformedURLException mex) {
                logger.debug("doFilter: parsing referer header failed", mex);
            }
        }

        si.setRefererHost(refHeader);
    }

    logger.debug("doFilter: si=" + si.toString());

    csrfPreventionSaltCache.put(si, si);

    // Add the salt to the current request so it can be used
    // by the page rendered in this request
    httpReq.setAttribute(SecurityConstant.SALT_ATTR_NAME, si);

    // set CSRF cookie
    HttpSession session = httpReq.getSession(false);
    if (session != null && StringUtils.isNotBlank(csrfCookieName)) {

        if (logger.isDebugEnabled()) {
            Cookie[] cookies = httpReq.getCookies();
            // boolean cookiePresent = false;
            for (Cookie c : cookies) {
                String name = c.getName();
                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());
                // if (csrfCookieName.equals(name)) {
                // cookiePresent = true;
                // break;
                // }
            }
        }
        // if (!cookiePresent) {
        byte[] hashSalt = new byte[32];
        SecureRandom sr = new SecureRandom();
        sr.nextBytes(hashSalt);

        String csrfHash = RandomStringUtils.random(64, 0, 0, true, true, null, sr);

        Cookie c = new Cookie(csrfCookieName, csrfHash);
        c.setMaxAge(1800);
        c.setSecure(false);
        c.setPath(httpReq.getContextPath());
        c.setHttpOnly(false);
        httpRes.addCookie(c);
        // session.setAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM,
        // hashStr);
        // }
    }

    chain.doFilter(request, response);
}

From source file:gov.nih.nci.caintegrator.web.action.analysis.GenePatternAnalysisForm.java

/**
 * Returns the URL where information on the currently selected analysis method may be found.
 *
 * @return the method information URL./*from w  w  w  . j  av a2s  .  c  o m*/
 */
public String getAnalysisMethodInformationUrl() {
    try {
        URL serviceUrl = new URL(server.getUrl());
        URL infoUrl = new URL(serviceUrl.getProtocol(), serviceUrl.getHost(), serviceUrl.getPort(),
                "/gp/getTaskDoc.jsp");
        return infoUrl.toExternalForm();
    } catch (MalformedURLException e) {
        throw new IllegalStateException("Server URL should already have been validated.", e);
    }
}

From source file:org.openmrs.module.dhisreport.web.controller.Dhis2ServerController.java

public boolean testConnection(URL url, String username, String password, HttpDhis2Server server,
        WebRequest webRequest, ModelMap model) {
    String host = url.getHost();
    int port = url.getPort();

    HttpHost targetHost = new HttpHost(host, port, url.getProtocol());
    DefaultHttpClient httpclient = new DefaultHttpClient();
    BasicHttpContext localcontext = new BasicHttpContext();

    try {//from w ww  .j  a v  a 2 s.co m
        HttpGet httpGet = new HttpGet(url.getPath()); // +
        // DATAVALUESET_PATH
        // );
        httpGet.addHeader(
                BasicScheme.authenticate(new UsernamePasswordCredentials(username, password), "UTF-8", false));

        HttpResponse response = httpclient.execute(targetHost, httpGet, localcontext);

        //System.out.println( "Http Response :" + response + ":" + response.getStatusLine().getStatusCode() );

        if (response.getStatusLine().getStatusCode() == 200) {
            log.debug("Dhis2 server configured: " + username + ":xxxxxx  " + url.toExternalForm());
            return true;
        }

        else {
            log.debug("Dhis2 server not configured");
            return false;
        }
    } catch (IOException ex) {
        log.debug("Problem accessing DHIS2 server: " + ex.toString());
        return false;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.predic8.membrane.core.interceptor.rewrite.ReverseProxyingInterceptor.java

/**
 * handles "Destination" header (see RFC 2518 section 9.3; also used by WebDAV)
 *///  w  w  w.j av  a  2s  . c  o m
@Override
public Outcome handleRequest(Exchange exc) throws Exception {
    if (exc.getRequest() == null)
        return Outcome.CONTINUE;
    String destination = exc.getRequest().getHeader().getFirstValue(Header.DESTINATION);
    if (destination == null)
        return Outcome.CONTINUE;
    if (!destination.contains("://"))
        return Outcome.CONTINUE; // local redirect (illegal by spec)
    // do not rewrite, if the client does not refer to the same host
    if (!isSameSchemeHostAndPort(getProtocol(exc) + "://" + exc.getRequest().getHeader().getHost(),
            destination))
        return Outcome.CONTINUE;
    // if we cannot determine the target hostname
    if (exc.getDestinations().isEmpty()) {
        // just remove the schema/hostname/port. this is illegal (by the spec),
        // but most clients understand it
        exc.getRequest().getHeader().setValue(Header.DESTINATION, new URL(destination).getFile());
        return Outcome.CONTINUE;
    }
    URL target = new URL(exc.getDestinations().get(0));
    // rewrite to our schema, host and port
    exc.getRequest().getHeader().setValue(Header.DESTINATION,
            Relocator.getNewLocation(destination, target.getProtocol(), target.getHost(),
                    target.getPort() == -1 ? target.getDefaultPort() : target.getPort()));
    return Outcome.CONTINUE;
}

From source file:fr.jayasoft.ivy.url.HttpClientHandler.java

private Credentials getCredentials(URL url) {
    return CredentialsStore.INSTANCE.getCredentials(null, url.getHost());
}

From source file:org.apache.hadoop.hbase.http.TestSpnegoHttpServer.java

@Test
public void testAllowedClient() throws Exception {
    // Create the subject for the client
    final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(CLIENT_PRINCIPAL, clientKeytab);
    final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    // Make sure the subject has a principal
    assertFalse(clientPrincipals.isEmpty());

    // Get a TGT for the subject (might have many, different encryption types). The first should
    // be the default encryption type.
    Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
    assertFalse(privateCredentials.isEmpty());
    KerberosTicket tgt = privateCredentials.iterator().next();
    assertNotNull(tgt);/*from w  w w .j a  va 2 s . co m*/

    // The name of the principal
    final String principalName = clientPrincipals.iterator().next().getName();

    // Run this code, logged in as the subject (the client)
    HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() {
        @Override
        public HttpResponse run() throws Exception {
            // Logs in with Kerberos via GSS
            GSSManager gssManager = GSSManager.getInstance();
            // jGSS Kerberos login constant
            Oid oid = new Oid("1.2.840.113554.1.2.2");
            GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
            GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME,
                    oid, GSSCredential.INITIATE_ONLY);

            HttpClientContext context = HttpClientContext.create();
            Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                    .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build();

            HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).build();
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

            URL url = new URL(getServerURL(server), "/echo?a=b");
            context.setTargetHost(new HttpHost(url.getHost(), url.getPort()));
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthSchemeRegistry(authRegistry);

            HttpGet get = new HttpGet(url.toURI());
            return client.execute(get, context);
        }
    });

    assertNotNull(resp);
    assertEquals(HttpURLConnection.HTTP_OK, resp.getStatusLine().getStatusCode());
    assertEquals("a:b", EntityUtils.toString(resp.getEntity()).trim());
}

From source file:org.signserver.client.cli.performance.PerformanceTestPDFServlet.java

License:asdf

/** @see org.signserver.client.PerformanceTestTask */
public boolean invoke(int threadId) {
    if (startTime == 0) {
        startTime = System.currentTimeMillis();
    }//from   w  w w. ja  v a 2 s  .c  o  m
    byte[] testPDF = pdfs
            .get((int) ((System.currentTimeMillis() - startTime) * ((long) pdfs.size()) / runTime));
    URL target;
    try {
        target = new URL(baseURLString);
        InetAddress addr = InetAddress.getByName(target.getHost());
        Socket socket = new Socket(addr, target.getPort());
        OutputStream raw = socket.getOutputStream();
        final int contentLength = REQUEST_CONTENT_WORKERNAME.length() + REQUEST_CONTENT_FILE.length()
                + testPDF.length + REQUEST_CONTENT_END.length();
        final String command = "POST " + target.getPath() + "pdf HTTP/1.0\r\n"
                + "Content-Type: multipart/form-data; boundary=signserver\r\n" + "Content-Length: "
                + contentLength + "\r\n" + "\r\n";
        raw.write(command.getBytes());
        raw.write(REQUEST_CONTENT_WORKERNAME.getBytes());
        raw.write(REQUEST_CONTENT_FILE.getBytes());
        raw.write(testPDF);
        raw.write(REQUEST_CONTENT_END.getBytes());
        raw.flush();

        InputStream in = socket.getInputStream();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf)) > 0) {
            os.write(buf, 0, len);
        }
        in.close();
        os.close();
        byte[] inbytes = os.toByteArray();

        PdfReader pdfReader = new PdfReader(inbytes);
        if (!new String(pdfReader.getPageContent(1)).contains(PDF_CONTENT)) {
            System.err.println("Did not get the same document back..");
            return false;
        }
        pdfReader.close();
        raw.close();
        socket.close();
    } catch (IOException e) {
        System.err.println("testPDF.length=" + testPDF.length + "," + e.getMessage());
        //e.printStackTrace();
        return false;
    }
    return true;
}

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

public String downloadFile(File pLocalFile, String pURL)
        throws IOException, LoginException, NoSuchAlgorithmException {
    ConsoleProgressMonitorInputStream in = null;
    OutputStream out = null;/*ww w  .j a v a2 s . co  m*/
    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("Downloading file: " + pLocalFile.getName() + " from " + url.getHost());
        performHeadHTTPMethod(url);

        out = new BufferedOutputStream(new FileOutputStream(pLocalFile), BUFFER_CAPACITY);

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

        MessageDigest md = MessageDigest.getInstance("MD5");
        in = new ConsoleProgressMonitorInputStream(conn.getContentLength(),
                new DigestInputStream(new BufferedInputStream(conn.getInputStream(), BUFFER_CAPACITY), md));
        byte[] data = new byte[CHUNK_SIZE];
        int length;

        while ((length = in.read(data)) != -1) {
            out.write(data, 0, length);
        }
        out.flush();

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