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:edu.cornell.mannlib.vitro.webapp.filters.VitroURL.java

public VitroURL(String urlStr, String characterEncoding) {
    this.characterEncoding = characterEncoding;
    if (urlStr.indexOf("&") > -1) {
        wasXMLEscaped = true;// w w w  . ja  v a2s  .c  o  m
        urlStr = StringEscapeUtils.unescapeXml(urlStr);
    }
    try {
        URL url = new URL(urlStr);
        this.protocol = url.getProtocol();
        this.host = url.getHost();
        this.port = Integer.toString(url.getPort());
        this.pathParts = splitPath(url.getPath());
        this.pathBeginsWithSlash = beginsWithSlash(url.getPath());
        this.pathEndsInSlash = endsInSlash(url.getPath());
        this.queryParams = parseQueryParams(url.getQuery());
        this.fragment = url.getRef();
    } catch (Exception e) {
        // Under normal circumstances, this is because the urlStr is relative
        // We'll assume that we just have a path and possibly a query string.
        // This is likely to be a bad assumption, but let's roll with it.
        Matcher m = pathPattern.matcher(urlStr);
        String[] urlParts = new String[2];
        if (m.matches()) {
            urlParts[0] = m.group(1);
            if (m.groupCount() == 2)
                urlParts[1] = m.group(2);
        } else {
            //???
        }

        try {
            this.pathParts = splitPath(URLDecoder.decode(getPath(urlStr), characterEncoding));
            this.pathBeginsWithSlash = beginsWithSlash(urlParts[0]);
            this.pathEndsInSlash = endsInSlash(urlParts[0]);
            if (urlParts.length > 1) {
                this.queryParams = parseQueryParams(URLDecoder.decode(urlParts[1], characterEncoding));
            }
        } catch (UnsupportedEncodingException uee) {
            log.error("Unable to use character encoding " + characterEncoding, uee);
        }
    }
}

From source file:com.dwdesign.tweetings.util.httpclient.HttpClientImpl.java

@Override
public twitter4j.internal.http.HttpResponse request(final twitter4j.internal.http.HttpRequest req)
        throws TwitterException {
    try {/*w  w  w.j a  v a2 s.  c o  m*/
        HttpRequestBase commonsRequest;

        //final HostAddressResolver resolver = conf.getHostAddressResolver();
        final String url_string = req.getURL();
        final URL url_orig = new URL(url_string);
        final String host = url_orig.getHost();
        //final String resolved_host = resolver != null ? resolver.resolve(host) : null;
        //final String resolved_url = resolved_host != null ? url_string.replace("://" + host, "://" + resolved_host)
        //      : url_string;
        final String resolved_url = url_string;
        if (req.getMethod() == RequestMethod.GET) {
            commonsRequest = new HttpGet(resolved_url);
        } else if (req.getMethod() == RequestMethod.POST) {
            final HttpPost post = new HttpPost(resolved_url);
            // parameter has a file?
            boolean hasFile = false;
            if (req.getParameters() != null) {
                for (final HttpParameter parameter : req.getParameters()) {
                    if (parameter.isFile()) {
                        hasFile = true;
                        break;
                    }
                }
                if (!hasFile) {
                    final ArrayList<NameValuePair> args = new ArrayList<NameValuePair>();
                    for (final HttpParameter parameter : req.getParameters()) {
                        args.add(new BasicNameValuePair(parameter.getName(), parameter.getValue()));
                    }
                    if (args.size() > 0) {
                        post.setEntity(new UrlEncodedFormEntity(args, "UTF-8"));
                    }
                } else {
                    final MultipartEntity me = new MultipartEntity();
                    for (final HttpParameter parameter : req.getParameters()) {
                        if (parameter.isFile()) {
                            final ContentBody body = new FileBody(parameter.getFile(),
                                    parameter.getContentType());
                            me.addPart(parameter.getName(), body);
                        } else {
                            final ContentBody body = new StringBody(parameter.getValue(),
                                    "text/plain; charset=UTF-8", Charset.forName("UTF-8"));
                            me.addPart(parameter.getName(), body);
                        }
                    }
                    post.setEntity(me);
                }
            }
            post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
            commonsRequest = post;
        } else if (req.getMethod() == RequestMethod.DELETE) {
            commonsRequest = new HttpDelete(resolved_url);
        } else if (req.getMethod() == RequestMethod.HEAD) {
            commonsRequest = new HttpHead(resolved_url);
        } else if (req.getMethod() == RequestMethod.PUT) {
            commonsRequest = new HttpPut(resolved_url);
        } else
            throw new AssertionError();
        final Map<String, String> headers = req.getRequestHeaders();
        for (final String headerName : headers.keySet()) {
            commonsRequest.addHeader(headerName, headers.get(headerName));
        }
        String authorizationHeader;
        if (req.getAuthorization() != null
                && (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req)) != null) {
            commonsRequest.addHeader("Authorization", authorizationHeader);
        }
        //if (resolved_host != null && !host.equals(resolved_host)) {
        //commonsRequest.addHeader("Host", host);
        //}
        final ApacheHttpClientHttpResponseImpl res = new ApacheHttpClientHttpResponseImpl(
                client.execute(commonsRequest), conf);
        final int statusCode = res.getStatusCode();
        if (statusCode < OK && statusCode > ACCEPTED)
            throw new TwitterException(res.asString(), res);
        return res;
    } catch (final IOException e) {
        throw new TwitterException(e);
    }
}

