java.net.URL#getPort ( )源码实例Demo

下面列出了java.net.URL#getPort ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: mrgeo   文件: KmlGenerator.java
@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;
}
 
源代码2 项目: streamsx.topology   文件: Instance.java
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);
    }
}
 
源代码3 项目: floobits-intellij   文件: FlooUrl.java
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;
        }
    }
}
 
源代码4 项目: dragonwell8_jdk   文件: AuthenticationInfo.java
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);
    }

}
 
源代码5 项目: openjdk-jdk8u-backup   文件: HttpURLConnection.java
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);
}
 
源代码6 项目: sakai   文件: HttpTransactionUtils.java
/**
  * 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();
}
 
源代码7 项目: SciGraph   文件: EntityProcessorImpl.java
/***
 * @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();
}
 
源代码8 项目: karaf-decanter   文件: ElasticsearchCollector.java
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);
}
 
源代码9 项目: xjar   文件: XJarClassLoader.java
@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;
    }
}
 
源代码10 项目: DoraemonKit   文件: ObsoleteUrlFactory.java
@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");
}
 
源代码11 项目: flink   文件: ElasticsearchValidator.java
/**
 * 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;
}
 
源代码12 项目: hottub   文件: KeepAliveCache.java
/**
 * 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;
}
 
源代码13 项目: weblaf   文件: NetUtils.java
/**
 * 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 () : "" );
}
 
源代码14 项目: abstract-operator   文件: SDKEntrypoint.java
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;
    }
}
 
源代码15 项目: lucene-solr   文件: JettySolrRunnerTest.java
@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();
  }

}
 
源代码16 项目: tomee   文件: TomcatClassPath.java
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);
}
 
源代码17 项目: cxf-fediz   文件: 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);
    }
    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);
}
 
源代码18 项目: Bytecoder   文件: HttpURLConnection.java
static String connectRequestURI(URL url) {
    String host = url.getHost();
    int port = url.getPort();
    port = port != -1 ? port : url.getDefaultPort();

    return host + ":" + port;
}
 
源代码19 项目: openjdk-jdk8u-backup   文件: HttpURLConnection.java
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;
}
 
源代码20 项目: jframe   文件: WxpayServiceImpl.java
/**
 * 通知租车后台
 * 
 * @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());
        // }
    }

}