Example usage for java.net URI getHost

List of usage examples for java.net URI getHost

Introduction

In this page you can find the example usage for java.net URI getHost.

Prototype

public String getHost() 

Source Link

Document

Returns the host component of this URI.

Usage

From source file:com.zimbra.qa.unittest.TestCollectConfigServletsAccess.java

/**
 * Verify that delegated admin canNOT access servlet at /service/collectldapconfig/
 * @throws Exception/*from   w ww  .  ja va2s  . c o m*/
 */
@Test
public void testLDAPConfigDelegatedAdmin() throws Exception {
    ZAuthToken at = TestUtil.getAdminSoapTransport(TEST_ADMIN_NAME, PASSWORD).getAuthToken();
    URI servletURI = new URI(getLDAPConfigServletUrl());
    HttpState initialState = HttpClientUtil.newHttpState(at, servletURI.getHost(), true);
    HttpClient restClient = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    restClient.setState(initialState);
    restClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    GetMethod get = new GetMethod(servletURI.toString());
    int statusCode = HttpClientUtil.executeMethod(restClient, get);
    assertEquals("This request should NOT succeed. Getting status code " + statusCode,
            HttpStatus.SC_UNAUTHORIZED, statusCode);
}

From source file:com.netflix.spinnaker.halyard.config.validate.v1.security.PublicServiceValidator.java

@Override
public void validate(ConfigProblemSetBuilder p, PublicService n) {
    String overrideBaseUrl = n.getOverrideBaseUrl();
    if (!StringUtils.isEmpty(overrideBaseUrl)) {
        try {//w ww. j a  v  a 2s. c o m
            URI uri = new URIBuilder(overrideBaseUrl).build();

            if (StringUtils.isEmpty(uri.getScheme())) {
                p.addProblem(ERROR, "You must supply a URI scheme, e.g. 'http://' or 'https://'");
            }

            if (StringUtils.isEmpty(uri.getHost())) {
                p.addProblem(ERROR, "You must supply a URI host");
            }
        } catch (URISyntaxException e) {
            p.addProblem(ERROR, "Invalid base URL: " + e.getMessage());
        }
    }
}

From source file:com.snowplowanalytics.refererparser.Parser.java

public Referer parse(URI refererUri, URI pageUri) {
    return parse(refererUri, pageUri.getHost());
}

From source file:com.grendelscan.commons.http.apache_overrides.client.CustomHttpClient.java

public String getRequestHeadString(final HttpHost originalTarget, final HttpRequest request,
        final HttpContext originalContext) throws IOException, HttpException {
    HttpContext context = originalContext;
    HttpHost target = originalTarget;// w  ww.  ja v a2s .c o m

    if (context == null) {
        context = createHttpContext();
    }

    if (target == null) {
        URI uri = ((HttpUriRequest) request).getURI();
        target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    }
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
    prepareRequest(request);

    getHttpProcessor().process(request, context);

    String requestString = request.getRequestLine().toString() + "\n";
    for (Header header : request.getAllHeaders()) {
        requestString += header.toString() + "\n";
    }
    return requestString;
}

From source file:org.springframework.ws.transport.http.HttpComponentsMessageSender.java

/**
 * Sets the maximum number of connections per host for the underlying HttpClient. The maximum number of connections
 * per host can be set in a form accepted by the {@code java.util.Properties} class, like as follows:
 * <p/>// w  ww .  j a va2  s.c  o  m
 * <pre>
 * https://www.example.com=1
 * http://www.example.com:8080=7
 * http://www.springframework.org=10
 * </pre>
 * <p/>
 * The host can be specified as a URI (with scheme and port).
 *
 * @param maxConnectionsPerHost a properties object specifying the maximum number of connection
 * @see org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager#setMaxForRoute(org.apache.http.conn.routing.HttpRoute,
 *      int)
 */
public void setMaxConnectionsPerHost(Map<String, String> maxConnectionsPerHost) throws URISyntaxException {
    ClientConnectionManager connectionManager = getHttpClient().getConnectionManager();
    if (!(connectionManager instanceof ThreadSafeClientConnManager)) {
        throw new IllegalArgumentException(
                "maxConnectionsPerHost is not supported on " + connectionManager.getClass().getName() + ". Use "
                        + ThreadSafeClientConnManager.class.getName() + " instead");
    }

    for (Object o : maxConnectionsPerHost.keySet()) {
        String host = (String) o;
        URI uri = new URI(host);
        HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        int maxHostConnections = Integer.parseInt(maxConnectionsPerHost.get(host));
        ((ThreadSafeClientConnManager) connectionManager).setMaxForRoute(new HttpRoute(httpHost),
                maxHostConnections);
    }
}

