Java Code Examples for java.net.URL#getPort()

The following examples show how to use java.net.URL#getPort() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EntityProcessorImpl.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
/***
 * @param url
 * @return The appropriate base s.t. relative URLs can resolve
 */
static String getBase(URL url) {
  StringBuilder buffer = new StringBuilder();
  buffer.append(url.getProtocol());
  buffer.append("://");
  buffer.append(url.getHost());
  if (url.getPort() > 0 && 80 != url.getPort()) {
    buffer.append(':');
    buffer.append(url.getPort());
  }
  if (!isNullOrEmpty(url.getPath()) && url.getPath().contains("/")) {
    String path = url.getPath();
    buffer.append(path.substring(0, path.lastIndexOf("/")));
  }
  buffer.append('/');
  return buffer.toString();
}
 
Example 2
Source File: KmlGenerator.java    From mrgeo with Apache License 2.0 6 votes vote down vote up
@SuppressFBWarnings(value = "SERVLET_PARAMETER", justification = "WMSHOST - simply returning the value sent in")
private String getWmsHost(HttpServletRequest request) throws MalformedURLException
{
  String result = request.getParameter("WMSHOST");
  if (result == null)
  {
    URL requestUrl = new URL(request.getRequestURL().toString());
    result = requestUrl.getHost();
    int port = requestUrl.getPort();
    if (port != -1)
    {
      result = String.format("%s:%d", result, port);
    }
  }
  return result;
}
 
Example 3
Source File: Instance.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
private static StreamsConnection createStandaloneConnection(String endpoint,
        String userName, String password, boolean verify) throws IOException {
    if (!endpoint.endsWith(STREAMS_REST_RESOURCES)) {
        URL url = new URL(endpoint);
        URL resourcesUrl = new URL(url.getProtocol(), url.getHost(),
                url.getPort(), STREAMS_REST_RESOURCES);
        endpoint = resourcesUrl.toExternalForm();
    }
    StandaloneAuthenticator auth = StandaloneAuthenticator.of(endpoint, userName, password);
    if (auth.config(verify) != null) {
        return StreamsConnection.ofAuthenticator(endpoint, auth);
    } else {
        // Couldn't configure standalone authenticator, try Basic
        return StreamsConnection.createInstance(userName, password, endpoint);
    }
}
 
Example 4
Source File: FlooUrl.java    From floobits-intellij with Apache License 2.0 6 votes vote down vote up
public FlooUrl(String url) throws MalformedURLException {
    URL u = new URL(url);
    String path = u.getPath();
    String[] parts = path.split("/");

    this.host = u.getHost();
    this.owner = parts[1];
    this.workspace = parts[2];
    if (this.owner.equals("r")) {
        this.owner = parts[2];
        this.workspace = parts[3];
    }
    this.port = u.getPort();
    this.proto = u.getProtocol();

    this.secure = !this.proto.equals("http");

    if (this.port < 0) {
        if (this.secure) {
            this.port = 3448;
        } else {
            this.port = 3148;
        }
    }
}
 
Example 5
Source File: AuthenticationInfo.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public AuthenticationInfo(char type, AuthScheme authScheme, URL url, String realm) {
    this.type = type;
    this.authScheme = authScheme;
    this.protocol = url.getProtocol().toLowerCase();
    this.host = url.getHost().toLowerCase();
    this.port = url.getPort();
    if (this.port == -1) {
        this.port = url.getDefaultPort();
    }
    this.realm = realm;

    String urlPath = url.getPath();
    if (urlPath.length() == 0)
        this.path = urlPath;
    else {
        this.path = reducePath (urlPath);
    }

}
 
Example 6
Source File: HttpURLConnection.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private String getHostAndPort(URL url) {
    String host = url.getHost();
    final String hostarg = host;
    try {
        // lookup hostname and use IP address if available
        host = AccessController.doPrivileged(
            new PrivilegedExceptionAction<String>() {
                public String run() throws IOException {
                        InetAddress addr = InetAddress.getByName(hostarg);
                        return addr.getHostAddress();
                }
            }
        );
    } catch (PrivilegedActionException e) {}
    int port = url.getPort();
    if (port == -1) {
        String scheme = url.getProtocol();
        if ("http".equals(scheme)) {
            return host + ":80";
        } else { // scheme must be https
            return host + ":443";
        }
    }
    return host + ":" + Integer.toString(port);
}
 
