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:jp.igapyon.selecrawler.SeleCrawlerWebContentGetter.java

public File getFileHtml(final String deviceName, final String urlLookup) throws IOException {
    final URL url = new URL(urlLookup);
    final String serverhostname = url.getHost();
    String path = url.getPath();//from  w  ww  .  ja  v  a2  s.  c o m
    if (path.length() == 0 || path.equals("/") || path.endsWith("/")) {
        path = path + "/index.html";
    }

    if (url.getQuery() != null) {
        try {
            path += new URLCodec().encode("?" + url.getQuery());
        } catch (EncoderException e) {
            e.printStackTrace();
        }

    }

    return new File(settings.getPathTargetDir() + deviceName + "/" + serverhostname + path);
}

From source file:fx.browser.Window.java

public void setLocation(String location) throws URISyntaxException {
    System.out.println("# " + this.toString() + "-Classloader: " + getClass().getClassLoader().toString()
            + " setLocation()");
    this.location = location;
    HttpGet httpGet = new HttpGet(new URI(location));

    try (CloseableHttpResponse response = Browser.getHttpClient().execute(httpGet)) {
        switch (response.getStatusLine().getStatusCode()) {

        case HttpStatus.SC_OK:
            FXMLLoader loader = new FXMLLoader();
            Header header = response.getFirstHeader("class-loader-url");

            if (header != null) {
                URL url = new URL(location);

                url = new URL(url.getProtocol(), url.getHost(), url.getPort(), header.getValue());
                if (logger.isLoggable(Level.INFO)) {
                    logger.log(Level.INFO, "Set up remote classloader: {0}", url);
                }//from w w w  . j  a  v a  2  s  .  com

                loader.setClassLoader(HttpClassLoader.getInstance(url, getClass().getClassLoader()));
            }

            try {
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();

                response.getEntity().writeTo(buffer);
                response.close();
                setContent(loader.load(new ByteArrayInputStream(buffer.toByteArray())));
            } catch (Exception e) {
                response.close();
                logger.log(Level.INFO, e.toString(), e);
                Node node = loader.load(getClass().getResourceAsStream("/fxml/webview.fxml"));
                WebViewController controller = (WebViewController) loader.getController();

                controller.view(location);
                setContent(node);
            }

            break;

        case HttpStatus.SC_UNAUTHORIZED:
            response.close();
            Optional<Pair<String, String>> result = new LoginDialog().showAndWait();

            if (result.isPresent()) {
                URL url = new URL(location);

                Browser.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                        new UsernamePasswordCredentials(result.get().getKey(), result.get().getValue()));
                setLocation(location);
            }

            break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:uk.ac.ox.oucs.vle.XcriPopulatorInput.java

public InputStream getInput(PopulatorContext context) throws PopulatorException {

    InputStream input = null;//from  w  w  w  .jav  a  2 s  .  c  o m
    HttpEntity entity = null;

    try {
        URL xcri = new URL(context.getURI());

        HttpHost targetHost = new HttpHost(xcri.getHost(), xcri.getPort(), xcri.getProtocol());

        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(context.getUser(), context.getPassword()));

        HttpGet httpget = new HttpGet(xcri.toURI());
        HttpResponse response = httpClient.execute(targetHost, httpget);
        entity = response.getEntity();

        if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
            throw new PopulatorException("Invalid Response [" + response.getStatusLine().getStatusCode() + "]");
        }

        input = entity.getContent();

    } catch (MalformedURLException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IllegalStateException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IOException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (URISyntaxException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } finally {
        if (null == input && null != entity) {
            try {
                entity.getContent().close();
            } catch (IOException e) {
                log.error("IOException [" + e + "]");
            }
        }
    }
    return input;
}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImpl.java

public AvaticaCommonsHttpClientImpl(URL url) {
    this.host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    this.uri = toURI(Objects.requireNonNull(url));
    initializeClient();/* w  ww .  java2  s.co  m*/
}

From source file:com.macdonst.ftpclient.FtpClient.java

/**
 * Creates, connects and logs into a FTP server
 * @param url of the FTP server/*  ww w.  ja va2  s  .co m*/
 * @return an instance of FTPClient
 * @throws IOException
 */
private FTPClient setup(URL url) throws IOException {
    FTPClient f = new FTPClient();
    f.connect(url.getHost(), extractPort(url));

    StringTokenizer tok = new StringTokenizer(url.getUserInfo(), ":");
    f.login(tok.nextToken(), tok.nextToken());

    f.enterLocalPassiveMode();
    f.setFileType(FTP.BINARY_FILE_TYPE);

    return f;
}

From source file:net.nightwhistler.pageturner.PageTurnerModule.java

/**
 * Binds the HttpClient interface to the DefaultHttpClient implementation.
 * //ww w  .ja v  a  2 s  .c o m
 * In testing we'll use a stub.
 * 
 * @return
 */
@Provides
@Inject
public HttpClient getHttpClient(Configuration config) {
    HttpParams httpParams = new BasicHttpParams();
    DefaultHttpClient client;

    if (config.isAcceptSelfSignedCertificates()) {
        client = new SSLHttpClient(httpParams);
    } else {
        client = new DefaultHttpClient(httpParams);
    }

    for (CustomOPDSSite site : config.getCustomOPDSSites()) {
        if (site.getUserName() != null && site.getUserName().length() > 0) {
            try {
                URL url = new URL(site.getUrl());
                client.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                        new UsernamePasswordCredentials(site.getUserName(), site.getPassword()));
            } catch (MalformedURLException mal) {
                //skip to the next
            }
        }
    }

    return client;
}

