Java Code Examples for java.net.URI#getPort()
The following examples show how to use
java.net.URI#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: WebSocketClientHandshaker.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
static CharSequence websocketOriginValue(URI wsURL) { String scheme = wsURL.getScheme(); final String schemePrefix; int port = wsURL.getPort(); final int defaultPort; if (WebSocketScheme.WSS.name().contentEquals(scheme) || HttpScheme.HTTPS.name().contentEquals(scheme) || (scheme == null && port == WebSocketScheme.WSS.port())) { schemePrefix = HTTPS_SCHEME_PREFIX; defaultPort = WebSocketScheme.WSS.port(); } else { schemePrefix = HTTP_SCHEME_PREFIX; defaultPort = WebSocketScheme.WS.port(); } // Convert uri-host to lower case (by RFC 6454, chapter 4 "Origin of a URI") String host = wsURL.getHost().toLowerCase(Locale.US); if (port != defaultPort && port != -1) { // if the port is not standard (80/443) its needed to add the port to the header. // See http://tools.ietf.org/html/rfc6454#section-6.2 return schemePrefix + NetUtil.toSocketAddressString(host, port); } return schemePrefix + host; }
Example 2
Source File: StaticNameResolverProvider.java From grpc-spring-boot-starter with MIT License | 6 votes |
/** * Creates a new {@link NameResolver} for the given authority and attributes. * * @param targetAuthority The authority to connect to. * @param defaultPort The default port to use, if none is specified. * @return The newly created name resolver for the given target. */ private NameResolver of(final String targetAuthority, int defaultPort) { requireNonNull(targetAuthority, "targetAuthority"); // Determine target ips final String[] hosts = PATTERN_COMMA.split(targetAuthority); final List<EquivalentAddressGroup> targets = new ArrayList<>(hosts.length); for (final String host : hosts) { final URI uri = URI.create("//" + host); int port = uri.getPort(); if (port == -1) { port = defaultPort; } targets.add(new EquivalentAddressGroup(new InetSocketAddress(uri.getHost(), port))); } if (targets.isEmpty()) { throw new IllegalArgumentException("Must have at least one target, but was: " + targetAuthority); } return new StaticNameResolver(targetAuthority, targets); }
Example 3
Source File: BinaryJedis.java From cachecloud with Apache License 2.0 | 6 votes |
private void initializeClientFromURI(URI uri) { if (!JedisURIHelper.isValid(uri)) { throw new InvalidURIException(String.format( "Cannot open Redis connection due invalid URI. %s", uri.toString())); } client = new Client(uri.getHost(), uri.getPort()); String password = JedisURIHelper.getPassword(uri); if (password != null) { client.auth(password); client.getStatusCodeReply(); } int dbIndex = JedisURIHelper.getDBIndex(uri); if (dbIndex > 0) { client.select(dbIndex); client.getStatusCodeReply(); client.setDb(dbIndex); } }
Example 4
Source File: RMINotifier.java From juddi with Apache License 2.0 | 6 votes |
public RMINotifier(BindingTemplate bindingTemplate) throws IOException, URISyntaxException, NotBoundException { super(); if (!AccessPointType.END_POINT.toString().equalsIgnoreCase(bindingTemplate.getAccessPointType())) { log.error("rmi enpoints only support AccessPointType " + AccessPointType.END_POINT); } String accessPointUrl = bindingTemplate.getAccessPointUrl().toLowerCase(); if (!accessPointUrl.startsWith("rmi")) { log.warn("rmi accessPointUrl for bindingTemplate " + bindingTemplate.getEntityKey() + " should start with 'rmi'"); } URI accessPointURI = new URI(accessPointUrl); String host = accessPointURI.getHost(); int port = accessPointURI.getPort(); String path = accessPointURI.getPath(); log.debug("Connecting to " + host + ":" + port); Registry registry = LocateRegistry.getRegistry(host, port); subscriptionListenerPort = (UDDISubscriptionListenerPortType) registry.lookup(path); }
Example 5
Source File: TargetDTO.java From galeb with Apache License 2.0 | 6 votes |
private String hcHostDefaultFromTarget(Target target) { URI targetURI; try { String targetName = target.getName(); targetURI = URI.create(targetName); } catch (Exception ignore) { targetURI = URI.create("http://invalidhost.invaliddomain"); } int port = targetURI.getPort(); if (port <= 0) { if ("https".equalsIgnoreCase(targetURI.getScheme())) { port = 443; } else { port = 80; } } return targetURI.getHost() + ":" + port; }
Example 6
Source File: NettyHttpClient.java From jiguang-java-client-common with MIT License | 6 votes |
public void send(ByteBuf body, HttpMethod method, URI uri) { String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); int port = uri.getPort(); if (port == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80; } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } _channel = b.connect(host, port).syncUninterruptibly().channel(); HttpRequest request; if (null != body) { request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, uri.getRawPath(), body); request.headers().set(HttpHeaderNames.CONTENT_LENGTH, (long) body.readableBytes()); } else { request = new DefaultFullHttpRequest(HTTP_1_1, method, uri.getRawPath()); } request.headers().set(HttpHeaderNames.HOST, uri.getHost()); request.headers().set(HttpHeaderNames.AUTHORIZATION, _authCode); request.headers().set("Content-Type", "application/json;charset=utf-8"); LOG.info("Sending request. " + request); LOG.info("Send body: " + body); _channel.writeAndFlush(request); }
Example 7
Source File: ITBootListener.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
protected void selectPort(String cfgKey) { String endpoint = DynamicPropertyFactory.getInstance().getStringProperty(cfgKey, null).get(); if (endpoint == null) { return; } URI uri = URI.create("http://" + endpoint); if (uri.getPort() == 0) { int port = getRandomPort(); try { ConcurrentCompositeConfiguration config = (ConcurrentCompositeConfiguration) DynamicPropertyFactory .getBackingConfigurationSource(); endpoint = new URIBuilder("http://" + endpoint).setPort(port).build().toString().substring(7); config.getConfiguration(0).setProperty(cfgKey, endpoint); LOGGER.info("change {} to {}.", cfgKey, endpoint); } catch (URISyntaxException e) { throw new IllegalStateException("Failed to build endpoint.", e); } } }
Example 8
Source File: IamAuthenticatingUtils.java From super-cloudops with Apache License 2.0 | 5 votes |
/** * Get the URI address of the authenticator interface on the client or * server side.</br> * e.g. * * <pre> * http://iam.xx.com/iam-server/xx/list?id=1 => http://iam.xx.com/iam-server/authenticator?id=1 * http://iam.xx.com/xx/list?id=1 => http://iam.xx.com/xx/authenticator?id=1 * http://iam.xx.com/xx/list/?id=1 => http://iam.xx.com/xx/authenticator?id=1 * http://iam.xx.com:8080/xx/list/?id=1 => http://iam.xx.com:8080/xx/authenticator?id=1 * /view/index.html => /view/index.html * </pre> * <p> * Implementing the IAM-CAS protocol: When successful login, you must * redirect to the back-end server URI of IAM-CAS-Client. (Note: URI of * front-end pages can not be used directly). * * @param url * @return * @see {@link com.wl4g.devops.iam.client.filter.AuthenticatorAuthenticationFilter} * @see {@link com.wl4g.devops.iam.filter.AuthenticatorAuthenticationFilter#determineSuccessUrl()} */ public static String correctAuthenticaitorURI(String url) { if (isBlank(url)) { return EMPTY; } try { URI _uri = new URI(url); // e.g. /view/index.html => /view/index.html if (isAnyBlank(_uri.getScheme(), _uri.getHost())) { return url; } if (!endsWith(_uri.getPath(), URI_AUTHENTICATOR)) { String portPart = (_uri.getPort() == 80 || _uri.getPort() == 443 || _uri.getPort() < 0) ? EMPTY : (":" + _uri.getPort()); String queryPart = isBlank(_uri.getQuery()) ? EMPTY : ("?" + _uri.getQuery()); String contextPath = _uri.getPath(); String[] pathPart = split(_uri.getPath(), "/"); if (pathPart.length > 1) { contextPath = "/" + pathPart[0]; } return new StringBuffer(_uri.getScheme()).append("://").append(_uri.getHost()).append(portPart) .append(contextPath).append(URI_AUTHENTICATOR).append(queryPart).toString(); } return url; } catch (URISyntaxException e) { throw new IllegalStateException("Can't to obtain a redirect authenticaitor URL.", e); } }
Example 9
Source File: PeerSpanDecorator.java From riptide with MIT License | 5 votes |
@Override public void onRequest(final Span span, final RequestArguments arguments) { final URI uri = arguments.getRequestUri(); final int port = uri.getPort(); span.setTag(PEER_HOSTNAME, uri.getHost()); if (port == -1) { span.setTag(PEER_ADDRESS, uri.getHost()); } else { span.setTag(PEER_ADDRESS, uri.getHost() + ":" + port); span.setTag(PEER_PORT, port); } }
Example 10
Source File: Netty4ClientHttpRequest.java From lams with GNU General Public License v2.0 | 5 votes |
private static int getPort(URI uri) { int port = uri.getPort(); if (port == -1) { if ("http".equalsIgnoreCase(uri.getScheme())) { port = 80; } else if ("https".equalsIgnoreCase(uri.getScheme())) { port = 443; } } return port; }
Example 11
Source File: ActiveMQXAConnectionFactoryTest.java From activemq-artemis with Apache License 2.0 | 5 votes |
protected void assertCreateConnection(String uri) throws Exception { // Start up a broker with a tcp connector. broker = new BrokerService(); broker.setPersistent(false); broker.setUseJmx(false); TransportConnector connector = broker.addConnector(uri); broker.start(); URI temp = new URI(uri); // URI connectURI = connector.getServer().getConnectURI(); // TODO this sometimes fails when using the actual local host name URI currentURI = new URI(connector.getPublishableConnectString()); // sometimes the actual host name doesn't work in this test case // e.g. on OS X so lets use the original details but just use the actual // port URI connectURI = new URI(temp.getScheme(), temp.getUserInfo(), temp.getHost(), currentURI.getPort(), temp.getPath(), temp.getQuery(), temp.getFragment()); LOG.info("connection URI is: " + connectURI); // This should create the connection. ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory(connectURI); Connection connection = cf.createConnection(); assertXAConnection(connection); assertNotNull(connection); connection.close(); connection = cf.createXAConnection(); assertXAConnection(connection); assertNotNull(connection); }
Example 12
Source File: StratosServerExtension.java From attic-stratos with Apache License 2.0 | 5 votes |
private int startActiveMQServer() throws AutomationFrameworkException { try { String activemqBindAddress = getParameters().get(Util.ACTIVEMQ_BIND_ADDRESS); if (activemqBindAddress == null) { throw new AutomationFrameworkException("ActiveMQ bind address not found in automation.xml"); } URI givenURI = new URI(activemqBindAddress); int initAMQPort = givenURI.getPort(); // dynamically pick an open port starting from initial port given in automation.xml while (!Util.isPortAvailable(initAMQPort)) { initAMQPort++; } URI dynamicURL = new URI(givenURI.getScheme(), givenURI.getUserInfo(), givenURI.getHost(), initAMQPort, givenURI.getPath(), givenURI.getQuery(), givenURI.getFragment()); long time1 = System.currentTimeMillis(); log.info("Starting ActiveMQ with dynamic bind address: " + dynamicURL.toString()); broker.setDataDirectory(StratosServerExtension.class.getResource(File.separator).getPath() + File.separator + ".." + File.separator + "activemq-data"); broker.setBrokerName("testBroker"); broker.addConnector(dynamicURL.toString()); broker.start(); long time2 = System.currentTimeMillis(); log.info(String.format("ActiveMQ started in %d sec", (time2 - time1) / 1000)); return initAMQPort; } catch (Exception e) { throw new AutomationFrameworkException("Could not start ActiveMQ", e); } }
Example 13
Source File: FailoverUriPool.java From qpid-jms with Apache License 2.0 | 5 votes |
private boolean compareURIs(final URI first, final URI second) { boolean result = false; if (first == null || second == null) { return result; } if (first.getPort() == second.getPort()) { InetAddress firstAddr = null; InetAddress secondAddr = null; try { firstAddr = InetAddress.getByName(first.getHost()); secondAddr = InetAddress.getByName(second.getHost()); if (firstAddr.equals(secondAddr)) { result = true; } } catch (IOException e) { if (firstAddr == null) { LOG.error("Failed to Lookup INetAddress for URI[ " + first + " ] : " + e); } else { LOG.error("Failed to Lookup INetAddress for URI[ " + second + " ] : " + e); } if (first.getHost().equalsIgnoreCase(second.getHost())) { result = true; } } } return result; }
Example 14
Source File: Status.java From orion.server with Eclipse Public License 1.0 | 5 votes |
private URI statusToIndexLocation(URI u) throws URISyntaxException { String uriPath = u.getPath(); String prefix = uriPath.substring(0, uriPath.indexOf(GitServlet.GIT_URI)); uriPath = uriPath.substring(prefix.length() + (GitServlet.GIT_URI + '/' + Status.RESOURCE).length()); uriPath = prefix + GitServlet.GIT_URI + '/' + Index.RESOURCE + uriPath; return new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), uriPath, u.getQuery(), u.getFragment()); }
Example 15
Source File: AbstractHttpClient.java From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 | 5 votes |
public final HttpContext createContext(URI uri, UsernamePasswordCredentials creds) throws Exception { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(uri.getHost(), uri.getPort()), creds); org.apache.http.HttpHost host = new org.apache.http.HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(host, basicAuth); HttpClientContext context1 = HttpClientContext.create(); context1.setCredentialsProvider(credsProvider); context1.setAuthCache(authCache); return context1; }
Example 16
Source File: HttpSenderBase.java From iaf with Apache License 2.0 | 5 votes |
protected int getPort(URI uri) { int port = uri.getPort(); if (port<1) { try { URL url = uri.toURL(); port = url.getDefaultPort(); log.debug(getLogPrefix()+"looked up protocol for scheme ["+uri.getScheme()+"] to be port ["+port+"]"); } catch (Exception e) { log.debug(getLogPrefix()+"protocol for scheme ["+uri.getScheme()+"] not found, setting port to 80",e); port=80; } } return port; }
Example 17
Source File: SFTPFileSystemLoggingTest.java From sftp-fs with Apache License 2.0 | 4 votes |
@Test public void testLogging() throws IOException { URI uri = getURI(); try (SFTPFileSystem fs = newFileSystem(uri, createEnv())) { SFTPFileSystemProvider.keepAlive(fs); } URI brokenUri; try (ServerSocket serverSocket = new ServerSocket(0)) { brokenUri = URI.create("sftp://localhost:" + serverSocket.getLocalPort()); } assertThrows(IOException.class, () -> FileSystems.newFileSystem(brokenUri, createEnv())); ArgumentCaptor<LoggingEvent> captor = ArgumentCaptor.forClass(LoggingEvent.class); verify(appender, atLeast(1)).doAppend(captor.capture()); List<Object> debugMessages = new ArrayList<>(); Set<String> names = new HashSet<>(); Set<Level> levels = new HashSet<>(); List<Throwable> thrown = new ArrayList<>(); for (LoggingEvent event : captor.getAllValues()) { names.add(event.getLoggerName()); levels.add(event.getLevel()); if (Level.DEBUG.equals(event.getLevel())) { debugMessages.add(event.getMessage()); } if (event.getThrowableInformation() != null) { thrown.add(event.getThrowableInformation().getThrowable()); } } assertThat(names, contains(SSHChannelPool.class.getName())); assertThat(levels, contains(Level.DEBUG)); String hostname = uri.getHost(); int port = uri.getPort(); if (port == -1) { assertThat(debugMessages, hasItem("Creating SSHChannelPool to " + hostname + " with poolSize 1 and poolWaitTimeout 0")); assertThat(debugMessages, hasItem("Created SSHChannelPool to " + hostname + " with poolSize 1")); } else { assertThat(debugMessages, hasItem("Creating SSHChannelPool to " + hostname + ":" + port + " with poolSize 1 and poolWaitTimeout 0")); assertThat(debugMessages, hasItem("Created SSHChannelPool to " + hostname + ":" + port + " with poolSize 1")); } assertThat(debugMessages, hasItem("Failed to create SSHChannelPool, disconnecting all created channels")); assertThat(debugMessages, hasItem(new RegexMatcher("Created new channel with id 'channel-\\d+' \\(pooled: true\\)"))); assertThat(debugMessages, hasItem(new RegexMatcher("Took channel 'channel-\\d+' from pool, current pool size: 0"))); assertThat(debugMessages, hasItem(new RegexMatcher("Reference count for channel 'channel-\\d+' increased to 1"))); assertThat(debugMessages, hasItem(new RegexMatcher("Reference count for channel 'channel-\\d+' decreased to 0"))); assertThat(debugMessages, hasItem(new RegexMatcher("Returned channel 'channel-\\d+' to pool, current pool size: 1"))); assertThat(debugMessages, hasItem("Drained pool for keep alive")); assertThat(debugMessages, hasItem("Drained pool for close")); assertThat(debugMessages, hasItem(new RegexMatcher("Disconnected channel 'channel-\\d+'"))); assertThat(thrown, contains(Matchers.<Throwable>instanceOf(IOException.class))); }
Example 18
Source File: HTTPClient.java From gocd-build-status-notifier with Apache License 2.0 | 4 votes |
private HttpHost getHttpHost(String url) throws Exception { URI uri = new URI(url); return new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); }
Example 19
Source File: AbstractFileSystem.java From big-c with Apache License 2.0 | 4 votes |
/** * Check that a Path belongs to this FileSystem. * * If the path is fully qualified URI, then its scheme and authority * matches that of this file system. Otherwise the path must be * slash-relative name. * * @throws InvalidPathException if the path is invalid */ public void checkPath(Path path) { URI uri = path.toUri(); String thatScheme = uri.getScheme(); String thatAuthority = uri.getAuthority(); if (thatScheme == null) { if (thatAuthority == null) { if (path.isUriPathAbsolute()) { return; } throw new InvalidPathException("relative paths not allowed:" + path); } else { throw new InvalidPathException( "Path without scheme with non-null authority:" + path); } } String thisScheme = this.getUri().getScheme(); String thisHost = this.getUri().getHost(); String thatHost = uri.getHost(); // Schemes and hosts must match. // Allow for null Authority for file:/// if (!thisScheme.equalsIgnoreCase(thatScheme) || (thisHost != null && !thisHost.equalsIgnoreCase(thatHost)) || (thisHost == null && thatHost != null)) { throw new InvalidPathException("Wrong FS: " + path + ", expected: " + this.getUri()); } // Ports must match, unless this FS instance is using the default port, in // which case the port may be omitted from the given URI int thisPort = this.getUri().getPort(); int thatPort = uri.getPort(); if (thatPort == -1) { // -1 => defaultPort of Uri scheme thatPort = this.getUriDefaultPort(); } if (thisPort != thatPort) { throw new InvalidPathException("Wrong FS: " + path + ", expected: " + this.getUri()); } }
Example 20
Source File: TestUrlStreamHandler.java From big-c with Apache License 2.0 | 4 votes |
/** * Test opening and reading from an InputStream through a hdfs:// URL. * <p> * First generate a file with some content through the FileSystem API, then * try to open and read the file through the URL stream API. * * @throws IOException */ @Test public void testDfsUrls() throws IOException { Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build(); FileSystem fs = cluster.getFileSystem(); // Setup our own factory // setURLSteramHandlerFactor is can be set at most once in the JVM // the new URLStreamHandler is valid for all tests cases // in TestStreamHandler FsUrlStreamHandlerFactory factory = new org.apache.hadoop.fs.FsUrlStreamHandlerFactory(); java.net.URL.setURLStreamHandlerFactory(factory); Path filePath = new Path("/thefile"); try { byte[] fileContent = new byte[1024]; for (int i = 0; i < fileContent.length; ++i) fileContent[i] = (byte) i; // First create the file through the FileSystem API OutputStream os = fs.create(filePath); os.write(fileContent); os.close(); // Second, open and read the file content through the URL API URI uri = fs.getUri(); URL fileURL = new URL(uri.getScheme(), uri.getHost(), uri.getPort(), filePath .toString()); InputStream is = fileURL.openStream(); assertNotNull(is); byte[] bytes = new byte[4096]; assertEquals(1024, is.read(bytes)); is.close(); for (int i = 0; i < fileContent.length; ++i) assertEquals(fileContent[i], bytes[i]); // Cleanup: delete the file fs.delete(filePath, false); } finally { fs.close(); cluster.shutdown(); } }