List of usage examples for java.net URI getPort
public int getPort()
From source file:com.springsource.insight.plugin.springweb.http.SimpleClientHttpRequestFactoryCollectionAspectTest.java
private ExternalResourceDescriptor assertExternalResource(Operation op, URI uri) { Collection<ExternalResourceDescriptor> descs = extAnalyzer .locateExternalResourceName(creatMockOperationTraceWrapper(op)); assertEquals("Mismatched descriptors size", 1, ListUtil.size(descs)); ExternalResourceDescriptor desc = ListUtil.getFirstMember(descs); assertEquals("Mismatched host", uri.getHost(), desc.getHost()); assertEquals("Mismatched port", uri.getPort(), desc.getPort()); assertEquals("Mismatched type", ExternalResourceType.WEB_SERVER.name(), desc.getType()); assertFalse("Outgoing link ?", desc.isIncoming()); assertFalse("Parent descriptor ?", desc.isParent()); return desc;//from w w w . j a va2s . c o m }
From source file:io.curly.artifact.web.remote.PaperclipLinkCatcher.java
private String reconstructURI(String host, String href) { URI original; try {/*from ww w. ja v a 2 s. c o m*/ original = new URI(href); } catch (URISyntaxException e) { throw new IllegalArgumentException("Cannot create URI from: " + href); } int port = 80; if ("https".equals(original.getScheme())) { port = 443; } if (host.contains(":")) { String[] pair = host.split(":"); host = pair[0]; port = Integer.valueOf(pair[1]); } if (host.equals(original.getHost()) && port == original.getPort()) { return href; } String scheme = original.getScheme(); if (scheme == null) { scheme = port == 443 ? "https" : "http"; } StringBuilder sb = new StringBuilder(); sb.append(scheme).append("://"); if (StringUtils.hasText(original.getRawUserInfo())) { sb.append(original.getRawUserInfo()).append("@"); } sb.append(host); if (port >= 0) { sb.append(":").append(port); } sb.append(original.getPath()); if (StringUtils.hasText(original.getRawQuery())) { sb.append("?").append(original.getRawQuery()); } if (StringUtils.hasText(original.getRawFragment())) { sb.append("#").append(original.getRawFragment()); } return sb.toString(); }
From source file:com.beyondj.gateway.handlers.detecting.DetectingGateway.java
/** * Creates a new client for the given URL and handler *//* w w w . j a va2 s.c o m*/ private NetClient createClient(final ConnectionParameters params, final SocketWrapper socketFromClient, final URI url, final Buffer received) { NetClient netClient = vertx.createNetClient(); return netClient.connect(url.getPort(), url.getHost(), new Handler<AsyncResult<NetSocket>>() { public void handle(final AsyncResult<NetSocket> asyncSocket) { if (!asyncSocket.succeeded()) { handleConnectFailure(socketFromClient, String.format("Could not connect to '%s'", url)); } else { final NetSocket socketToServer = asyncSocket.result(); successfulConnectionAttempts.incrementAndGet(); socketsConnecting.remove(socketFromClient); final ConnectedSocketInfo connectedInfo = new ConnectedSocketInfo(params, url, socketFromClient, socketToServer); socketsConnected.add(connectedInfo); Handler<Void> endHandler = new Handler<Void>() { @Override public void handle(Void event) { handleShutdown(connectedInfo); } }; Handler<Throwable> exceptionHandler = new Handler<Throwable>() { @Override public void handle(Throwable event) { handleShutdown(connectedInfo); } }; socketFromClient.readStream().endHandler(endHandler); socketFromClient.readStream().exceptionHandler(exceptionHandler); socketToServer.endHandler(endHandler); socketToServer.exceptionHandler(exceptionHandler); socketToServer.write(received); Pump.createPump(socketToServer, socketFromClient.writeStream()).start(); Pump.createPump(socketFromClient.readStream(), socketToServer).start(); } } }); }
From source file:com.aurel.track.util.LdapUtil.java
/** * Gets the base URL from a complete URL (possibly with dn) * //from www .j a va2 s .c om * @param ldapServerURL * @return */ public static String getBaseURL(String ldapServerURL) { String baseURL = null; URI uri = null; try { uri = new URI(ldapServerURL); } catch (URISyntaxException e) { LOGGER.warn("Creating an URI from " + ldapServerURL + " failed with " + e.getMessage()); } if (uri != null) { // uri.get baseURL = uri.getScheme() + "://" + uri.getHost(); int port = uri.getPort(); if (port > 0) { baseURL += ":" + uri.getPort(); } baseURL += "/"; LOGGER.debug("Base url from " + ldapServerURL + " is " + baseURL); } return baseURL; }
From source file:ezid.EZIDService.java
/** * Log into the EZID service using account credentials provided by EZID. The cookie * returned by EZID is cached in a local CookieStore for the duration of the EZIDService, * and so subsequent calls using this instance of the service will function as * fully authenticated. An exception is thrown if authentication fails. * * @param username to identify the user account from EZID * @param password the secret password for this account * * @throws EZIDException if authentication fails for any reason *///from www . j a v a2s . co m public void login(String username, String password) throws EZIDException { this.username = username; this.password = password; String msg; try { URI serviceUri = new URI(LOGIN_SERVICE); HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.getScheme()); httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING.... //System.out.println("authCache: " + authCache.toString()); ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; byte[] body = null; HttpGet httpget = new HttpGet(LOGIN_SERVICE); body = httpclient.execute(httpget, handler, localcontext); String message = new String(body); msg = parseIdentifierResponse(message); // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING.... /* org.apache.http.client.CookieStore cookieStore = httpclient.getCookieStore(); System.out.println("\n\nCookies : "); List<Cookie> cookies = cookieStore.getCookies(); for (int i = 0; i < cookies.size(); i++) { System.out.println("Cookie: " + cookies.get(i)); } */ } catch (URISyntaxException e) { //System.out.println("URI SyntaxError Exception in LOGIN"); throw new EZIDException("Bad syntax for uri: " + LOGIN_SERVICE, e); } catch (ClientProtocolException e) { //System.out.println("ClientProtocol Exception in LOGIN"); throw new EZIDException(e); } catch (IOException e) { //System.out.println("IO Exception in LOGIN"); throw new EZIDException(e); } //System.out.println("Seems to be a successful LOGIN, msg= " + msg.toString()); }
From source file:com.github.tomakehurst.wiremock.testsupport.WireMockTestClient.java
public WireMockResponse getViaProxy(String url, int proxyPort) { URI targetUri = URI.create(url); HttpHost proxy = new HttpHost(address, proxyPort, targetUri.getScheme()); HttpClient httpClientUsingProxy = HttpClientBuilder.create().disableAuthCaching().disableAutomaticRetries() .disableCookieManagement().disableRedirectHandling().setProxy(proxy).build(); try {/*from w w w . j ava2s.co m*/ HttpHost target = new HttpHost(targetUri.getHost(), targetUri.getPort(), targetUri.getScheme()); HttpGet req = new HttpGet( targetUri.getPath() + (isNullOrEmpty(targetUri.getQuery()) ? "" : "?" + targetUri.getQuery())); req.removeHeaders("Host"); System.out.println("executing request to " + targetUri + "(" + target + ") via " + proxy); HttpResponse httpResponse = httpClientUsingProxy.execute(target, req); return new WireMockResponse(httpResponse); } catch (IOException ioe) { throw new RuntimeException(ioe); } }
From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java
@Override public void execute(HttpRequest request, ResponseCallback responseCallback, LoadBalancerStrategy loadBalancerStrategy, String apiName) { InternalServerProxy serverProxy = loadBalancerStrategy.getServerProxy(request); Throwable lastCaugtException = null; if (serverProxy == null) { // server proxy will be null if the configuration was not // configured properly // or if all the servers are passivated. loadBalancerStrategy.handleNullserverProxy(apiName, lastCaugtException); }//from w w w . ja v a 2 s . co m request = updateRequestUri((S) request, serverProxy); if (request.isSilentLogging()) { LOGGER.trace("sending request: {}-{}", request.getHttpMethod(), request.getUri()); } else { LOGGER.info("sending request: {}-{}", request.getHttpMethod(), request.getUri()); } org.apache.http.HttpRequest httpRequest = null; Joiner joiner = Joiner.on(",").skipNulls(); URI requestUri = buildUri(request, joiner); httpRequest = buildHttpUriRequest(request, joiner, requestUri); HttpHost httpHost = new HttpHost(requestUri.getHost(), requestUri.getPort(), requestUri.getScheme()); FlowContext flowContext = FlowContextFactory.getFlowContext(); httpAsyncClient.execute(httpHost, httpRequest, new FoundationFutureCallBack(this, request, responseCallback, serverProxy, loadBalancerStrategy, apiName, flowContext.getUniqueId())); }
From source file:com.geoxp.oss.client.OSSClient.java
public static boolean init(String ossURL, byte[] secret, String sshKeyFingerprint) throws OSSException { SSHAgentClient agent = null;//from w w w . j av a 2 s .co m HttpClient httpclient = newHttpClient(); try { agent = new SSHAgentClient(); List<SSHKey> sshkeys = agent.requestIdentities(); // // If no SSH Key fingerprint was provided, try all SSH keys available in the agent // List<String> fingerprints = new ArrayList<String>(); if (null == sshKeyFingerprint) { for (SSHKey key : sshkeys) { fingerprints.add(key.fingerprint); } } else { fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", "")); } int idx = 0; for (String fingerprint : fingerprints) { idx++; // // Ask the SSH agent for the SSH key blob // byte[] keyblob = null; for (SSHKey key : sshkeys) { if (key.fingerprint.equals(fingerprint)) { keyblob = key.blob; break; } } // // Throw an exception if this condition is encountered as it can only happen if // there was a provided fingerprint which is not in the agent. // if (null == keyblob) { throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent."); } // // Retrieve OSS RSA key // RSAPublicKey pubkey = getOSSRSA(ossURL); // // Build the initialization token // // <TS> <SECRET> <SSH Signing Key Blob> <SSH Signature Blob> // ByteArrayOutputStream token = new ByteArrayOutputStream(); byte[] tsdata = nowBytes(); token.write(CryptoHelper.encodeNetworkString(tsdata)); token.write(CryptoHelper.encodeNetworkString(secret)); token.write(CryptoHelper.encodeNetworkString(keyblob)); byte[] sigblob = agent.sign(keyblob, token.toByteArray()); token.write(CryptoHelper.encodeNetworkString(sigblob)); // // Encrypt the token with a random AES256 key // byte[] aeskey = new byte[32]; CryptoHelper.getSecureRandom().nextBytes(aeskey); byte[] wrappedtoken = CryptoHelper.wrapAES(aeskey, token.toByteArray()); // // Encrypt the random key with OSS' RSA key // byte[] sealedaeskey = CryptoHelper.encryptRSA(pubkey, aeskey); // // Create the token // token.reset(); token.write(CryptoHelper.encodeNetworkString(wrappedtoken)); token.write(CryptoHelper.encodeNetworkString(sealedaeskey)); // // Base64 encode the encryptedtoken // String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8"); // // Send request to OSS // URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_INIT); builder.addParameter("token", b64token); URI uri = builder.build(); String qs = uri.getRawQuery(); HttpPost post = new HttpPost( uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath()); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new StringEntity(qs)); httpclient = newHttpClient(); HttpResponse response = httpclient.execute(post); HttpEntity resEntity = response.getEntity(); String content = EntityUtils.toString(resEntity, "UTF-8"); post.reset(); if (HttpServletResponse.SC_ACCEPTED == response.getStatusLine().getStatusCode()) { return false; } else if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) { // Only throw an exception if this is the last SSH key we could try if (idx == fingerprints.size()) { throw new OSSException("None of the provided keys (" + idx + ") could be used to initialize this Open Secret Server. Latest error message was: " + response.getStatusLine().getReasonPhrase()); } else { continue; } } return true; } } catch (OSSException osse) { throw osse; } catch (Exception e) { throw new OSSException(e); } finally { if (null != httpclient) { httpclient.getConnectionManager().shutdown(); } if (null != agent) { agent.close(); } } return false; }
From source file:nl.esciencecenter.osmium.mac.MacITCase.java
/** * Submit status to a callback server using MAC Access authentication. * /*from www. j a va2 s.co m*/ * @throws URISyntaxException * @throws ClientProtocolException * @throws IOException */ @Test public void test() throws URISyntaxException, ClientProtocolException, IOException { URI url = getServerURI(); // TODO throw better exception than NullPointerException when property can not be found. String state = "STOPPED"; HttpPut request = new HttpPut(url); request.setEntity(new StringEntity(state)); String mac_id = "eyJzYWx0IjogIjU3MjY0NCIsICJleHBpcmVzIjogMTM4Njc3MjEwOC4yOTIyNTUsICJ1c2VyaWQiOiAiam9ibWFuYWdlciJ9KBJRMeTW2G9I6jlYwRj6j8koAek="; String mac_key = "_B1YfcqEYpZxyTx_-411-QdBOSI="; URI scope = new URI(url.getScheme(), null, url.getHost(), url.getPort(), null, null, null); ImmutableList<MacCredential> macs = ImmutableList.of(new MacCredential(mac_id, mac_key, scope)); HttpClient httpClient = new DefaultHttpClient(); httpClient = JobLauncherService.macifyHttpClient((AbstractHttpClient) httpClient, macs); HttpResponse response = httpClient.execute(request); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); assertThat(EntityUtils.toString(response.getEntity())).startsWith("MAC id=\"" + mac_id); // asserting rest of request.header[AUTHORIZATION] can not be done due to embedded timestamp and changing hostname/port. }
From source file:com.geoxp.oss.client.OSSClient.java
public static void putSecret(String ossURL, String secretname, byte[] secret, String sshKeyFingerprint) throws OSSException { SSHAgentClient agent = null;/*from www . j a v a2 s . c o m*/ HttpClient httpclient = null; try { agent = new SSHAgentClient(); List<SSHKey> sshkeys = agent.requestIdentities(); // // If no SSH Key fingerprint was provided, try all SSH keys available in the agent // List<String> fingerprints = new ArrayList<String>(); if (null == sshKeyFingerprint) { for (SSHKey key : sshkeys) { fingerprints.add(key.fingerprint); } } else { fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", "")); } int idx = 0; for (String fingerprint : fingerprints) { idx++; // // Ask the SSH agent for the SSH key blob // byte[] keyblob = null; for (SSHKey key : sshkeys) { if (key.fingerprint.equals(fingerprint)) { keyblob = key.blob; break; } } // // Throw an exception if this condition is encountered as it can only happen if // there was a provided fingerprint which is not in the agent. // if (null == keyblob) { throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent."); } // // Retrieve OSS RSA key // RSAPublicKey pubkey = getOSSRSA(ossURL); // // Build the token // // <TS> <<WRAPPED_SECRET><ENCRYPTED_WRAPPING_KEY>> <SSH Signing Key Blob> <SSH Signature Blob> // ByteArrayOutputStream token = new ByteArrayOutputStream(); byte[] tsdata = nowBytes(); token.write(CryptoHelper.encodeNetworkString(tsdata)); ByteArrayOutputStream subtoken = new ByteArrayOutputStream(); subtoken.write(CryptoHelper.encodeNetworkString(secretname.getBytes("UTF-8"))); subtoken.write(CryptoHelper.encodeNetworkString(secret)); token.write(CryptoHelper.encodeNetworkString(subtoken.toByteArray())); token.write(CryptoHelper.encodeNetworkString(keyblob)); byte[] sigblob = agent.sign(keyblob, token.toByteArray()); token.write(CryptoHelper.encodeNetworkString(sigblob)); // // Encrypt the token with a random AES256 key // byte[] aeskey = new byte[32]; CryptoHelper.getSecureRandom().nextBytes(aeskey); byte[] wrappedtoken = CryptoHelper.wrapAES(aeskey, token.toByteArray()); // // Encrypt the random key with OSS' RSA key // byte[] sealedaeskey = CryptoHelper.encryptRSA(pubkey, aeskey); // // Create the token // token.reset(); token.write(CryptoHelper.encodeNetworkString(wrappedtoken)); token.write(CryptoHelper.encodeNetworkString(sealedaeskey)); // // Base64 encode the encryptedtoken // String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8"); // // Send request to OSS // URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_PUT_SECRET); builder.addParameter("token", b64token); URI uri = builder.build(); String qs = uri.getRawQuery(); HttpPost post = new HttpPost( uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath()); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new StringEntity(qs)); httpclient = newHttpClient(); HttpResponse response = httpclient.execute(post); HttpEntity resEntity = response.getEntity(); String content = EntityUtils.toString(resEntity, "UTF-8"); post.reset(); if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) { // Only throw an exception if this is the last SSH key we could try if (idx == fingerprints.size()) { throw new OSSException("None of the provided keys (" + idx + ") could be used to store the secret. Latest error message was: " + response.getStatusLine().getReasonPhrase()); } else { continue; } } return; } } catch (OSSException osse) { throw osse; } catch (Exception e) { throw new OSSException(e); } finally { if (null != httpclient) { httpclient.getConnectionManager().shutdown(); } if (null != agent) { agent.close(); } } }