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:com.googlesource.gerrit.plugins.github.oauth.PooledHttpClientProvider.java

@Override
public HttpClient get() {
    HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnPerRoute(maxConnectionPerRoute)
            .setMaxConnTotal(maxTotalConnection);

    if (proxy.getProxyUrl() != null) {
        URL url = proxy.getProxyUrl();
        builder.setProxy(new HttpHost(url.getHost(), url.getPort()));
        if (!Strings.isNullOrEmpty(proxy.getUsername()) && !Strings.isNullOrEmpty(proxy.getPassword())) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(proxy.getUsername(),
                    proxy.getPassword());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), creds);
            builder.setDefaultCredentialsProvider(credsProvider);
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        }/*from w ww. j a  v a  2  s  . c om*/
    }

    return builder.build();
}

From source file:sh.calaba.driver.model.CalabashAndroidDriver.java

public CalabashAndroidDriver(String remoteURL, Map<String, Object> capabilities) {
    this.remoteURL = remoteURL;
    this.requestedCapabilities = capabilities;
    try {//from   www  .j  a  va2s  .  c  o  m
        URL url = new URL(remoteURL);
        port = url.getPort();
        host = url.getHost();
        session = start();
    } catch (Exception e) {
        if (e instanceof CalabashException) {
            throw (CalabashException) e;
        }
        e.printStackTrace();

        throw new CalabashException(e);
    }
}

From source file:com.cisco.cta.taxii.adapter.httpclient.CredentialsProviderFactory.java

private void addTaxiiCredentials(CredentialsProvider credsProvider) {
    URL url = settings.getPollEndpoint();
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(settings.getUsername(), settings.getPassword()));
}

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

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    Assert.isTrue(applicationContext != null, "Application context must not be null");
    STSAuthenticationProvider authProvider = authenticationProvider;
    if (authProvider == null) {
        authProvider = applicationContext.getBean(STSAuthenticationProvider.class);
    }//from   w w w  .  ja v a 2  s . c  o m
    Assert.isTrue(authProvider != null, "STSAuthenticationProvider must be configured");

    //Only update the port if HTTPS is used, otherwise ignored (like retrieving the WADL over HTTP)
    if (!isPortSet && request.isSecure()) {
        try {
            URL url = new URL(authProvider.getWsdlLocation());
            if (url.getPort() == 0) {
                URL updatedUrl = new URL(url.getProtocol(), url.getHost(), request.getLocalPort(),
                        url.getFile());
                setSTSWsdlUrl(authProvider, updatedUrl.toString());
                LOG.info("STSAuthenticationProvider.wsdlLocation set to " + updatedUrl.toString());
            } else {
                setSTSWsdlUrl(authProvider, url.toString());
            }
        } catch (MalformedURLException e) {
            LOG.error("Invalid Url '" + authProvider.getWsdlLocation() + "': " + e.getMessage());
        }
    }

    chain.doFilter(request, response);
}

From source file:com.zextras.zimbradrive.statustest.ConnectionTestUtils.java

public boolean pingHost(URL url, int connectionTimeout) throws MalformedURLException {
    String host = url.getHost();/*from ww  w.  ja  va2  s  . c om*/
    int port = url.getPort();
    if (port == -1) {
        if (url.getProtocol().equals("https")) {
            port = 443;
        } else {
            port = 80;
        }
    }
    try (Socket socket = new Socket()) {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        socket.connect(inetSocketAddress, connectionTimeout);
        return true;
    } catch (IOException e) {
        return false; // Either timeout or unreachable or failed DNS lookup.
    }
}

From source file:com.macdonst.ftpclient.FtpClient.java

/**
 * Extracts the port of the FTP server. Returns 21 by default.
 * @param url/*from  w  ww . j a v a2 s.co m*/
 * @return
 */
private int extractPort(URL url) {
    if (url.getPort() == -1) {
        return url.getDefaultPort();
    } else {
        return url.getPort();
    }
}

From source file:com.esri.gpt.framework.http.crawl.HttpCrawlRequest.java

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

From source file:com.dtolabs.client.utils.BasicAuthenticator.java

public boolean authenticate(URL reqUrl, HttpClient client) throws HttpClientException {
    AuthScope scope = new AuthScope(reqUrl.getHost(), reqUrl.getPort(), REALM_NAME);
    Credentials creds = new UsernamePasswordCredentials(getUsername(), getPassword());
    client.getParams().setAuthenticationPreemptive(true);
    if (client.getState().getCredentials(scope) == null) {
        client.getState().setCredentials(scope, creds);
    }// www  . j  a  v a  2 s .c  o m
    return true;
}

From source file:de.fraunhofer.iosb.ilt.stc.auth.AuthBasic.java

@Override
public void setAuth(SensorThingsService service) {
    try {//from   w w  w .  j ava  2 s . c  o  m
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        URL url = service.getEndpoint().toURL();
        credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(editorUsername.getValue(), editorPassword.getValue()));
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .build();
        service.setClient(httpclient);
    } catch (MalformedURLException ex) {
        LOGGER.error("Failed to initialise basic auth.", ex);
    }
}

