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:juzu.impl.plugin.amd.AmdMaxAgeTestCase.java

@Test
@RunAsClient/* w w w  .j  a  va2s .  co  m*/
public void test() throws Exception {
    URL applicationURL = applicationURL();
    driver.get(applicationURL.toString());
    WebElement elt = driver.findElement(By.id("Foo"));
    URL url = new URL(applicationURL.getProtocol(), applicationURL.getHost(), applicationURL.getPort(),
            elt.getText());
    HttpGet get = new HttpGet(url.toURI());
    HttpResponse response = HttpClientBuilder.create().build().execute(get);
    Header[] cacheControl = response.getHeaders("Cache-Control");
    assertEquals(1, cacheControl.length);
    assertEquals("max-age=1000", cacheControl[0].getValue());
}

From source file:io.github.cidisk.indexcrawler.robotstxt.RobotstxtServer.java

private HostDirectives fetchDirectives(URL url) {
    WebURL robotsTxtUrl = new WebURL();
    String host = getHost(url);/*from   www  . j  a  v a  2  s.co  m*/
    String port = (url.getPort() == url.getDefaultPort() || url.getPort() == -1) ? "" : ":" + url.getPort();
    robotsTxtUrl.setURL("http://" + host + port + "/robots.txt");
    HostDirectives directives = null;
    PageFetchResult fetchResult = null;
    try {
        fetchResult = pageFetcher.fetchPage(robotsTxtUrl);
        if (fetchResult.getStatusCode() == HttpStatus.SC_OK) {
            Page page = new Page(robotsTxtUrl);
            fetchResult.fetchContent(page);
            if (Util.hasPlainTextContent(page.getContentType())) {
                String content;
                if (page.getContentCharset() == null) {
                    content = new String(page.getContentData());
                } else {
                    content = new String(page.getContentData(), page.getContentCharset());
                }
                directives = RobotstxtParser.parse(content, config.getUserAgentName());
            }
        }
    } catch (SocketException | UnknownHostException | SocketTimeoutException se) {
        // No logging here, as it just means that robots.txt doesn't exist on this server which is perfectly ok
    } catch (PageBiggerThanMaxSizeException pbtms) {
        logger.error("Error occurred while fetching (robots) url: {}, {}", robotsTxtUrl.getURL(),
                pbtms.getMessage());
    } catch (Exception e) {
        logger.error("Error occurred while fetching (robots) url: " + robotsTxtUrl.getURL(), e);
    } finally {
        if (fetchResult != null) {
            fetchResult.discardContentIfNotConsumed();
        }
    }

    if (directives == null) {
        // We still need to have this object to keep track of the time we
        // fetched it
        directives = new HostDirectives();
    }
    synchronized (host2directivesCache) {
        if (host2directivesCache.size() == config.getCacheSize()) {
            String minHost = null;
            long minAccessTime = Long.MAX_VALUE;
            for (Entry<String, HostDirectives> entry : host2directivesCache.entrySet()) {
                if (entry.getValue().getLastAccessTime() < minAccessTime) {
                    minAccessTime = entry.getValue().getLastAccessTime();
                    minHost = entry.getKey();
                }
            }
            host2directivesCache.remove(minHost);
        }
        host2directivesCache.put(host, directives);
    }
    return directives;
}

From source file:mobi.jenkinsci.server.core.net.PooledHttpClientFactory.java

private CredentialsProvider getCredentialsProvider(final URL url, final String user, final String password) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM, "BASIC"),
            new UsernamePasswordCredentials(user, password));
    return provider;
}

From source file:com.predic8.membrane.core.interceptor.swagger.SwaggerRewriterInterceptor.java

@Override
public Outcome handleRequest(Exchange exc) throws Exception {
    ((ServiceProxy) exc.getRule()).setTargetHost(swagger.getHost());
    URL url = new URL(swaggerUrl);
    exc.getDestinations().set(0, url.getProtocol() + "://" + url.getHost()
            + (url.getPort() < 0 ? "" : ":" + url.getPort()) + exc.getOriginalRequestUri());
    return super.handleRequest(exc);
}

From source file:org.wso2.carbon.device.mgt.iot.common.apimgt.TokenClient.java

