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:cm.aptoide.pt.RemoteInTab.java

private void downloadExtras(String srv) {
    String url = srv + REMOTE_EXTRAS_FILE;

    try {//from  w w w. j a  v  a 2 s .  c o  m
        FileOutputStream saveit = new FileOutputStream(LOCAL_PATH + REMOTE_EXTRAS_FILE);
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);
        DefaultHttpClient mHttpClient = new DefaultHttpClient(httpParameters);
        HttpGet mHttpGet = new HttpGet(url);

        String[] logins = null;
        logins = db.getLogin(srv);
        if (logins != null) {
            URL mUrl = new URL(url);
            mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mUrl.getHost(), mUrl.getPort()),
                    new UsernamePasswordCredentials(logins[0], logins[1]));
        }

        HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
        if (mHttpResponse.getStatusLine().getStatusCode() == 401) {
            /*Message msg = new Message();
            msg.obj = new String(srv);
            secure_error_handler.sendMessage(msg);*/
        } else {
            byte[] buffer = EntityUtils.toByteArray(mHttpResponse.getEntity());
            saveit.write(buffer);
        }
    } catch (UnknownHostException e) {
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }
}

From source file:com.cladonia.xngreditor.URLUtilities.java

/**
 * Decrypts the string and creates a URL.
 * /*from w w  w  .  j  a v  a  2 s .  c o  m*/
 * @param url the url.
 * 
 * @return the decrypted url or null if the url could not be constructed.
 */