Example 7
Source File: HttpTransactionUtils.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
  * Format a base URL string ( protocol://server[:port][/file-specification] )
  * @param url URL to format
  * @param preserveFile Keep the /directory/filename portion of the URL?
  * @return URL string
  */
 public static String formatUrl(URL url, boolean preserveFile)
 																				throws MalformedURLException {
   StringBuilder	result;
	int						port;

	result = new StringBuilder(url.getProtocol());

   result.append("://");
   result.append(url.getHost());

   if ((port = url.getPort()) != -1) {
   	result.append(":");
   	result.append(String.valueOf(port));
  	}

  	if (preserveFile) {
  		String file = url.getFile();

  		if (file != null) {
  			result.append(file);
  		}
  	}
   return result.toString();
}
 
Example 8
Source File: XJarClassLoader.java    From xjar with Apache License 2.0 5 votes vote down vote up
@Override
public URL nextElement() {
    URL url = enumeration.nextElement();
    if (url == null) {
        return null;
    }
    try {
        return new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile(), xJarURLHandler);
    } catch (MalformedURLException e) {
        return url;
    }
}
 
Example 9
Source File: HttpURLConnection.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
static String connectRequestURI(URL url) {
    String host = url.getHost();
    int port = url.getPort();
    port = port != -1 ? port : url.getDefaultPort();

    return host + ":" + port;
}
 
Example 10
Source File: STSPortFilter.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@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);
    }
    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);
}
 
Example 11
Source File: TomcatClassPath.java    From tomee with Apache License 2.0 5 votes vote down vote up
private static URL targetURL(final URL base, final String name) throws MalformedURLException {
    final StringBuilder sb = new StringBuilder(base.getFile().length() + name.length());
    sb.append(base.getFile());
    sb.append(name);
    final String file = sb.toString();
    return new URL(base.getProtocol(), base.getHost(), base.getPort(), file, null);
}
 
Example 12
Source File: JettySolrRunnerTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testRestartPorts() throws Exception {

  Path solrHome = createTempDir();
  Files.write(solrHome.resolve("solr.xml"), MiniSolrCloudCluster.DEFAULT_CLOUD_SOLR_XML.getBytes(Charset.defaultCharset()));

  JettyConfig config = JettyConfig.builder().build();

  JettySolrRunner jetty = new JettySolrRunner(solrHome.toString(), config);
  try {
    jetty.start();

    URL url = jetty.getBaseUrl();
    int usedPort = url.getPort();

    jetty.stop();
    jetty.start();

    assertEquals("After restart, jetty port should be the same", usedPort, jetty.getBaseUrl().getPort());

    jetty.stop();
    jetty.start(false);

    assertThat("After restart, jetty port should be different", jetty.getBaseUrl().getPort(), not(usedPort));
  }
  finally {
    if (jetty.isRunning())
      jetty.stop();
  }

}
 
Example 13
Source File: SDKEntrypoint.java    From abstract-operator with Apache License 2.0 5 votes vote down vote up
private void checkIfOnOpenshift() {
    try {
        URL kubernetesApi = client.getMasterUrl();

        HttpUrl.Builder urlBuilder = new HttpUrl.Builder();
        urlBuilder.host(kubernetesApi.getHost());

        if (kubernetesApi.getPort() == -1) {
            urlBuilder.port(kubernetesApi.getDefaultPort());
        } else {
            urlBuilder.port(kubernetesApi.getPort());
        }
        if (kubernetesApi.getProtocol().equals("https")) {
            urlBuilder.scheme("https");
        }
        urlBuilder.addPathSegment("apis/route.openshift.io/v1");

        OkHttpClient httpClient = HttpClientUtils.createHttpClient(new ConfigBuilder().build());
        HttpUrl url = urlBuilder.build();
        Response response = httpClient.newCall(new Request.Builder().url(url).build()).execute();
        boolean success = response.isSuccessful();
        if (success) {
            log.info("{} returned {}. We are on OpenShift.", url, response.code());
        } else {
            log.info("{} returned {}. We are not on OpenShift. Assuming, we are on Kubernetes.", url, response.code());
        }
        isOpenShift = success;
    } catch (Exception e) {
        e.printStackTrace();
        log.error("Failed to distinguish between Kubernetes and OpenShift");
        log.warn("Let's assume we are on K8s");
        isOpenShift = false;
    }
}
 
Example 14
Source File: NetUtils.java    From weblaf with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns base address for the specified complete address.
 *
 * @param address complete address to process
 * @return base address for the specified complete address
 */
@NotNull
public static String getBaseAddress ( @NotNull final String address )
{
    final URL url = getURL ( address );
    return url.getHost () + ( url.getPort () != 80 && url.getPort () != -1 ? ":" + url.getPort () : "" );
}
 
