Example usage for java.net URI getPort

List of usage examples for java.net URI getPort

Introduction

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

Prototype

public int getPort() 

Source Link

Document

Returns the port number of this URI.

Usage

From source file:com.ksc.http.apache.request.impl.ApacheHttpRequestFactory.java

private String getHostHeaderValue(final URI endpoint) {
    /*/*www . j a va2s.  com*/
     * 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.
     */
    return SdkHttpUtils.isUsingNonDefaultPort(endpoint) ? endpoint.getHost() + ":" + endpoint.getPort()
            : endpoint.getHost();
}

From source file:edu.umn.cs.spatialHadoop.nasa.HTTPFileSystem.java

@Override
public void initialize(URI uri, Configuration conf) throws IOException { // get
    super.initialize(uri, conf);
    // get host information from uri (overrides info in conf)
    String host = uri.getHost();/*w w w.j  a va 2s .  co m*/
    host = (host == null) ? conf.get("fs.http.host", null) : host;
    if (host == null) {
        throw new IOException("Invalid host specified");
    }
    conf.set("fs.http.host", host);

    // get port information from uri, (overrides info in conf)
    int port = uri.getPort();
    port = (port == -1) ? DEFAULT_PORT : port;
    conf.setInt("fs.http.host.port", port);

    setConf(conf);
    this.uri = uri;
    retries = conf.getInt(HTTP_RETRIES, 3);
}

From source file:com.ge.predix.test.utils.ZoneHelper.java

public String getZoneSpecificUrl(final String zoneId) {
    URI uri = null;
    String zoneurl = null;/* w  ww .jav a2 s  . c o  m*/
    try {
        uri = new URI(this.acsBaseUrl);
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    // if running locally, acsDomain is not needed in uri
    if (this.acsCFDomain == null || this.acsCFDomain.isEmpty()) {
        zoneurl = uri.getScheme() + "://" + zoneId + "." + this.cfBaseDomain;
    } else {
        zoneurl = uri.getScheme() + "://" + zoneId + "." + this.acsCFDomain + "." + this.cfBaseDomain;
    }
    if (uri.getPort() != -1) {
        zoneurl += ":" + uri.getPort();
    }
    return zoneurl;
}

From source file:com.github.parisoft.resty.request.Request.java

/**
 * Creates a request from a {@link URI}.<br>
 * The URI must conform the <a href=https://www.ietf.org/rfc/rfc2396.txt>RFC 2396</a> with the <i>path</i> and <i>query</i> properly encoded.<br>
 * <br>/* w  ww .  j a v  a 2 s. c o  m*/
 * For your convenience, call this constructor with the base address of your request - like {@literal <scheme>://<authority>} -
 * and use {@link #path(String...)} and {@link #query(String, String)} to configure the URI path and query respectively without worring about escape.<br>
 * <br>
 * As example, you can do<br>
 * <pre>
 * URI partialUri = new URI("http://some.domain.org:1234");
 * Request request = new Request(partialUri)
 *                       .path("any unescaped path")
 *                       .query("don't", "scape too");
 * </pre>
 * or
 * <pre>
 * URI fullUri = new URI("http://some.domain.org:1234/any%20unescaped%20path?don%27t=scape+too");
 * Request request = new Request(fullUri);
 * </pre>
 * <i>Note:</i> this is equivalent to {@link RESTy#request(URI)}
 *
 * @param uri A {@link URI} as defined by <a href=https://www.ietf.org/rfc/rfc2396.txt>RFC 2396</a>
 * @throws IllegalArgumentException If the URI is null
 */
public Request(URI uri) {
    if (uri == null) {
        throw new IllegalArgumentException("Cannot create a request: URI cannot be null");
    }

    path(emptyIfNull(uri.getPath()));

    try {
        query(URLEncodedUtils.parse(uri, UTF_8.name()));
        rootUri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null,
                uri.getFragment());
    } catch (Exception e) {
        throw new IllegalArgumentException("Cannot create a request: " + e.getMessage());
    }
}

From source file:org.dasein.cloud.ibm.sce.SCEMethod.java

protected @Nonnull HttpClient getClient() throws InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new SCEConfigException("No context was defined for this request");
    }//from   w w w  .java2s .  c o  m
    String endpoint = ctx.getEndpoint();

    if (endpoint == null) {
        throw new SCEConfigException("No cloud endpoint was defined");
    }
    boolean ssl = endpoint.startsWith("https");
    int targetPort;
    URI uri;

    try {
        uri = new URI(endpoint);
        targetPort = uri.getPort();
        if (targetPort < 1) {
            targetPort = (ssl ? 443 : 80);
        }
    } catch (URISyntaxException e) {
        throw new SCEConfigException(e);
    }
    HttpHost targetHost = new HttpHost(uri.getHost(), targetPort, uri.getScheme());
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "");

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    DefaultHttpClient client = new DefaultHttpClient(params);

    try {
        String userName = new String(ctx.getAccessPublic(), "utf-8");
        String password = new String(ctx.getAccessPrivate(), "utf-8");

        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(userName, password));
    } catch (UnsupportedEncodingException e) {
        throw new InternalException(e);
    }
    return client;
}

From source file:fr.ippon.wip.http.request.RequestBuilderFactory.java

/**
 * Return a request instance. The request type will be PostRequest if the
 * resource type is POST, GetRequest otherwise.
 * // w  w w .  j  a  va  2s . com
 * @param requestedURL
 *            request url
 * @param resourceType
 *            resource type, if any
 * @param httpMethod
 *            http method, if any
 * @param originalMap
 *            parameters map, if any
 * @return a implementation of Request
 */