public static URL decrypt(String string) {
    try {
        URL url = new URL(string);

        String password = getPassword(url);
        String username = getUsername(url);

        if (password != null) {
            password = StringUtilities.decrypt(password);
        }

        //         System.out.println( "URLUtilities.decrypt( "+string+") ["+password+"]");

        return createURL(url.getProtocol(), username, password, url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
    } catch (MalformedURLException e) {
        // ignore
    }

    return null;
}

From source file:org.apache.solr.client.solrj.impl.ConnectionReuseTest.java

@Test
public void testConnectionReuse() throws Exception {

    URL url = cluster.getJettySolrRunners().get(0).getBaseUrl();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

    CloseableHttpClient httpClient = HttpClientUtil.createClient(null, cm);
    try (SolrClient client = buildClient(httpClient, url)) {

        HttpHost target = new HttpHost(url.getHost(), url.getPort(), isSSLMode() ? "https" : "http");
        HttpRoute route = new HttpRoute(target);

        ConnectionRequest mConn = getClientConnectionRequest(httpClient, route, cm);

        HttpClientConnection conn1 = getConn(mConn);
        headerRequest(target, route, conn1, cm);

        cm.releaseConnection(conn1, null, -1, TimeUnit.MILLISECONDS);

        int queueBreaks = 0;
        int cnt1 = atLeast(3);
        int cnt2 = atLeast(30);
        for (int j = 0; j < cnt1; j++) {
            boolean done = false;
            for (int i = 0; i < cnt2; i++) {
                AddUpdateCommand c = new AddUpdateCommand(null);
                c.solrDoc = sdoc("id", id.incrementAndGet());
                try {
                    client.add(c.solrDoc);
                } catch (Exception e) {
                    e.printStackTrace();
                }//  ww w  .  j a  v a 2 s . c o m
                if (!done && i > 0 && i < cnt2 - 1 && client instanceof ConcurrentUpdateSolrClient
                        && random().nextInt(10) > 8) {
                    queueBreaks++;
                    done = true;
                    Thread.sleep(350); // wait past streaming client poll time of 250ms
                }
            }
            if (client instanceof ConcurrentUpdateSolrClient) {
                ((ConcurrentUpdateSolrClient) client).blockUntilFinished();
            }
        }

        route = new HttpRoute(new HttpHost(url.getHost(), url.getPort(), isSSLMode() ? "https" : "http"));

        mConn = cm.requestConnection(route, HttpSolrClient.cacheKey);

        HttpClientConnection conn2 = getConn(mConn);

        HttpConnectionMetrics metrics = conn2.getMetrics();
        headerRequest(target, route, conn2, cm);

        cm.releaseConnection(conn2, null, -1, TimeUnit.MILLISECONDS);

        assertNotNull(
                "No connection metrics found - is the connection getting aborted? server closing the connection? "
                        + client.getClass().getSimpleName(),
                metrics);

        // we try and make sure the connection we get has handled all of the requests in this test
        if (client instanceof ConcurrentUpdateSolrClient) {
            // we can't fully control queue polling breaking up requests - allow a bit of leeway
            int exp = cnt1 + queueBreaks + 2;
            assertTrue(
                    "We expected all communication via streaming client to use one connection! expected=" + exp
                            + " got=" + metrics.getRequestCount(),
                    Math.max(exp, metrics.getRequestCount()) - Math.min(exp, metrics.getRequestCount()) < 3);
        } else {
            assertTrue("We expected all communication to use one connection! "
                    + client.getClass().getSimpleName() + " " + metrics.getRequestCount(),
                    cnt1 * cnt2 + 2 <= metrics.getRequestCount());
        }

    } finally {
        HttpClientUtil.close(httpClient);
    }
}

From source file:cm.aptoide.pt.RemoteInTab.java

private void downloadList(String srv) {
    String url = srv + REMOTE_FILE;

    try {//from   w w w  .  j av  a  2  s  . c om
        FileOutputStream saveit = new FileOutputStream(XML_PATH);
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);
        DefaultHttpClient mHttpClient = new DefaultHttpClient(httpParameters);
        HttpGet mHttpGet = new HttpGet(url);

        String[] logins = null;
        logins = db.getLogin(srv);
        if (logins != null) {
            URL mUrl = new URL(url);
            mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mUrl.getHost(), mUrl.getPort()),
                    new UsernamePasswordCredentials(logins[0], logins[1]));
        }

        HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
        if (mHttpResponse.getStatusLine().getStatusCode() == 401) {
            Message msg = new Message();
            msg.obj = new String(srv);
            secure_error_handler.sendMessage(msg);
        } else {
            byte[] buffer = EntityUtils.toByteArray(mHttpResponse.getEntity());
            saveit.write(buffer);
        }
    } catch (UnknownHostException e) {
        Message msg = new Message();
        msg.obj = new String(srv);
        error_handler.sendMessage(msg);
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }
}

From source file:org.apache.jmeter.protocol.http.control.HC4CookieHandler.java

