Example usage for java.net URL getPort

List of usage examples for java.net URL getPort

Introduction

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

Prototype

public int getPort() 

Source Link

Document

Gets the port number of this URL .

Usage

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

private String requestEncoding() throws IOException {
    URI uri;/*w ww.  j  a  va 2 s .com*/
    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:com.cloudant.http.interceptors.CookieInterceptor.java

private String getCookie(URL url, HttpConnectionInterceptorContext context) {
    try {/*from www.  j a 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;
}

From source file:de.juwimm.cms.common.http.HttpClientWrapper.java

public void setHostConfiguration(HttpClient client, URL targetURL) {
    int port = targetURL.getPort();
    String host = targetURL.getHost();
    HostConfiguration config = hostMap.get(host + ":" + port);
    if (config == null) {
        config = new HostConfiguration();
        if (port == -1) {
            if (targetURL.getProtocol().equalsIgnoreCase("https")) {
                port = 443;/*ww w . j  a va 2  s.  c  om*/
            } else {
                port = 80;
            }
        }
        config.setHost(host, port, targetURL.getProtocol());
    }
    // in the meantime HttpProxyUser and HttpProxyPasword might have changed
    // (DlgUsernamePassword) or now trying NTLM instead of BASE
    // authentication
    if (getHttpProxyHost() != null && getHttpProxyPort() != null && getHttpProxyHost().length() > 0
            && getHttpProxyPort().length() > 0) {
        client.getParams().setAuthenticationPreemptive(true);
        int proxyPort = new Integer(getHttpProxyPort()).intValue();
        config.setProxy(getHttpProxyHost(), proxyPort);
        if (getHttpProxyUser() != null && getHttpProxyUser().length() > 0) {
            Credentials proxyCred = null;
            if (isUseNTproxy()) {
                proxyCred = new NTCredentials(getHttpProxyUser(), getHttpProxyPassword(), getHttpProxyHost(),
                        "");
            } else {
                proxyCred = new UsernamePasswordCredentials(getHttpProxyUser(), getHttpProxyPassword());
            }
            client.getState().setProxyCredentials(AUTHSCOPE_ANY, proxyCred);

        }
    }
    hostMap.put(host + ":" + port, config);
    client.setHostConfiguration(config);

}

From source file:net.java.sip.communicator.service.httputil.HttpUtils.java

/**
 * Posting form to <tt>address</tt>. For submission we use POST method
 * which is "application/x-www-form-urlencoded" encoded.
 * @param httpClient the http client/*from  w  w w.j  av a 2s  .c o m*/
 * @param postMethod the post method
 * @param address HTTP address.
 * @param formParamNames the parameter names to include in post.
 * @param formParamValues the corresponding parameter values to use.
 * @param usernameParamIx the index of the username parameter in the
 * <tt>formParamNames</tt> and <tt>formParamValues</tt>
 * if any, otherwise -1.
 * @param passwordParamIx the index of the password parameter in the
 * <tt>formParamNames</tt> and <tt>formParamValues</tt>
 * if any, otherwise -1.
 * @param headerParamNames additional header name to include
 * @param headerParamValues corresponding header value to include
 * @return the result or null if send was not possible or
 * credentials ask if any was canceled.
 */
private static HttpEntity postForm(DefaultHttpClient httpClient, HttpPost postMethod, String address,
        ArrayList<String> formParamNames, ArrayList<String> formParamValues, int usernameParamIx,
        int passwordParamIx, RedirectHandler redirectHandler, List<String> headerParamNames,
        List<String> headerParamValues) throws Throwable {
    // if we have username and password in the parameters, lets
    // retrieve their values
    // if there are already filled skip asking the user
    Credentials creds = null;
    if (usernameParamIx != -1 && usernameParamIx < formParamNames.size() && passwordParamIx != -1
            && passwordParamIx < formParamNames.size()
            && (formParamValues.get(usernameParamIx) == null
                    || formParamValues.get(usernameParamIx).length() == 0)
            && (formParamValues.get(passwordParamIx) == null
                    || formParamValues.get(passwordParamIx).length() == 0)) {
        URL url = new URL(address);
        HTTPCredentialsProvider prov = (HTTPCredentialsProvider) httpClient.getCredentialsProvider();

        // don't allow empty username
        while (creds == null || creds.getUserPrincipal() == null
                || StringUtils.isNullOrEmpty(creds.getUserPrincipal().getName())) {
            creds = prov.getCredentials(new AuthScope(url.getHost(), url.getPort()));

            // it was user canceled lets stop processing
            if (creds == null && !prov.retry()) {
                return null;
            }
        }
    }

    // construct the name value pairs we will be sending
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    // there can be no params
    if (formParamNames != null) {
        for (int i = 0; i < formParamNames.size(); i++) {
            // we are on the username index, insert retrieved username value
            if (i == usernameParamIx && creds != null) {
                parameters
                        .add(new BasicNameValuePair(formParamNames.get(i), creds.getUserPrincipal().getName()));
            } // we are on the password index, insert retrieved password val
            else if (i == passwordParamIx && creds != null) {
                parameters.add(new BasicNameValuePair(formParamNames.get(i), creds.getPassword()));
            } else // common name value pair, all info is present
            {
                parameters.add(new BasicNameValuePair(formParamNames.get(i), formParamValues.get(i)));
            }
        }
    }

    // our custom strategy, will check redirect handler should we redirect
    // if missing will use the default handler
    httpClient.setRedirectStrategy(new CustomRedirectStrategy(redirectHandler, parameters));

    // Uses String UTF-8 to keep compatible with android version and
    // older versions of the http client libs, as the one used
    // in debian (4.1.x)
    String s = URLEncodedUtils.format(parameters, "UTF-8");
    StringEntity entity = new StringEntity(s, "UTF-8");
    // set content type to "application/x-www-form-urlencoded"
    entity.setContentType(URLEncodedUtils.CONTENT_TYPE);

    // insert post values encoded.
    postMethod.setEntity(entity);

    if (headerParamNames != null) {
        for (int i = 0; i < headerParamNames.size(); i++) {
            postMethod.addHeader(headerParamNames.get(i), headerParamValues.get(i));
        }
    }

    // execute post
    return executeMethod(httpClient, postMethod, redirectHandler, parameters);
}