From source file:com.zimbra.cs.util.SpamExtract.java

private static void extract(String authToken, Account account, Server server, String query, File outdir,
        boolean delete, boolean raw) throws ServiceException, HttpException, SoapFaultException, IOException {
    String soapURL = getSoapURL(server, false);

    URL restURL = getServerURL(server, false);
    HttpClient hc = new HttpClient(); // CLI only, don't need conn mgr
    HttpState state = new HttpState();
    GetMethod gm = new GetMethod();
    gm.setFollowRedirects(true);/* w ww. j a  v  a  2 s .c om*/
    Cookie authCookie = new Cookie(restURL.getHost(), ZimbraCookie.COOKIE_ZM_AUTH_TOKEN, authToken, "/", -1,
            false);
    state.addCookie(authCookie);
    hc.setState(state);
    hc.getHostConfiguration().setHost(restURL.getHost(), restURL.getPort(),
            Protocol.getProtocol(restURL.getProtocol()));
    gm.getParams().setSoTimeout(60000);

    if (verbose) {
        LOG.info("Mailbox requests to: " + restURL);
    }

    SoapHttpTransport transport = new SoapHttpTransport(soapURL);
    transport.setRetryCount(1);
    transport.setTimeout(0);
    transport.setAuthToken(authToken);

    int totalProcessed = 0;
    boolean haveMore = true;
    int offset = 0;
    while (haveMore) {
        Element searchReq = new Element.XMLElement(MailConstants.SEARCH_REQUEST);
        searchReq.addElement(MailConstants.A_QUERY).setText(query);
        searchReq.addAttribute(MailConstants.A_SEARCH_TYPES, MailItem.Type.MESSAGE.toString());
        searchReq.addAttribute(MailConstants.A_QUERY_OFFSET, offset);
        searchReq.addAttribute(MailConstants.A_LIMIT, BATCH_SIZE);

        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug(searchReq.prettyPrint());
            }
            Element searchResp = transport.invoke(searchReq, false, true, account.getId());
            if (LOG.isDebugEnabled()) {
                LOG.debug(searchResp.prettyPrint());
            }

            StringBuilder deleteList = new StringBuilder();

            List<String> ids = new ArrayList<String>();
            for (Iterator<Element> iter = searchResp.elementIterator(MailConstants.E_MSG); iter.hasNext();) {
                offset++;
                Element e = iter.next();
                String mid = e.getAttribute(MailConstants.A_ID);
                if (mid == null) {
                    LOG.warn("null message id SOAP response");
                    continue;
                }

                LOG.debug("adding id %s", mid);
                ids.add(mid);
                if (ids.size() >= BATCH_SIZE || !iter.hasNext()) {
                    StringBuilder path = new StringBuilder("/service/user/" + account.getName()
                            + "/?fmt=tgz&list=" + StringUtils.join(ids, ","));
                    LOG.debug("sending request for path %s", path.toString());
                    List<String> extractedIds = extractMessages(hc, gm, path.toString(), outdir, raw);
                    if (ids.size() > extractedIds.size()) {
                        ids.removeAll(extractedIds);
                        LOG.warn("failed to extract %s", ids);
                    }
                    for (String id : extractedIds) {
                        deleteList.append(id).append(',');
                    }

                    ids.clear();
                }
                totalProcessed++;
            }

            haveMore = false;
            String more = searchResp.getAttribute(MailConstants.A_QUERY_MORE);
            if (more != null && more.length() > 0) {
                try {
                    int m = Integer.parseInt(more);
                    if (m > 0) {
                        haveMore = true;
                        try {
                            Thread.sleep(SLEEP_TIME);
                        } catch (InterruptedException e) {
                        }
                    }
                } catch (NumberFormatException nfe) {
                    LOG.warn("more flag from server not a number: " + more, nfe);
                }
            }

            if (delete && deleteList.length() > 0) {
                deleteList.deleteCharAt(deleteList.length() - 1); // -1 removes trailing comma
                Element msgActionReq = new Element.XMLElement(MailConstants.MSG_ACTION_REQUEST);
                Element action = msgActionReq.addElement(MailConstants.E_ACTION);
                action.addAttribute(MailConstants.A_ID, deleteList.toString());
                action.addAttribute(MailConstants.A_OPERATION, ItemAction.OP_HARD_DELETE);

                if (LOG.isDebugEnabled()) {
                    LOG.debug(msgActionReq.prettyPrint());
                }
                Element msgActionResp = transport.invoke(msgActionReq, false, true, account.getId());
                if (LOG.isDebugEnabled()) {
                    LOG.debug(msgActionResp.prettyPrint());
                }
                offset = 0; //put offset back to 0 so we always get top N messages even after delete
            }
        } finally {
            gm.releaseConnection();
        }

    }
    LOG.info("Total messages processed: " + totalProcessed);
}