@Override
public void addCookieFromHeader(CookieManager cookieManager, boolean checkCookies, String cookieHeader,
        URL url) {
    boolean debugEnabled = log.isDebugEnabled();
    if (debugEnabled) {
        log.debug("Received Cookie: " + cookieHeader + " From: " + url.toExternalForm());
    }/*from  ww  w  .ja v a2  s .  c o  m*/
    String protocol = url.getProtocol();
    String host = url.getHost();
    int port = HTTPSamplerBase.getDefaultPort(protocol, url.getPort());
    String path = url.getPath();
    boolean isSecure = HTTPSamplerBase.isSecure(protocol);

    List<org.apache.http.cookie.Cookie> cookies = null;

    CookieOrigin cookieOrigin = new CookieOrigin(host, port, path, isSecure);
    BasicHeader basicHeader = new BasicHeader(HTTPConstants.HEADER_SET_COOKIE, cookieHeader);

    try {
        cookies = cookieSpec.parse(basicHeader, cookieOrigin);
    } catch (MalformedCookieException e) {
        log.error("Unable to add the cookie", e);
    }
    if (cookies == null) {
        return;
    }
    for (org.apache.http.cookie.Cookie cookie : cookies) {
        try {
            if (checkCookies) {
                cookieSpec.validate(cookie, cookieOrigin);
            }
            Date expiryDate = cookie.getExpiryDate();
            long exp = 0;
            if (expiryDate != null) {
                exp = expiryDate.getTime();
            }
            Cookie newCookie = new Cookie(cookie.getName(), cookie.getValue(), cookie.getDomain(),
                    cookie.getPath(), cookie.isSecure(), exp / 1000,
                    ((BasicClientCookie) cookie).containsAttribute(ClientCookie.PATH_ATTR),
                    ((BasicClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR),
                    cookie.getVersion());

            // Store session cookies as well as unexpired ones
            if (exp == 0 || exp >= System.currentTimeMillis()) {
                cookieManager.add(newCookie); // Has its own debug log; removes matching cookies
            } else {
                cookieManager.removeMatchingCookies(newCookie);
                if (debugEnabled) {
                    log.info("Dropping expired Cookie: " + newCookie.toString());
                }
            }
        } catch (MalformedCookieException e) { // This means the cookie was wrong for the URL
            log.warn("Not storing invalid cookie: <" + cookieHeader + "> for URL " + url + " ("
                    + e.getLocalizedMessage() + ")");
        } catch (IllegalArgumentException e) {
            log.warn(cookieHeader + e.getLocalizedMessage());
        }
    }
}

From source file:org.apache.solr.client.solrj.ConnectionReuseTest.java

@Test
public void testConnectionReuse() throws Exception {

    URL url = cluster.getJettySolrRunners().get(0).getBaseUrl();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

    CloseableHttpClient httpClient = HttpClientUtil.createClient(null, cm);
    try (SolrClient client = buildClient(httpClient, url)) {

        HttpHost target = new HttpHost(url.getHost(), url.getPort(), isSSLMode() ? "https" : "http");
        HttpRoute route = new HttpRoute(target);

        ConnectionRequest mConn = getClientConnectionRequest(httpClient, route, cm);

        HttpClientConnection conn1 = getConn(mConn);
        headerRequest(target, route, conn1, cm);

        cm.releaseConnection(conn1, null, -1, TimeUnit.MILLISECONDS);

        int queueBreaks = 0;
        int cnt1 = atLeast(3);
        int cnt2 = atLeast(30);
        for (int j = 0; j < cnt1; j++) {
            boolean done = false;
            for (int i = 0; i < cnt2; i++) {
                AddUpdateCommand c = new AddUpdateCommand(null);
                c.solrDoc = sdoc("id", id.incrementAndGet());
                try {
                    client.add(c.solrDoc);
                } catch (Exception e) {
                    e.printStackTrace();
                }/*from ww  w. ja v a  2  s .  c om*/
                if (!done && i > 0 && i < cnt2 - 1 && client instanceof ConcurrentUpdateSolrClient
                        && random().nextInt(10) > 8) {
                    queueBreaks++;
                    done = true;
                    Thread.sleep(350); // wait past streaming client poll time of 250ms
                }
            }
            if (client instanceof ConcurrentUpdateSolrClient) {
                ((ConcurrentUpdateSolrClient) client).blockUntilFinished();
            }
        }

        route = new HttpRoute(new HttpHost(url.getHost(), url.getPort(), isSSLMode() ? "https" : "http"));

        mConn = cm.requestConnection(route, null);

        HttpClientConnection conn2 = getConn(mConn);

        HttpConnectionMetrics metrics = conn2.getMetrics();
        headerRequest(target, route, conn2, cm);

        cm.releaseConnection(conn2, null, -1, TimeUnit.MILLISECONDS);

        assertNotNull(
                "No connection metrics found - is the connection getting aborted? server closing the connection? "
                        + client.getClass().getSimpleName(),
                metrics);

        // we try and make sure the connection we get has handled all of the requests in this test
        if (client instanceof ConcurrentUpdateSolrClient) {
            // we can't fully control queue polling breaking up requests - allow a bit of leeway
            int exp = cnt1 + queueBreaks + 2;
            assertTrue(
                    "We expected all communication via streaming client to use one connection! expected=" + exp
                            + " got=" + metrics.getRequestCount(),
                    Math.max(exp, metrics.getRequestCount()) - Math.min(exp, metrics.getRequestCount()) < 3);
        } else {
            assertTrue("We expected all communication to use one connection! "
                    + client.getClass().getSimpleName() + " " + metrics.getRequestCount(),
                    cnt1 * cnt2 + 2 <= metrics.getRequestCount());
        }

    } finally {
        HttpClientUtil.close(httpClient);
    }
}

From source file:io.selendroid.server.grid.SelfRegisteringRemote.java

public void performRegistration() throws Exception {
    String tmp = config.getRegistrationUrl();

    HttpClient client = HttpClientUtil.getHttpClient();

    URL registration = new URL(tmp);
    if (log.isLoggable(Level.INFO)) {
        log.info("Registering selendroid node to Selenium Grid hub :" + registration);
    }/*from   w w w.  j  a v  a 2 s.c o  m*/
    BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",
            registration.toExternalForm());
    JSONObject nodeConfig = getNodeConfig();
    r.setEntity(new StringEntity(nodeConfig.toString()));

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

From source file:edu.du.penrose.systems.fedoraApp.batchIngest.data.BatchIngestURLhandlerImpl.java

/**
 * This location will vary depending on if the ingest is running as a task.
 * A task will put the reports into a temporary directory prior to performing
 * the finalization of the ingest (e-mailing results, posting rest responses).
 * /*from   ww w.  j a v a 2 s  . c  o  m*/
 * @see edu.du.penrose.systems.fedoraApp.batchIngest.data.BatchIngestOptions#isRunningAsRemoteTask()
 */
public URL getPidReportLocationURL() {
    URL pidReportURL = null;

    pidReportURL = this.getLogFilesFolderURL();

    String host = pidReportURL.getHost();
    String protocol = pidReportURL.getProtocol();
    int port = pidReportURL.getPort();
    String filePath = pidReportURL.getFile();

    try {
        pidReportURL = new URL(protocol, host, port,
                filePath + this.getUniqueBatchRunName() + FedoraAppConstants.BATCH_INGEST_PID_REPORT_FILE_EXT);
    } catch (MalformedURLException e) {
        // the original url has already been checked so this should never happen.
        throw new RuntimeException(e.getMessage());
    }

    return pidReportURL;
}

From source file:com.gargoylesoftware.htmlunit.WebRequest.java

private URL buildUrlWithNewFile(URL url, String newFile) {
    try {/* ww w . j av a  2  s  .c  o m*/
        if (url.getRef() != null) {
            newFile += '#' + url.getRef();
        }
        url = new URL(url.getProtocol(), url.getHost(), url.getPort(), newFile);
    } catch (final Exception e) {
        throw new RuntimeException("Cannot set URL: " + url.toExternalForm(), e);
    }
    return url;
}

From source file:cm.aptoide.pt.ManageRepo.java

private int checkServer(String uri, String user, String pwd) {

    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
    HttpConnectionParams.setSoTimeout(httpParameters, 5000);

    DefaultHttpClient mHttpClient = new DefaultHttpClient(httpParameters);
    HttpGet mHttpGet = new HttpGet(uri + "/info.xml");
    try {//w w w. j a va2  s  .co m
        if (user != null && pwd != null) {
            URL mUrl = new URL(uri);
            mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mUrl.getHost(), mUrl.getPort()),
                    new UsernamePasswordCredentials(user, pwd));
        }
        HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
        return mHttpResponse.getStatusLine().getStatusCode();
    } catch (ClientProtocolException e) {
        return -1;
    } catch (IOException e) {
        return -1;
    } catch (IllegalArgumentException e) {
        return -1;
    }
}