From source file:de.e7o.caldav.caldav.Connection.java

public InputStream request(String extUri, String requestMethod, String bodyData, String[]... additionalHeaders)
        throws Exception {
    int i;/*from ww w.j  a  v a  2  s .co m*/

    // Pre
    HttpClient httpclient = new DefaultHttpClient();
    HttpAny ha = new HttpAny(base.baseUri + extUri);
    ha.setMethod(requestMethod);

    // Headers
    for (i = 0; i < additionalHeaders.length; i++) {
        ha.addHeader(additionalHeaders[i][0], additionalHeaders[i][1]);
    }

    // Body
    ha.setEntity(new StringEntity(bodyData));

    // Authentication
    URL url = new URL(base.baseUri);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.authInfo.getUserName(),
            this.authInfo.getPassword());
    ((AbstractHttpClient) httpclient).getCredentialsProvider()
            .setCredentials(new AuthScope(url.getHost(), 80, null, "Basic"), credentials);

    // Send request
    HttpResponse httpresp = httpclient.execute(ha);

    // Remember state
    lastCode = httpresp.getStatusLine().getStatusCode();
    lastHeaders = httpresp.getAllHeaders();

    // Done - return InputStream
    HttpEntity httpent = httpresp.getEntity();
    return httpent.getContent();
}

From source file:com.qut.middleware.esoemanager.manager.logic.impl.ServiceCryptoImpl.java