Example 15
Source File: KeepAliveCache.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param url the URL containing the protocol, host and port information
 */
public KeepAliveKey(URL url, Object obj) {
    this.protocol = url.getProtocol();
    this.host = url.getHost();
    this.port = url.getPort();
    this.obj = obj;
}
 
Example 16
Source File: ElasticsearchValidator.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Parse Hosts String to list.
 *
 * <p>Hosts String format was given as following:
 *
 * <pre>
 *     connector.hosts = http://host_name:9092;http://host_name:9093
 * </pre>
 */
public static List<Host> validateAndParseHostsString(DescriptorProperties descriptorProperties) {
	final List<Host> hostList = new ArrayList<>();

	descriptorProperties.validateString(CONNECTOR_HOSTS, false, 1);
	final String hostsStr = descriptorProperties.getString(CONNECTOR_HOSTS);

	final String[] hosts = hostsStr.split(";");
	final String validationExceptionMessage = "Properties '" + CONNECTOR_HOSTS + "' format should " +
		"follow the format 'http://host_name:port', but is '" + hostsStr + "'.";

	if (hosts.length == 0) {
		throw new ValidationException(validationExceptionMessage);
	}
	for (String host : hosts) {
		try {
			final URL url = new URL(host);
			final String protocol = url.getProtocol();
			final String hostName = url.getHost();
			final int hostPort = url.getPort();

			if (StringUtils.isNullOrWhitespaceOnly(protocol) ||
				StringUtils.isNullOrWhitespaceOnly(hostName) ||
				-1 == hostPort) {
				throw new ValidationException(validationExceptionMessage);
			}

			hostList.add(new Host(hostName, hostPort, protocol));
		} catch (MalformedURLException e) {
			throw new ValidationException(validationExceptionMessage, e);
		}
	}
	return hostList;
}
 
Example 17
Source File: ObsoleteUrlFactory.java    From DoraemonKit with Apache License 2.0 5 votes vote down vote up
@Override
public Permission getPermission() {
    URL url = getURL();
    String hostname = url.getHost();
    int hostPort = url.getPort() != -1
            ? url.getPort()
            : HttpUrl.defaultPort(url.getProtocol());
    if (usingProxy()) {
        InetSocketAddress proxyAddress = (InetSocketAddress) client.proxy().address();
        hostname = proxyAddress.getHostName();
        hostPort = proxyAddress.getPort();
    }
    return new SocketPermission(hostname + ":" + hostPort, "connect, resolve");
}
 
Example 18
Source File: ElasticsearchCollector.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
public void activate(Dictionary<String, Object> configuration) {
    this.configuration = configuration;
    String addressesString = (configuration.get("addresses") != null) ? configuration.get("addresses").toString() : "http://localhost:9200";
    String username = (configuration.get("username") != null) ? configuration.get("username").toString() : null;
    String password = (configuration.get("password") != null) ? configuration.get("password").toString() : null;

    Set<String> addresses = new HashSet<>(Arrays.asList(addressesString.split(",")));

    HttpHost[] hosts = new HttpHost[addresses.size()];
    int i = 0;
    for (String address : addresses) {
        try {
            URL url = new URL(address);
            hosts[i] = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
            i++;
        } catch (Exception e) {
            LOGGER.warn("Bad elasticsearch address {}", address, e);
        }
    }
    RestClientBuilder restClientBuilder = RestClient.builder(hosts);

    restClientBuilder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setConnectTimeout(1000)
            .setSocketTimeout(10000));

    if (username != null) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        restClientBuilder.setHttpClientConfigCallback(
                new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                        return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                }
        );
    }

    restClient = new RestHighLevelClient(restClientBuilder);
}
 