private AccessTokenInfo getTokenInfo(List<NameValuePair> nameValuePairs) throws AccessTokenException {

    try {//from  w  ww.j av a2s . c  om
        URL tokenUrl = new URL(tokenURL);
        HttpClient httpClient = null;
        try {
            httpClient = IoTUtil.getHttpClient(tokenUrl.getPort(), tokenUrl.getProtocol());
        } catch (Exception e) {
            String msg = "Error on getting a http client for port :" + tokenUrl.getPort() + " protocol :"
                    + tokenUrl.getProtocol();
            log.error(msg);
            throw new AccessTokenException(msg);
        }
        HttpPost postMethod = new HttpPost(tokenURL);
        postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        if (appToken != null) {
            postMethod.addHeader("Authorization", "Basic " + appToken);
        }
        postMethod.addHeader("Content-Type", "application/x-www-form-urlencoded");

        HttpResponse httpResponse = httpClient.execute(postMethod);
        String response = IoTUtil.getResponseString(httpResponse);
        if (log.isDebugEnabled()) {
            log.debug(response);
        }
        JSONObject jsonObject = new JSONObject(response);

        AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
        accessTokenInfo.setAccess_token(jsonObject.getString("access_token"));
        accessTokenInfo.setRefresh_token(jsonObject.getString("refresh_token"));
        accessTokenInfo.setExpires_in(jsonObject.getInt("expires_in"));
        accessTokenInfo.setToken_type(jsonObject.getString("token_type"));
        return accessTokenInfo;

    } catch (IOException | JSONException | IoTException e) {
        log.error(e.getMessage());
        throw new AccessTokenException("Configuration Error for Access Token Generation");
    }

}

From source file:es.gva.cit.catalog.protocols.HTTPGetProtocol.java

/**
 * /*from  ww  w  .j  a v a  2  s.co  m*/
 * 
 * 
 * @return
 * @param url
 * @param object
 * @param firstRecord
 */
public Collection doQuery(URL url, Object object, int firstRecord) {
    NameValuePair[] parameters = (NameValuePair[]) object;
    File file = null;

    String sUrl = "http://" + url.getHost() + ":" + url.getPort() + url.getPath();
    sUrl = sUrl + createURLParams(parameters);

    try {
        file = Utilities.downloadFile(new URL(sUrl), "catalog-", null);

    } catch (Exception e) {
        return null;
    }

    Collection col = new java.util.ArrayList();
    col.add(XMLTree.xmlToTree(file));
    return col;
}

From source file:org.jboss.as.test.integration.web.security.authentication.BasicAuthenticationMechanismPicketboxRemovedTestCase.java

/**
 * Test checks if correct response is returned after the EJB is called from the secured servlet.
 *
 * @param url/*from  w ww .  j av a2  s.c o  m*/
 * @throws Exception
 */
@Test
public void test(@ArquillianResource URL url) throws Exception {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(USER, PASSWORD));
    try (CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credentialsProvider).build()) {

        HttpGet httpget = new HttpGet(url.toExternalForm() + "SecuredEJBServlet/");
        HttpResponse response = httpclient.execute(httpget);
        assertNotNull("Response is 'null', we expected non-null response!", response);
        String text = Utils.getContent(response);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertTrue("User principal different from what we expected!", text.contains("Principal: " + USER));
        assertTrue("Remote user different from what we expected!", text.contains("Remote User: " + USER));
        assertTrue("Authentication type different from what we expected!",
                text.contains("Authentication Type: BASIC"));
    }
}

From source file:com.asual.summer.core.faces.FacesResourceResolver.java

public URL resolveUrl(String path) {
    if (!resources.containsKey(path)) {
        URL url = ResourceUtils
                .getClasspathResource("/".equals(path) ? "META-INF/" : path.replaceAll("^/", ""));
        if (url != null) {
            try {
                url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile(),
                        new FacesStreamHandler(url));
            } catch (AccessControlException e) {
            } catch (NoClassDefFoundError e) {
            } catch (MalformedURLException e) {
                throw new FacesException(e);
            }/*from w w  w.j  av a  2 s  .  c o m*/
        } else {
            logger.warn("The requested resource [" + path + "] cannot be resolved.");
        }
        resources.put(path, url);
    }
    return resources.get(path);
}

From source file:de.ecclesia.kipeto.RepositoryResolver.java

/**
 * Ermittelt anhand der Default-Repository-URL die IP-Adresse der
 * Netzwerkkarte, die Verbindung zum Repository hat.
 *///from  w  ww  . jav  a2 s .  co  m
private String determinateLocalIP() throws IOException {
    Socket socket = null;

    try {

        int port;
        String hostname;

        if (isSftp()) {
            port = 22;
            hostname = getHostname();
        } else {
            URL url = new URL(defaultRepositoryUrl);
            port = url.getPort() > -1 ? url.getPort() : url.getDefaultPort();
            hostname = url.getHost();
        }

        log.debug("Determinating local IP-Adress by connect to {}:{}", defaultRepositoryUrl, port);
        InetAddress address = Inet4Address.getByName(hostname);

        socket = new Socket();
        socket.connect(new InetSocketAddress(address, port), 3000);
        InputStream stream = socket.getInputStream();
        InetAddress localAddress = socket.getLocalAddress();
        stream.close();

        String localIp = localAddress.getHostAddress();

        log.info("Local IP-Adress is {}", localIp);

        return localIp;
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:org.squashtest.tm.plugin.testautomation.jenkins.internal.net.HttpClientProvider.java

protected void registerServer(TestAutomationServer server) {

    URL baseURL = server.getBaseURL();

    credentialsProvider.setCredentials(new AuthScope(baseURL.getHost(), baseURL.getPort(), AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(server.getLogin(), server.getPassword()));

}