private String generateSubjectDN(String service) {
    try {// w w  w .  jav a  2 s. c  o  m
        String result = new String();
        URL serviceURL = new URL(service);
        String[] components = serviceURL.getHost().split("\\.");
        for (String component : components) {
            if (result.length() != 0)
                result = result + ",";

            result = result + "dc=" + component;
        }
        return result;
    } catch (MalformedURLException e) {
        this.logger.error("Error attempting to generate certificate subjectDN " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        return "dc=" + service;
    }
}

From source file:org.talend.components.dataprep.connection.DataPrepConnectionHandler.java

private String requestEncoding() throws IOException {
    URI uri;/*from w  w  w  .j a v  a 2 s .  co m*/
    try {
        URL localUrl = new URL(url);
        uri = new URI(localUrl.getProtocol(), null, localUrl.getHost(), localUrl.getPort(), "/api/datasets",
                "name=" + dataSetName + "&tag=components", null);
        LOGGER.debug("Request is: {}", uri);
    } catch (MalformedURLException | URISyntaxException e) {
        LOGGER.debug(messages.getMessage("error.wrongInputParameters", e));
        throw new IOException(messages.getMessage("error.wrongInputParameters", e));
    }
    return uri.toString();
}

From source file:org.apache.nifi.elasticsearch.ElasticSearchClientServiceImpl.java

private void setupClient(ConfigurationContext context) throws MalformedURLException, InitializationException {
    final String hosts = context.getProperty(HTTP_HOSTS).evaluateAttributeExpressions().getValue();
    String[] hostsSplit = hosts.split(",[\\s]*");
    this.url = hostsSplit[0];
    final SSLContextService sslService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final String username = context.getProperty(USERNAME).evaluateAttributeExpressions().getValue();
    final String password = context.getProperty(PASSWORD).evaluateAttributeExpressions().getValue();

    final Integer connectTimeout = context.getProperty(CONNECT_TIMEOUT).asInteger();
    final Integer readTimeout = context.getProperty(SOCKET_TIMEOUT).asInteger();
    final Integer retryTimeout = context.getProperty(RETRY_TIMEOUT).asInteger();

    HttpHost[] hh = new HttpHost[hostsSplit.length];
    for (int x = 0; x < hh.length; x++) {
        URL u = new URL(hostsSplit[x]);
        hh[x] = new HttpHost(u.getHost(), u.getPort(), u.getProtocol());
    }/* w w  w .ja  v  a 2s .c om*/

    final SSLContext sslContext;
    try {
        sslContext = (sslService != null && sslService.isKeyStoreConfigured()
                && sslService.isTrustStoreConfigured()) ? buildSslContext(sslService) : null;
    } catch (IOException | CertificateException | NoSuchAlgorithmException | UnrecoverableKeyException
            | KeyStoreException | KeyManagementException e) {
        getLogger().error("Error building up SSL Context from the supplied configuration.", e);
        throw new InitializationException(e);
    }

    RestClientBuilder builder = RestClient.builder(hh).setHttpClientConfigCallback(httpClientBuilder -> {
        if (sslContext != null) {
            httpClientBuilder = httpClientBuilder.setSSLContext(sslContext);
        }

        if (username != null && password != null) {
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
            httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        return httpClientBuilder;
    }).setRequestConfigCallback(requestConfigBuilder -> {
        requestConfigBuilder.setConnectTimeout(connectTimeout);
        requestConfigBuilder.setSocketTimeout(readTimeout);
        return requestConfigBuilder;
    }).setMaxRetryTimeoutMillis(retryTimeout);

    this.client = builder.build();
    this.highLevelClient = new RestHighLevelClient(client);
}

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

public void put(String targetLocation, File file, String username, String password) throws TransportException {

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

    PostMethod post = new PostMethod(targetLocation);

    //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   www .  jav  a 2s . c  o  m*/

        Part[] parts = { new FilePart("userfile", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        //Set the HTTP 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);
        }

        // This line makes the HTTP call
        int status = client.executeMethod(post);

        // I've noticed on Windows (at least) that PHP seems to fail when moving files on the first attempt
        // The second attempt works so lets just do that
        if (status == HttpStatus.SC_OK && post.getResponseBodyAsString().equals("FILE_WASNT_MOVED")) {
            status = client.executeMethod(post);
        }

        if (status != HttpStatus.SC_OK) {
            throw new TransportException(
                    "There's been some kind of problem uploading a file to 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 uploading a file to the HTTP server.\n\nThe error message is ["
                            + post.getResponseBodyAsString() + "]");
        }

    } catch (FileNotFoundException e) {
        throw new TransportException(e);
    } 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:jenkins.security.Security637Test.java

@Test
@Issue("SECURITY-637")
public void urlSafeDeserialization_inXStreamContext() {
    rr.addStep(new Statement() {
        @Override//from w ww.  ja  v  a2  s.co m
        public void evaluate() throws Exception {
            FreeStyleProject project = rr.j.createFreeStyleProject("project-with-url");
            URLJobProperty URLJobProperty = new URLJobProperty(
                    // url to be wrapped
                    new URL("https://www.google.com/"),
                    // safe url, not required to be wrapped
                    new URL("https", null, -1, "", null));
            project.addProperty(URLJobProperty);

            project.save();
        }
    });

    rr.addStep(new Statement() {
        @Override
        public void evaluate() throws Exception {
            FreeStyleProject project = rr.j.jenkins.getItemByFullName("project-with-url",
                    FreeStyleProject.class);
            assertNotNull(project);

            Field handlerField = URL.class.getDeclaredField("handler");
            handlerField.setAccessible(true);

            URLJobProperty urlJobProperty = project.getProperty(URLJobProperty.class);
            for (URL url : urlJobProperty.urlSet) {
                URLStreamHandler handler = (URLStreamHandler) handlerField.get(url);
                if (StringUtils.isEmpty(url.getHost())) {
                    assertThat(handler.getClass().getName(), not(containsString("SafeURLStreamHandler")));
                } else {
                    assertThat(handler.getClass().getName(), containsString("SafeURLStreamHandler"));
                }
            }
        }
    });
}

From source file:com.predic8.membrane.core.rules.SOAPProxy.java

/**
 * @return error or null for success/*from   w ww . j  a  va2 s  . c o  m*/
 */
private void parseWSDL() throws Exception {
    WSDLParserContext ctx = new WSDLParserContext();
    ctx.setInput(ResolverMap.combine(router.getBaseLocation(), wsdl));
    try {
        WSDLParser wsdlParser = new WSDLParser();
        wsdlParser.setResourceResolver(resolverMap.toExternalResolver().toExternalResolver());

        Definitions definitions = wsdlParser.parse(ctx);

        List<Service> services = definitions.getServices();
        if (services.size() != 1)
            throw new IllegalArgumentException("There are " + services.size()
                    + " services defined in the WSDL, but exactly 1 is required for soapProxy.");
        Service service = services.get(0);

        if (StringUtils.isEmpty(name))
            name = StringUtils.isEmpty(service.getName()) ? definitions.getName() : service.getName();

        List<Port> ports = service.getPorts();
        Port port = selectPort(ports, portName);

        String location = port.getAddress().getLocation();
        if (location == null)
            throw new IllegalArgumentException("In the WSDL, there is no @location defined on the port.");
        try {
            URL url = new URL(location);
            target.setHost(url.getHost());
            if (url.getPort() != -1)
                target.setPort(url.getPort());
            else
                target.setPort(url.getDefaultPort());
            if (key.getPath() == null) {
                key.setUsePathPattern(true);
                key.setPathRegExp(false);
                key.setPath(url.getPath());
            } else {
                targetPath = url.getPath();
            }
            if (location.startsWith("https")) {
                SSLParser sslOutboundParser = new SSLParser();
                target.setSslParser(sslOutboundParser);
            }
            ((ServiceProxyKey) key).setMethod("*");
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("WSDL endpoint location '" + location + "' is not an URL.", e);
        }
        return;
    } catch (Exception e) {
        Throwable f = e;
        while (f.getCause() != null && !(f instanceof ResourceRetrievalException))
            f = f.getCause();
        if (f instanceof ResourceRetrievalException) {
            ResourceRetrievalException rre = (ResourceRetrievalException) f;
            if (rre.getStatus() >= 400)
                throw rre;
            Throwable cause = rre.getCause();
            if (cause != null) {
                if (cause instanceof UnknownHostException)
                    throw (UnknownHostException) cause;
                else if (cause instanceof ConnectException)
                    throw (ConnectException) cause;
            }
        }
        throw new IllegalArgumentException("Could not download the WSDL '" + wsdl + "'.", e);
    }
}

From source file:com.cloudant.http.interceptors.CookieInterceptor.java

private String getCookie(URL url, HttpConnectionInterceptorContext context) {
    try {//from ww  w .ja  va  2  s .  c  o m
        URL sessionURL = new URL(
                String.format("%s://%s:%d/_session", url.getProtocol(), url.getHost(), url.getPort()));

        HttpConnection conn = Http.POST(sessionURL, "application/x-www-form-urlencoded");
        conn.setRequestBody(sessionRequestBody);

        //when we request the session we need all interceptors except this one

        conn.requestInterceptors.addAll(context.connection.requestInterceptors);
        conn.requestInterceptors.remove(this);
        conn.responseInterceptors.addAll(context.connection.responseInterceptors);
        conn.responseInterceptors.remove(this);

        HttpURLConnection connection = conn.execute().getConnection();
        String cookieHeader = connection.getHeaderField("Set-Cookie");
        int responseCode = connection.getResponseCode();

        if (responseCode / 100 == 2) {

            if (sessionHasStarted(connection.getInputStream())) {
                return cookieHeader.substring(0, cookieHeader.indexOf(";"));
            } else {
                return null;
            }

        } else if (responseCode == 401) {
            shouldAttemptCookieRequest = false;
            logger.severe("Credentials are incorrect, cookie authentication will not be"
                    + " attempted again by this interceptor object");
        } else if (responseCode / 100 == 5) {
            logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, cookie auth",
                    responseCode);
        } else {
            // catch any other response code
            logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, "
                    + "cookie authentication will not be attempted again", responseCode);
            shouldAttemptCookieRequest = false;
        }

    } catch (MalformedURLException e) {
        logger.log(Level.SEVERE, "Failed to create URL for _session endpoint", e);
    } catch (UnsupportedEncodingException e) {
        logger.log(Level.SEVERE, "Failed to encode cookieRequest body", e);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Failed to read cookie response header", e);
    }
    return null;
}