From source file:com.epam.catgenome.manager.DownloadFileManager.java

private void checkURL(final URL url) {
    final String urlHost = url.getHost();
    final List<String> hostList = getFilterWhiteHostList();
    boolean flag = false;
    for (String s : hostList) {
        if (s.equals(urlHost)) {
            flag = true;//from w w w . j a v  a2 s .c o  m
        }
    }
    Assert.isTrue(flag, MessageHelper.getMessage(MessagesConstants.ERROR_UNKNOWN_HOST));
}

From source file:org.gvnix.service.roo.addon.addon.util.WsdlParserUtils.java

/**
 * Method makePackageName./*from   w  w w.  jav  a  2  s .com*/
 * 
 * @param namespace
 * @return
 */
public static String makePackageName(String namespace) {

    String hostname = null;
    String path = "";

    // get the target namespace of the document
    try {

        URL u = new URL(namespace);
        hostname = u.getHost();
        path = u.getPath();

    } catch (MalformedURLException e) {

        if (namespace.indexOf(':') > -1) {

            hostname = namespace.substring(namespace.indexOf(':') + 1);
            if (hostname.indexOf('/') > -1) {

                hostname = hostname.substring(0, hostname.indexOf('/'));
            }
        } else {

            hostname = namespace;
        }
    }

    // if we didn't file a hostname, bail
    if (hostname == null) {
        return null;
    }

    // convert illegal java identifier
    hostname = hostname.replace('-', '_');
    path = path.replace('-', '_');

    // chomp off last forward slash in path, if necessary
    if ((path.length() > 0) && (path.charAt(path.length() - 1) == '/')) {
        path = path.substring(0, path.length() - 1);
    }

    // tokenize the hostname and reverse it
    StringTokenizer st = new StringTokenizer(hostname, ".:");
    String[] words = new String[st.countTokens()];

    for (int i = 0; i < words.length; ++i) {
        words[i] = st.nextToken();
    }

    StringBuffer sb = new StringBuffer(namespace.length());

    for (int i = words.length - 1; i >= 0; --i) {
        addWordToPackageBuffer(sb, words[i], (i == words.length - 1));
    }

    // tokenize the path
    StringTokenizer st2 = new StringTokenizer(path, "/");

    while (st2.hasMoreTokens()) {
        addWordToPackageBuffer(sb, st2.nextToken(), false);
    }

    return sb.toString();
}

From source file:com.machinepublishers.jbrowserdriver.OptionsServer.java

private org.apache.http.cookie.Cookie convert(Cookie in) {
    BasicClientCookie out = new BasicClientCookie(in.getName(), in.getValue());
    String domainStr = null;/*from   w ww. j  av a 2s .  c o  m*/
    if (StringUtils.isEmpty(in.getDomain())) {
        String urlStr = context.item().engine.get().getLocation();
        try {
            URL url = new URL(urlStr);
            domainStr = url.getHost();
        } catch (MalformedURLException e) {
            Matcher matcher = domain.matcher(urlStr);
            if (matcher.matches()) {
                domainStr = matcher.group(1);
            }
        }
    }
    out.setDomain(domainStr == null ? in.getDomain() : domainStr);
    if (in.getExpiry() != null) {
        out.setExpiryDate(in.getExpiry());
    }
    out.setPath(in.getPath());
    out.setSecure(in.isSecure());
    out.setValue(in.getValue());
    out.setVersion(1);
    return out;
}

From source file:pt.webdetails.browserid.spring.BrowserIdProcessingFilter.java

/**
 * /*from  w  w  w . ja va  2 s .  com*/
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request) throws AuthenticationException {
    String browserIdAssertion = request.getParameter(getAssertionParameterName());
    //    String assertionAudience = request.getParameter(getAudienceParameterName());

    if (browserIdAssertion != null) {

        BrowserIdVerifier verifier = new BrowserIdVerifier(getVerificationServiceUrl());
        BrowserIdResponse response = null;

        String audience = request.getRequestURL().toString();
        try {
            URL url = new URL(audience);
            audience = url.getHost();
        } catch (MalformedURLException e) {
            throw new BrowserIdAuthenticationException("Malformed request URL", e);
        }

        //      Assert.hasLength("Unable to determine hostname",audience);
        //      if(!StringUtils.equals(audience, assertionAudience)){
        //        logger.error("Server and client-side audience don't match");
        //      }

        try {
            response = verifier.verify(browserIdAssertion, audience);
        } catch (HttpException e) {
            throw new BrowserIdAuthenticationException(
                    "Error calling verify service [" + verifier.getVerifyUrl() + "]", e);
        } catch (IOException e) {
            throw new BrowserIdAuthenticationException(
                    "Error calling verify service [" + verifier.getVerifyUrl() + "]", e);
        } catch (JSONException e) {
            throw new BrowserIdAuthenticationException(
                    "Could not parse response from verify service [" + verifier.getVerifyUrl() + "]", e);
        }

        if (response != null) {
            if (response.getStatus() == BrowserIdResponse.Status.OK) {
                BrowserIdAuthenticationToken token = new BrowserIdAuthenticationToken(response,
                        browserIdAssertion);
                //send to provider to get authorities
                return getAuthenticationManager().authenticate(token);
            } else {
                throw new BrowserIdAuthenticationException(
                        "BrowserID verification failed, reason: " + response.getReason());
            }
        } else
            throw new BrowserIdAuthenticationException("Verification yielded null response");
    }
    //may not be a BrowserID authentication
    return null;
}