From source file:org.wso2.carbon.http2.transport.Http2TransportSender.java

/**
 * Handels requests come from Axis2 Engine
 *
 * @param msgCtx//from w ww  .j a va2 s . c  o  m
 * @param targetEPR
 * @param trpOut
 * @throws AxisFault
 */
public void sendMessage(MessageContext msgCtx, String targetEPR, OutTransportInfo trpOut) throws AxisFault {
    try {
        if (targetEPR.toLowerCase().contains("http2://")) {
            targetEPR = targetEPR.replaceFirst("http2://", "http://");
        } else if (targetEPR.toLowerCase().contains("https2://")) {
            targetEPR = targetEPR.replaceFirst("https2://", "https://");
        }
        URI uri = new URI(targetEPR);
        String scheme = uri.getScheme() != null ? uri.getScheme() : "http";
        String hostname = uri.getHost();
        int port = uri.getPort();
        if (port == -1) {
            // use default
            if ("http".equals(scheme)) {
                port = 80;
            } else if ("https".equals(scheme)) {
                port = 443;
            }
        }
        HttpHost target = new HttpHost(hostname, port, scheme);
        boolean secure = "https".equals(target.getSchemeName());

        HttpHost proxy = proxyConfig.selectProxy(target);

        msgCtx.setProperty(PassThroughConstants.PROXY_PROFILE_TARGET_HOST, target.getHostName());

        HttpRoute route;
        if (proxy != null) {
            route = new HttpRoute(target, null, proxy, secure);
        } else {
            route = new HttpRoute(target, null, secure);
        }
        Http2TargetRequestUtil util = new Http2TargetRequestUtil(targetConfiguration, route);
        msgCtx.setProperty(Http2Constants.PASSTHROUGH_TARGET, util);

        if (msgCtx.getProperty(PassThroughConstants.PASS_THROUGH_PIPE) == null) {
            Pipe pipe = new Pipe(targetConfiguration.getBufferFactory().getBuffer(), "Test",
                    targetConfiguration);
            msgCtx.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe);
            msgCtx.setProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED, Boolean.TRUE);
        }

        Http2ClientHandler clientHandler = connectionFactory.getChannelHandler(target);

        String tenantDomain = (msgCtx.getProperty(MultitenantConstants.TENANT_DOMAIN) == null) ? null
                : (String) msgCtx.getProperty(MultitenantConstants.TENANT_DOMAIN);
        String dispatchSequence = (msgCtx.getProperty(Http2Constants.HTTP2_DISPATCH_SEQUENCE) == null) ? null
                : (String) msgCtx.getProperty(Http2Constants.HTTP2_DISPATCH_SEQUENCE);
        String errorSequence = (msgCtx.getProperty(Http2Constants.HTTP2_ERROR_SEQUENCE) == null) ? null
                : (String) msgCtx.getProperty(Http2Constants.HTTP2_ERROR_SEQUENCE);
        InboundResponseSender responseSender = (msgCtx
                .getProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER) == null) ? null
                        : (InboundResponseSender) msgCtx
                                .getProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER);
        boolean serverPushEnabled = (msgCtx
                .getProperty(Http2Constants.HTTP2_PUSH_PROMISE_REQEUST_ENABLED) == null) ? false
                        : (boolean) msgCtx.getProperty(Http2Constants.HTTP2_PUSH_PROMISE_REQEUST_ENABLED);

        clientHandler.setResponseReceiver(tenantDomain, dispatchSequence, errorSequence, responseSender,
                targetConfiguration, serverPushEnabled);
        clientHandler.channelWrite(msgCtx);

    } catch (URISyntaxException e) {
        log.error("Error parsing the http2 endpoint url");
        throw new AxisFault(e.getMessage());
    }
}

From source file:com.esri.geoportal.commons.http.BotsHttpClient.java

private String getProtocolHostPort(URI u) throws MalformedURLException {
    return String.format("%s://%s%s", u.getScheme(), u.getHost(), u.getPort() >= 0 ? ":" + u.getPort() : "");
}

From source file:com.github.lpezet.antiope.dao.DefaultHttpRequestFactory.java