public RequestBuilder getRequest(PortletRequest portletRequest, String requestedURL, ResourceType resourceType,
        HttpMethod httpMethod, Map<String, String[]> originalMap, boolean isMultipart) {
    URI uri = URI.create(requestedURL);
    String query = uri.getQuery();

    Multimap<String, String> parameterMap = ArrayListMultimap.create();
    if (originalMap != null)
        for (Entry<String, String[]> entry : originalMap.entrySet())
            for (String value : entry.getValue())
                parameterMap.put(entry.getKey(), value);

    if (!Strings.isNullOrEmpty(query)) {
        // hack; can't figure why separators are sometime "&" or "&amp;"...
        query = query.replaceAll("amp;", "");

        requestedURL = uri.getScheme() + "://" + uri.getHost()
                + (uri.getPort() == -1 ? "" : ":" + uri.getPort()) + uri.getPath();
        updateParameterMap(parameterMap, query);
    }

    if (isMultipart) {
        try {
            return new MultipartRequestBuilder(requestedURL, resourceType, (ActionRequest) portletRequest,
                    parameterMap);
        } catch (FileUploadException e) {
            e.printStackTrace();
            return null;
        }

    } else if (httpMethod == HttpMethod.POST)
        return new PostRequestBuilder(requestedURL, resourceType, parameterMap);
    else
        return new GetRequestBuilder(requestedURL, resourceType, parameterMap);
}

From source file:com.eucalyptus.http.MappingHttpRequest.java

/**
 * Constructor for outbound requests. //from  w w w.  j a  v  a2 s . c  o m
 */
public MappingHttpRequest(final HttpVersion httpVersion, final HttpMethod method,
        final ServiceConfiguration serviceConfiguration, final Object source) {
    super(httpVersion);
    this.method = method;
    URI fullUri = ServiceUris.internal(serviceConfiguration);
    this.uri = fullUri.toString();
    this.servicePath = fullUri.getPath();
    this.query = null;
    this.parameters = null;
    this.rawParameters = null;
    this.nonQueryParameterKeys = null;
    this.formFields = null;
    this.message = source;
    if (source instanceof BaseMessage)
        this.setCorrelationId(((BaseMessage) source).getCorrelationId());
    this.addHeader(HttpHeaders.Names.HOST, fullUri.getHost() + ":" + fullUri.getPort());
}

From source file:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java

private String append(String base, Map<String, ?> query, Map<String, String> keys, boolean fragment) {

    UriComponentsBuilder template = UriComponentsBuilder.newInstance();
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(base);
    URI redirectUri;
    try {/*w  w  w . j  a v a 2s. c  o  m*/
        // assume it's encoded to start with (if it came in over the wire)
        redirectUri = builder.build(true).toUri();
    } catch (Exception e) {
        // ... but allow client registrations to contain hard-coded non-encoded values
        redirectUri = builder.build().toUri();
        builder = UriComponentsBuilder.fromUri(redirectUri);
    }
    template.scheme(redirectUri.getScheme()).port(redirectUri.getPort()).host(redirectUri.getHost())
            .userInfo(redirectUri.getUserInfo()).path(redirectUri.getPath());

    if (fragment) {
        StringBuilder values = new StringBuilder();
        if (redirectUri.getFragment() != null) {
            String append = redirectUri.getFragment();
            values.append(append);
        }
        for (String key : query.keySet()) {
            if (values.length() > 0) {
                values.append("&");
            }
            String name = key;
            if (keys != null && keys.containsKey(key)) {
                name = keys.get(key);
            }
            values.append(name + "={" + key + "}");
        }
        if (values.length() > 0) {
            template.fragment(values.toString());
        }
        UriComponents encoded = template.build().expand(query).encode();
        builder.fragment(encoded.getFragment());
    } else {
        for (String key : query.keySet()) {
            String name = key;
            if (nonNull(keys) && keys.containsKey(key)) {
                name = keys.get(key);
            }
            template.queryParam(name, "{" + key + "}");
        }
        template.fragment(redirectUri.getFragment());
        UriComponents encoded = template.build().expand(query).encode();
        builder.query(encoded.getQuery());
    }

    return builder.build().toUriString();
}

From source file:com.tripit.auth.OAuthCredential.java

public boolean validateSignature(URI requestUri)
        throws URISyntaxException, UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
    List<NameValuePair> argList = URLEncodedUtils.parse(requestUri, "UTF-8");
    SortedMap<String, String> args = new TreeMap<String, String>();
    for (NameValuePair arg : argList) {
        args.put(arg.getName(), arg.getValue());
    }/*w  w  w  .j  a  va2s . c  o  m*/

    String signature = args.remove("oauth_signature");

    String baseUrl = new URI(requestUri.getScheme(), requestUri.getUserInfo(), requestUri.getAuthority(),
            requestUri.getPort(), requestUri.getPath(), null, requestUri.getFragment()).toString();

    return (signature != null && signature.equals(generateSignature(baseUrl, args)));
}

From source file:com.apigee.sdk.apm.http.impl.client.cache.CachingHttpClient.java

/**
 * @param request/*from  w w  w  .  jav a  2 s .  c om*/
 *            the request to execute
 * @param context
 *            the context to use for the execution, or <code>null</code> to
 *            use the default context
 * @return HttpResponse The cached entry or the result of a backend call
 * @throws IOException
 */
public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException {
    URI uri = request.getURI();
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    return execute(httpHost, request, context);
}