From source file:org.picketbox.test.authentication.http.jetty.DelegatingSecurityFilterHTTPBasicUnitTestCase.java

@Test
public void testBasicAuth() throws Exception {
    URL url = new URL(urlStr);

    DefaultHttpClient httpclient = null;
    try {//  w w  w .j  a  v a2 s .c om
        String user = "Aladdin";
        String pass = "Open Sesame";

        httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(user, pass));

        HttpGet httpget = new HttpGet(url.toExternalForm());

        System.out.println("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(200, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.apache.cxf.fediz.service.idp.beans.STSClientAction.java

public void setWsdlLocation(String wsdlLocation) {
    this.wsdlLocation = wsdlLocation;
    try {//  w w w  . j  a  va 2s.  c om
        URL url = new URL(wsdlLocation);
        isPortSet = url.getPort() > 0;
        if (!isPortSet) {
            LOG.info("Port is 0 for 'wsdlLocation'. Port evaluated when processing first request.");
        }
    } catch (MalformedURLException e) {
        LOG.error("Invalid Url '" + wsdlLocation + "': " + e.getMessage());
    }
}

From source file:com.allblacks.utils.web.HttpUtil.java

/**
 * Gets data from URL as byte[] throws {@link RuntimeException} If anything
 * goes wrong/*from   ww  w  . jav a2  s.c om*/
 * 
 * @return The content of the URL as a byte[]
 * @throws java.io.IOException
 */
public byte[] getDataAsByteArray(String url, CredentialsProvider cp) throws IOException {
    HttpClient httpClient = getNewHttpClient();

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

    HttpContext credContext = new BasicHttpContext();
    credContext.setAttribute(ClientContext.CREDS_PROVIDER, cp);

    HttpGet job = new HttpGet(url);
    HttpResponse response = httpClient.execute(host, job, credContext);

    HttpEntity entity = response.getEntity();
    return EntityUtils.toByteArray(entity);
}

From source file:com.allblacks.utils.web.HttpUtil.java

/**
 * Gets data from URL as char[] throws {@link RuntimeException} If anything
 * goes wrong/*  w ww.  ja v a  2s.  c  om*/
 * 
 * @param url the url from which to retrieve the data.
 * @param cp the credential provider
 * 
 * @return The content of the URL as a char[]
 * @throws java.io.IOException
 */
public synchronized char[] getDataAsCharArray(String url, CredentialsProvider cp) throws IOException {
    HttpClient httpClient = getNewHttpClient();

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

    HttpContext credContext = new BasicHttpContext();
    credContext.setAttribute(ClientContext.CREDS_PROVIDER, cp);

    HttpGet job = new HttpGet(url);
    HttpResponse response = httpClient.execute(host, job, credContext);

    HttpEntity entity = response.getEntity();
    return EntityUtils.toString(entity).toCharArray();
}

From source file:org.uiautomation.ios.server.grid.RegistrationRequest.java

public void registerToHub() {

    HttpClient client = new DefaultHttpClient();
    try {/*  w w w  . jav a 2s.  c  om*/
        URL registration = new URL(hubURL);

        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",
                registration.toExternalForm());

        String json = getJSONRequest().toString();

        r.setEntity(new StringEntity(json));

        HttpHost host = new HttpHost(registration.getHost(), registration.getPort());
        HttpResponse response = client.execute(host, r);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Error sending the registration request.");
        }
    } catch (Exception e) {
        throw new WebDriverException("Error sending the registration request.", e);
    }

}

From source file:org.whispersystems.mmsmonster.mms.MmsConnection.java

protected CloseableHttpClient constructHttpClient() throws IOException {
    RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000)
            .setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build();

    URL mmsc = new URL(apn.getMmsc());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    if (apn.hasAuthentication()) {
        credsProvider.setCredentials(/* ww w  .  ja  va 2s .c  o  m*/
                new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
    }

    return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
            .setRedirectStrategy(new LaxRedirectStrategy()).setUserAgent("Android-Mms/2.0")
            .setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config)
            .setDefaultCredentialsProvider(credsProvider).build();
}