/** Configures the headers in the specified Apache HTTP request. */
private void configureHeaders(HttpRequestBase pHttpRequest, Request<?> pRequest, ExecutionContext pContext,
        APIConfiguration pConfiguration) {
    /*//from  w  w  w. j  a v  a2s  .  c  o m
     * Apache HttpClient omits the port number in the Host header (even if
     * we explicitly specify it) if it's the default port for the protocol
     * in use. To ensure that we use the same Host header in the request and
     * in the calculated string to sign (even if Apache HttpClient changed
     * and started honoring our explicit host with endpoint), we follow this
     * same behavior here and in the QueryString signer.
     */
    URI endpoint = pRequest.getEndpoint();
    String hostHeader = endpoint.getHost();
    if (HttpUtils.isUsingNonDefaultPort(endpoint)) {
        hostHeader += COLON + endpoint.getPort();
    }
    pHttpRequest.addHeader(HOST, hostHeader);

    // Copy over any other headers already in our request
    for (Entry<String, String> entry : pRequest.getHeaders().entrySet()) {
        /*
         * HttpClient4 fills in the Content-Length header and complains if
         * it's already present, so we skip it here. We also skip the Host
         * header to avoid sending it twice, which will interfere with some
         * signing schemes.
         */
        if (entry.getKey().equalsIgnoreCase(CONTENT_LENGTH) || entry.getKey().equalsIgnoreCase(HOST))
            continue;

        pHttpRequest.addHeader(entry.getKey(), entry.getValue());
    }

    /* Set content type and encoding */
    if (pHttpRequest.getHeaders(CONTENT_TYPE) == null || pHttpRequest.getHeaders(CONTENT_TYPE).length == 0) {
        pHttpRequest.addHeader(CONTENT_TYPE,
                "application/x-www-form-urlencoded; " + "charset=" + DEFAULT_ENCODING.toLowerCase());
    }

    // Override the user agent string specified in the client params if the
    // context requires it
    if (pContext != null && pContext.getContextUserAgent() != null) {
        pHttpRequest.addHeader(USER_AGENT,
                createUserAgentString(pConfiguration, pContext.getContextUserAgent()));
    }
}

From source file:net.ripe.rpki.validator.util.UriToFileMapper.java

public File map(URI uri, ValidationResult result) {
    Validate.notNull(result);//from w w w  .  j av  a 2  s  .  c  o m
    Validate.notNull(uri);
    result.rejectIfFalse(RSYNC_SCHEME.equalsIgnoreCase(uri.getScheme()), VALIDATOR_URI_RSYNC_SCHEME,
            uri.toString());
    result.rejectIfNull(uri.getHost(), VALIDATOR_URI_HOST, uri.toString());
    result.rejectIfNull(uri.getRawPath(), VALIDATOR_URI_PATH, uri.toString());
    String s = uri.toString();
    result.rejectIfTrue(s.contains("/../") || s.endsWith("/.."), VALIDATOR_URI_SAFETY, uri.toString());
    if (result.hasFailureForCurrentLocation()) {
        return null;
    }
    return new File(new File(targetDirectory, getHostPortAsString(uri)), uri.getRawPath());
}

From source file:org.attribyte.api.pubsub.impl.server.NotificationMetricsServlet.java

/**
 * Gets a metrics prefix for a topic.// w w  w .j  a va2  s.co m
 * @param topicId The topic id.
 * @param joinString The string used to join parts of the topic URI.
 * @param allowSlash Is '/' allowed in the prefix?
 * @return The prefix.
 */
private String getTopicPrefix(final long topicId, final String joinString, final boolean allowSlash) {
    try {
        Topic topic = endpoint.getDatastore().getTopic(topicId);
        if (topic != null) {
            URI uri = new URI(topic.getURL());
            List<String> components = Lists.newArrayListWithCapacity(4);
            if (uri.getHost() != null)
                components.add(uri.getHost());
            if (uri.getPort() > 0)
                components.add(Integer.toString(uri.getPort()));
            String path = uri.getPath();
            if (path != null) {
                if (path.startsWith("/"))
                    path = path.substring(1);
                if (path.endsWith("/"))
                    path = path.substring(0, path.length() - 1);
                components.add(path);
            }
            String prefix = Joiner.on(joinString).skipNulls().join(components);
            if (!allowSlash)
                prefix = prefix.replace('/', '_');
            return prefix;
        } else {
            return null;
        }
    } catch (DatastoreException de) {
        log("Unable to resolve topic", de);
        return null;
    } catch (URISyntaxException use) {
        return null;
    }
}