List of usage examples for java.net URI getPort
public int getPort()
From source file:me.carbou.mathieu.tictactoe.di.ServiceBindings.java
@Provides @Singleton/*from ww w . ja v a2s . c om*/ JedisPool jedisPool() { URI connectionURI = URI.create(Env.REDISCLOUD_URL); GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMinIdle(0); config.setMaxIdle(5); config.setMaxTotal(30); String password = connectionURI.getUserInfo().split(":", 2)[1]; return new JedisPool(config, connectionURI.getHost(), connectionURI.getPort(), Protocol.DEFAULT_TIMEOUT, password); }
From source file:ee.ria.xroad.proxy.clientproxy.FastestSocketSelector.java
private SocketInfo initConnections(Selector selector) throws IOException { log.trace("initConnections()"); for (URI target : addresses) { SocketChannel channel = SocketChannel.open(); channel.setOption(StandardSocketOptions.TCP_NODELAY, true); channel.configureBlocking(false); try {/*from w ww . j ava2 s . c o m*/ channel.register(selector, SelectionKey.OP_CONNECT, target); if (channel.connect(new InetSocketAddress(target.getHost(), target.getPort()))) { // connected immediately channel.configureBlocking(true); return new SocketInfo(target, channel.socket()); } } catch (Exception e) { closeQuietly(channel); log.trace("Error connecting to '{}': {}", target, e); } } return null; }
From source file:org.duracloud.common.web.RestHttpHelper.java
private HttpResponse executeRequest(String url, Method method, HttpEntity requestEntity, Map<String, String> headers) throws IOException { if (url == null || url.length() == 0) { throw new IllegalArgumentException("URL must be a non-empty value"); }/* w ww. j a v a 2s . c o m*/ HttpRequestBase httpRequest = method.getMethod(url, requestEntity); if (headers != null && headers.size() > 0) { addHeaders(httpRequest, headers); } if (log.isDebugEnabled()) { log.debug(loggingRequestText(url, method, requestEntity, headers)); } org.apache.http.HttpResponse response; if (null != credsProvider) { HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider); if (socketTimeoutMs > -1) { BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager(); cm.setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeoutMs).build()); builder.setConnectionManager(cm); } CloseableHttpClient httpClient = buildClient(builder, method); // Use preemptive basic auth URI requestUri = httpRequest.getURI(); HttpHost target = new HttpHost(requestUri.getHost(), requestUri.getPort(), requestUri.getScheme()); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); response = httpClient.execute(httpRequest, localContext); } else { CloseableHttpClient httpClient = buildClient(HttpClients.custom(), method); response = httpClient.execute(httpRequest); } HttpResponse httpResponse = new HttpResponse(response); if (log.isDebugEnabled()) { log.debug(loggingResponseText(httpResponse)); } return httpResponse; }
From source file:com.emc.ecs.sync.SyncProcessTest.java
@Test public void testSourceObjectNotFound() throws Exception { Properties syncProperties = SyncConfig.getProperties(); String bucket = "ecs-sync-test-source-not-found"; String endpoint = syncProperties.getProperty(SyncConfig.PROP_S3_ENDPOINT); String accessKey = syncProperties.getProperty(SyncConfig.PROP_S3_ACCESS_KEY_ID); String secretKey = syncProperties.getProperty(SyncConfig.PROP_S3_SECRET_KEY); boolean useVHost = Boolean.valueOf(syncProperties.getProperty(SyncConfig.PROP_S3_VHOST)); Assume.assumeNotNull(endpoint, accessKey, secretKey); URI endpointUri = new URI(endpoint); S3Config s3Config;/*from w w w . j a v a 2 s . c o m*/ if (useVHost) s3Config = new S3Config(endpointUri); else s3Config = new S3Config(Protocol.valueOf(endpointUri.getScheme().toUpperCase()), endpointUri.getHost()); s3Config.withPort(endpointUri.getPort()).withUseVHost(useVHost).withIdentity(accessKey) .withSecretKey(secretKey); S3Client s3 = new S3JerseyClient(s3Config); try { s3.createBucket(bucket); } catch (S3Exception e) { if (!e.getErrorCode().equals("BucketAlreadyExists")) throw e; } try { File sourceKeyList = TestUtil.writeTempFile("this-key-does-not-exist"); EcsS3Source source = new EcsS3Source(); source.setEndpoint(endpointUri); source.setProtocol(endpointUri.getScheme()); source.setVdcs(Collections.singletonList(new Vdc(endpointUri.getHost()))); source.setPort(endpointUri.getPort()); source.setEnableVHosts(useVHost); source.setAccessKey(accessKey); source.setSecretKey(secretKey); source.setBucketName(bucket); source.setSourceKeyList(sourceKeyList); DbService dbService = new SqliteDbService(":memory:"); EcsSync sync = new EcsSync(); sync.setSource(source); sync.setTarget(new TestObjectTarget()); sync.setDbService(dbService); sync.run(); Assert.assertEquals(0, sync.getObjectsComplete()); Assert.assertEquals(1, sync.getObjectsFailed()); Assert.assertEquals(1, sync.getFailedObjects().size()); SyncObject syncObject = sync.getFailedObjects().iterator().next(); Assert.assertNotNull(syncObject); SyncRecord syncRecord = dbService.getSyncRecord(sync.getFailedObjects().iterator().next()); Assert.assertNotNull(syncRecord); Assert.assertEquals(ObjectStatus.Error, syncRecord.getStatus()); } finally { try { s3.deleteBucket(bucket); } catch (Throwable t) { // ignore } } }
From source file:com.microsoft.tfs.client.common.util.TeamContextCache.java
private String getCacheKey(final TFSTeamProjectCollection connection) { /*/*w w w. j av a 2 s . c o m*/ * So TeamContextCache is useful offline, we must use only attributes * from the connection that can be read offline. The connection's * instance ID plus the authorized user name would combine to make an * ideal key here, but those require a round-trip to the server. The URI * will do instead. */ final URI uri = connection.getBaseURI(); // Convert the URI parts to something more pref-key-like return String.format("%s/%s/%d/%s", uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath()) //$NON-NLS-1$ .toLowerCase(); }
From source file:com.allstate.client.core.SoapClient.java
private void configureAuthentication(URI uri, Security security) { if (security.isAuthEnabled()) { AuthScope scope = new AuthScope(uri.getHost(), uri.getPort()); Credentials credentials = null;//from www .j av a 2 s . c o m if (security.isAuthBasic()) { credentials = new UsernamePasswordCredentials(security.getAuthUsername(), security.getAuthPassword()); } else if (security.isAuthDigest()) { credentials = new UsernamePasswordCredentials(security.getAuthUsername(), security.getAuthPassword()); } else if (security.isAuthNtlm()) { // TODO credentials = new NTCredentials(security.getAuthUsername(), security.getAuthPassword(), null, null); } else if (security.isAuthSpnego()) { // TODO } client.getCredentialsProvider().setCredentials(scope, credentials); } }
From source file:io.gravitee.gateway.http.vertx.VertxHttpClient.java
@Override public ClientRequest request(io.gravitee.common.http.HttpMethod method, URI uri, HttpHeaders headers, Handler<ClientResponse> responseHandler) { HttpClient httpClient = httpClients.computeIfAbsent(Vertx.currentContext(), createHttpClient()); final int port = uri.getPort() != -1 ? uri.getPort() : (HTTPS_SCHEME.equals(uri.getScheme()) ? 443 : 80); String relativeUri = (uri.getRawQuery() == null) ? uri.getRawPath() : uri.getRawPath() + '?' + uri.getRawQuery(); HttpClientRequest clientRequest = httpClient.request(convert(method), port, uri.getHost(), relativeUri, clientResponse -> handleClientResponse(clientResponse, responseHandler)); clientRequest.setTimeout(endpoint.getHttpClientOptions().getReadTimeout()); VertxClientRequest invokerRequest = new VertxClientRequest(clientRequest); clientRequest.exceptionHandler(event -> { LOGGER.error("Server proxying failed: {}", event.getMessage()); if (invokerRequest.connectTimeoutHandler() != null && event instanceof ConnectTimeoutException) { invokerRequest.connectTimeoutHandler().handle(event); } else {//from www. j a va 2s .co m VertxClientResponse clientResponse = new VertxClientResponse( ((event instanceof ConnectTimeoutException) || (event instanceof TimeoutException)) ? HttpStatusCode.GATEWAY_TIMEOUT_504 : HttpStatusCode.BAD_GATEWAY_502); clientResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE); Buffer buffer = null; if (event.getMessage() != null) { // Create body content with error message buffer = Buffer.buffer(event.getMessage()); clientResponse.headers().set(HttpHeaders.CONTENT_LENGTH, Integer.toString(buffer.length())); } responseHandler.handle(clientResponse); if (buffer != null) { clientResponse.bodyHandler().handle(buffer); } clientResponse.endHandler().handle(null); } }); // Copy headers to final API copyRequestHeaders(headers, clientRequest, (port == 80 || port == 443) ? uri.getHost() : uri.getHost() + ':' + port); // Check chunk flag on the request if there are some content to push and if transfer_encoding is set // with chunk value if (hasContent(headers)) { String transferEncoding = headers.getFirst(HttpHeaders.TRANSFER_ENCODING); if (HttpHeadersValues.TRANSFER_ENCODING_CHUNKED.equalsIgnoreCase(transferEncoding)) { clientRequest.setChunked(true); } } // Send HTTP head as soon as possible clientRequest.sendHead(); return invokerRequest; }
From source file:org.xwiki.wysiwyg.internal.plugin.alfresco.server.TicketAuthenticator.java
@Override public void authenticate(HttpRequestBase request) { String ticket = null;//ww w. j a v a2 s . c om //get ticket from DB AlfrescoTiket dbTiket = ticketManager.getTicket(); //if there is a ticket for current user,use it if (dbTiket != null) { ticket = dbTiket.getTiket(); } /*if (ticket != null) { if (!ticketManager.validateAuthenticationTicket(ticket)) { //if ticket is not valid on alfresco, perform authentication ticket = getAuthenticationTicket(); } } else { //if there is no ticket in DB, perform authentication ticket = getAuthenticationTicket(); }*/ // Add the ticket to the query string. URI uri = request.getURI(); List<NameValuePair> parameters = URLEncodedUtils.parse(uri, QUERY_STRING_ENCODING); parameters.add(new BasicNameValuePair(AUTH_TICKET_PARAM, ticket)); String query = URLEncodedUtils.format(parameters, QUERY_STRING_ENCODING); try { request.setURI(URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getRawPath(), query, uri.getRawFragment())); } catch (URISyntaxException e) { // This shouldn't happen. } }
From source file:com.sap.core.odata.fit.basic.issues.TestIssue105.java
@Test public void checkContextForDifferentHostNamesRequests() throws ClientProtocolException, IOException, ODataException, URISyntaxException { URI uri1 = URI.create(getEndpoint().toString() + "$metadata"); HttpGet get1 = new HttpGet(uri1); HttpResponse response1 = getHttpClient().execute(get1); assertNotNull(response1);// w w w . j a v a 2s . c o m URI serviceRoot1 = getService().getProcessor().getContext().getPathInfo().getServiceRoot(); assertEquals(uri1.getHost(), serviceRoot1.getHost()); get1.reset(); URI uri2 = new URI(uri1.getScheme(), uri1.getUserInfo(), "127.0.0.1", uri1.getPort(), uri1.getPath(), uri1.getQuery(), uri1.getFragment()); HttpGet get2 = new HttpGet(uri2); HttpResponse response2 = getHttpClient().execute(get2); assertNotNull(response2); URI serviceRoot2 = getService().getProcessor().getContext().getPathInfo().getServiceRoot(); assertEquals(uri2.getHost(), serviceRoot2.getHost()); }
From source file:com.alexkli.jhb.Worker.java
@Override public void run() { try {/* w w w . j av a 2 s . c o m*/ while (true) { long start = System.nanoTime(); QueueItem<HttpRequestBase> item = queue.take(); idleAvg.add(System.nanoTime() - start); if (item.isPoisonPill()) { return; } HttpRequestBase request = item.getRequest(); if ("java".equals(config.client)) { System.setProperty("http.keepAlive", "false"); item.sent(); try { HttpURLConnection http = (HttpURLConnection) new URL(request.getURI().toString()) .openConnection(); http.setConnectTimeout(5000); http.setReadTimeout(5000); int statusCode = http.getResponseCode(); consumeAndCloseStream(http.getInputStream()); if (statusCode == 200) { item.done(); } else { item.failed(); } } catch (IOException e) { System.err.println("Failed request: " + e.getMessage()); e.printStackTrace(); // System.exit(2); item.failed(); } } else if ("ahc".equals(config.client)) { try { item.sent(); try (CloseableHttpResponse response = httpClient.execute(request, context)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { item.done(); } else { item.failed(); } } } catch (IOException e) { System.err.println("Failed request: " + e.getMessage()); item.failed(); } } else if ("fast".equals(config.client)) { try { URI uri = request.getURI(); item.sent(); InetAddress addr = InetAddress.getByName(uri.getHost()); Socket socket = new Socket(addr, uri.getPort()); PrintWriter out = new PrintWriter(socket.getOutputStream()); // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // send an HTTP request to the web server out.println("GET / HTTP/1.1"); out.append("Host: ").append(uri.getHost()).append(":").println(uri.getPort()); out.println("Connection: Close"); out.println(); out.flush(); // read the response consumeAndCloseStream(socket.getInputStream()); // boolean loop = true; // StringBuilder sb = new StringBuilder(8096); // while (loop) { // if (in.ready()) { // int i = 0; // while (i != -1) { // i = in.read(); // sb.append((char) i); // } // loop = false; // } // } item.done(); socket.close(); } catch (IOException e) { e.printStackTrace(); item.failed(); } } else if ("nio".equals(config.client)) { URI uri = request.getURI(); item.sent(); String requestBody = "GET / HTTP/1.1\n" + "Host: " + uri.getHost() + ":" + uri.getPort() + "\n" + "Connection: Close\n\n"; try { InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort()); SocketChannel channel = SocketChannel.open(); channel.socket().setSoTimeout(5000); channel.connect(addr); ByteBuffer msg = ByteBuffer.wrap(requestBody.getBytes()); channel.write(msg); msg.clear(); ByteBuffer buf = ByteBuffer.allocate(1024); int count; while ((count = channel.read(buf)) != -1) { buf.flip(); byte[] bytes = new byte[count]; buf.get(bytes); buf.clear(); } channel.close(); item.done(); } catch (IOException e) { e.printStackTrace(); item.failed(); } } } } catch (InterruptedException e) { System.err.println("Worker thread [" + this.toString() + "] was interrupted: " + e.getMessage()); } }