Example 19
Source File: HttpURLConnection.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private boolean followRedirect0(String loc, int stat, URL locUrl)
    throws IOException
{
    disconnectInternal();
    if (streaming()) {
        throw new HttpRetryException (RETRY_MSG3, stat, loc);
    }
    if (logger.isLoggable(PlatformLogger.Level.FINE)) {
        logger.fine("Redirected from " + url + " to " + locUrl);
    }

    // clear out old response headers!!!!
    responses = new MessageHeader();
    if (stat == HTTP_USE_PROXY) {
        /* This means we must re-request the resource through the
         * proxy denoted in the "Location:" field of the response.
         * Judging by the spec, the string in the Location header
         * _should_ denote a URL - let's hope for "http://my.proxy.org"
         * Make a new HttpClient to the proxy, using HttpClient's
         * Instance-specific proxy fields, but note we're still fetching
         * the same URL.
         */
        String proxyHost = locUrl.getHost();
        int proxyPort = locUrl.getPort();

        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkConnect(proxyHost, proxyPort);
        }

        setProxiedClient (url, proxyHost, proxyPort);
        requests.set(0, method + " " + getRequestURI()+" "  +
                         httpVersion, null);
        connected = true;
        // need to remember this in case NTLM proxy authentication gets
        // used. We can't use transparent authentication when user
        // doesn't know about proxy.
        useProxyResponseCode = true;
    } else {
        // maintain previous headers, just change the name
        // of the file we're getting
        url = locUrl;
        requestURI = null; // force it to be recalculated
        if (method.equals("POST") && !Boolean.getBoolean("http.strictPostRedirect") && (stat!=307)) {
            /* The HTTP/1.1 spec says that a redirect from a POST
             * *should not* be immediately turned into a GET, and
             * that some HTTP/1.0 clients incorrectly did this.
             * Correct behavior redirects a POST to another POST.
             * Unfortunately, since most browsers have this incorrect
             * behavior, the web works this way now.  Typical usage
             * seems to be:
             *   POST a login code or passwd to a web page.
             *   after validation, the server redirects to another
             *     (welcome) page
             *   The second request is (erroneously) expected to be GET
             *
             * We will do the incorrect thing (POST-->GET) by default.
             * We will provide the capability to do the "right" thing
             * (POST-->POST) by a system property, "http.strictPostRedirect=true"
             */

            requests = new MessageHeader();
            setRequests = false;
            super.setRequestMethod("GET"); // avoid the connecting check
            poster = null;
            if (!checkReuseConnection())
                connect();
        } else {
            if (!checkReuseConnection())
                connect();
            /* Even after a connect() call, http variable still can be
             * null, if a ResponseCache has been installed and it returns
             * a non-null CacheResponse instance. So check nullity before using it.
             *
             * And further, if http is null, there's no need to do anything
             * about request headers because successive http session will use
             * cachedInputStream/cachedHeaders anyway, which is returned by
             * CacheResponse.
             */
            if (http != null) {
                requests.set(0, method + " " + getRequestURI()+" "  +
                             httpVersion, null);
                int port = url.getPort();
                String host = url.getHost();
                if (port != -1 && port != url.getDefaultPort()) {
                    host += ":" + String.valueOf(port);
                }
                requests.set("Host", host);
            }
        }
    }
    return true;
}
 
Example 20
Source File: WxpayServiceImpl.java    From jframe with Apache License 2.0 4 votes vote down vote up
/**
 * 通知租车后台
 * 
 * @param conn
 * @param od
 * @param orderStatus
 */
public void postBack(OrderWx od) {
    Map<String, String> map = new HashMap<String, String>(2, 1);
    map.put(F_payNo, od.payNo);
    map.put(F_payStatus, od.payStatus);

    boolean succ = false;
    try {
        URL url = new URL(od.backUrl);
        int port = url.getPort() == -1 ? 80 : url.getPort();

        if (LOG.isDebugEnabled())
            LOG.debug("postBack -> {}, {},{}", url.toString(), new Date(), map);
        Long packtime = System.currentTimeMillis();

        Map<String, String> paras = new HashMap<>(HTTP_PARAS);
        paras.put("ip", url.getHost());
        paras.put("port", String.valueOf(port));
        Map<String, String> rsp = HttpClient.<HashMap<String, String>> send("payback", url.getPath(),
                HttpUtil.format(map, "utf-8"), null, paras);
        Long packTime = System.currentTimeMillis();
        if (LOG.isDebugEnabled())
            LOG.debug("orderNo=" + od.orderNo + " postBack" + new Date() + " use time=" + (packTime - packtime)
                    + " rsp=" + rsp);
        if (RspCode.SUCCESS.code.equals(rsp.get(F_rspCode))) {
            succ = true;
        } else {
            LOG.error("payNo=" + od.payNo + "rsp=" + rsp);
        }
    } catch (Exception e) {
        succ = false;
        LOG.error(e.getMessage());
    }

    if (!succ) {
        // TODO
        // map.put(F_backUrl, order.getBackUrl());
        // Task t = createTask(TaskType.PAY_BACK.type,
        // TaskType.PAY_BACK.desc,
        // JsonUtil.encode(map), new Date().getTime());
        // try {
        // insertTask_Order(conn, t);
        // } catch (Exception e1) {
        // LOG.error(e1.getMessage());
        // }
    }

}