List of usage examples for java.net URI getPort
public int getPort()
From source file:io.curly.commons.web.hateoas.ZuulAwareMappingResolver.java
/** * <a href="https://github.com/spring-cloud-samples/customers-stores/blob/master/rest-microservices-customers/src/main/java/example/customers/integration/StoreIntegration.java#L89">Github Spring Cloud Sample implementation<a/> * * @param host the current request host/*from www. j av a 2 s . c o m*/ * @param href the #resolve builder returns * @return reconstructed URI based on the current request host and port comparing them with the service host and port */ public String reconstructURI(String host, String href) { URI original; try { 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.sourcesense.confluence.servlets.CMISProxyServlet.java
protected String getProxyHost(HttpServletRequest httpServletRequest) { String serverName = httpServletRequest.getParameter("servername"); if (serverName != null) { List<String> up = getConfigurationList(serverName); if (up != null) { if (httpServletRequest.getPathInfo() == null || httpServletRequest.getPathInfo().equals("/")) { return up.get(0); } else { try { URI uri = new URI(up.get(0)); if (uri.getPort() != -1) { return uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort(); } else return uri.getScheme() + uri.getHost(); } catch (URISyntaxException e) { e.printStackTrace(); }//w w w. jav a2 s . com } } } return null; }
From source file:com.android.callstat.common.net.ConnectionThread.java
/** * A helper method to send or retrieve data through HTTP protocol. * //from www . j a va 2 s. c om * @param token * The token to identify the sending progress. * @param url * The URL used in a GET request. Null when the method is * HTTP_POST_METHOD. * @param pdu * The data to be POST. Null when the method is HTTP_GET_METHOD. * @param method * HTTP_POST_METHOD or HTTP_GET_METHOD. * @return A byte array which contains the response data. If an HTTP error * code is returned, an IOException will be thrown. * @throws IOException * if any error occurred on network interface or an HTTP error * code(>=400) returned from the server. */ private byte[] httpConnection(Context context, boolean isProxySet, MyHttpClient client, String proxyHost, int proxyPort, Request request) throws IOException { if (request.getUri() == null) { throw new IllegalArgumentException("URL must not be null."); } int timeout = (int) request.getmTimeout(); if (timeout != 0 && timeout < 5000) { timeout = 5000; } client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); try { URI hostUrl = new URI(request.getUri()); HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME); HttpLog.d("URL:" + request.getUri() + " Host:" + hostUrl.getHost() + " Port:" + hostUrl.getPort()); HttpRequest req = null; switch (request.getMethod()) { case HTTP_POST_METHOD: HttpPost post = new HttpPost(request.getUri()); HttpEntity content = request.getHttpEntity(); if (content != null) { post.setEntity(content); if (content instanceof StringEntity) { final StringEntity stringEntity = (StringEntity) content; post.setHeader(stringEntity.getContentEncoding()); post.setHeader(stringEntity.getContentType()); } } req = post; break; case HTTP_GET_METHOD: req = new HttpGet(request.getUri()); break; default: HttpLog.e("Unknown HTTP method: " + request.getMethod() + ". Must be one of POST[" + HTTP_POST_METHOD + "] or GET[" + HTTP_GET_METHOD + "]."); return null; } HttpResponse response = null; if (CallStatUtils.isOMS()) { setRequest(response, isProxySet, req, client, proxyHost, proxyPort, request); response = client.execute(target, req); } else { if (CallStatUtils.isMOBILE(mContext)) { String apn = CallStatUtils.getAPN(mContext); if (!StringUtil.isNullOrWhitespaces(apn)) { if (apn.equals("CMWAP")) { HttpClient httpclient = new DefaultHttpClient(); HttpHost proxy = new HttpHost("10.0.0.172", 80, "http"); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); response = httpclient.execute(target, req); } else { setRequest(response, isProxySet, req, client, proxyHost, proxyPort, request); response = client.execute(target, req); } } else { setRequest(response, isProxySet, req, client, proxyHost, proxyPort, request); response = client.execute(target, req); } } else { setRequest(response, isProxySet, req, client, proxyHost, proxyPort, request); response = client.execute(target, req); } } StatusLine status = response.getStatusLine(); request.getEventHandler().status(status.getProtocolVersion().getMajor(), status.getProtocolVersion().getMinor(), status.getStatusCode(), status.getReasonPhrase()); switch (status.getStatusCode()) { case 200: break; case 304: request.getEventHandler().endData(null, 0); return null; default: request.getEventHandler().endData(null, 0); throw new IOException( "HTTP error: " + status.getReasonPhrase() + " CODE:" + status.getStatusCode()); } Headers headers = new Headers(); readResponseHeaders(headers, response); request.getEventHandler().headers(headers); HttpEntity entity = response.getEntity(); byte[] body = null; if (entity != null) { try { int contentLength = (int) entity.getContentLength(); if (contentLength > 0) { body = new byte[contentLength]; // DataInputStream dis = new // DataInputStream(entity.getContent()); InputStream in = entity.getContent(); int offset = 0; int length = contentLength; try { while (length > 0) { int result = in.read(body, offset, length); HttpLog.v("################result:" + result); offset += result; length -= result; if (length <= 0) { request.getEventHandler().endData(body, contentLength); } } } finally { try { in.close(); // request.mLoadListener.loaded(body, // contentLength); // if(length == 0) // CallbackProxy.getHandler().onFinishResourceLoading(body, // contentLength, request.mLoadListener); } catch (IOException e) { HttpLog.e("Error closing input stream: " + e.getMessage()); } } } else { ByteArrayBuilder dataBuilder = new ByteArrayBuilder(); body = new byte[8192]; InputStream in = entity.getContent(); int result = 0; int count = 0; int lowWater = body.length / 2; try { while (result != -1) { result = in.read(body, count, body.length - count); if (result != -1) { HttpLog.v("################result:" + result); count += result; } if (result == -1 || count >= lowWater) { dataBuilder.append(body, 0, count); count = 0; } if (result == -1) { if (dataBuilder.getByteSize() > 0) { byte[] cert = new byte[dataBuilder.getByteSize()]; int offset = 0; while (true) { ByteArrayBuilder.Chunk c = dataBuilder.getFirstChunk(); if (c == null) break; if (c.mLength != 0) { System.arraycopy(c.mArray, 0, cert, offset, c.mLength); offset += c.mLength; } c.release(); } request.getEventHandler().endData(cert, cert.length); } } } } finally { try { in.close(); } catch (IOException e) { HttpLog.e("Error closing input stream: " + e.getMessage()); } } } } finally { if (entity != null) { entity.consumeContent(); } } } return body; } catch (URISyntaxException e) { // TODO Auto-generated catch block request.getEventHandler().error(EventHandler.ERROR_BAD_URL, e.getMessage()); e.printStackTrace(); } catch (IllegalStateException e) { request.getEventHandler().error(EventHandler.ERROR, e.getMessage()); e.printStackTrace(); } catch (IllegalArgumentException e) { request.getEventHandler().error(EventHandler.ERROR_BAD_URL, e.getMessage()); e.printStackTrace(); } catch (SocketException e) { request.getEventHandler().error(EventHandler.ERROR, e.getMessage()); e.printStackTrace(); } catch (ConnectTimeoutException e) { request.getEventHandler().error(EventHandler.ERROR_TIMEOUT, e.getMessage()); e.printStackTrace(); } catch (Exception e) { request.getEventHandler().error(EventHandler.ERROR, e.getMessage()); e.printStackTrace(); } return null; }
From source file:com.geoxp.oss.client.OSSClient.java
public static byte[] getSecret(String ossURL, String secretName, String sshKeyFingerprint) throws OSSException { HttpClient httpclient = null;// w w w.j a v a2 s . c om SSHAgentClient agent = 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++; // // Check if the signing key is available in the agent // 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."); } // // Generate temporary RSA key pair // RSAKeyPairGenerator rsagen = new RSAKeyPairGenerator(); RSAKeyGenerationParameters params = new RSAKeyGenerationParameters(new BigInteger("65537"), CryptoHelper.getSecureRandom(), OSS.DEFAULT_RSA_STRENGTH, 64); rsagen.init(params); final AsymmetricCipherKeyPair keypair = rsagen.generateKeyPair(); RSAPrivateKey rsapriv = new RSAPrivateKey() { public BigInteger getModulus() { return ((RSAKeyParameters) keypair.getPrivate()).getModulus(); } public String getFormat() { return "PKCS#8"; } public byte[] getEncoded() { return null; } public String getAlgorithm() { return "RSA"; } public BigInteger getPrivateExponent() { return ((RSAKeyParameters) keypair.getPrivate()).getExponent(); } }; RSAPublicKey rsapub = new RSAPublicKey() { public BigInteger getModulus() { return ((RSAKeyParameters) keypair.getPublic()).getModulus(); } public String getFormat() { return "PKCS#8"; } public byte[] getEncoded() { return null; } public String getAlgorithm() { return "RSA"; } public BigInteger getPublicExponent() { return ((RSAKeyParameters) keypair.getPublic()).getExponent(); } }; // // Build OSS Token // // <TS> <<SECRET_NAME> <RSA_ENC_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(CryptoHelper.sshKeyBlobFromPublicKey(rsapub))); token.write(CryptoHelper.encodeNetworkString(subtoken.toByteArray())); token.write(CryptoHelper.encodeNetworkString(keyblob)); // // Generate signature // byte[] sigblob = agent.sign(keyblob, token.toByteArray()); token.write(CryptoHelper.encodeNetworkString(sigblob)); String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8"); // // Send request // httpclient = newHttpClient(); URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_GET_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)); 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 retrieve secret. Latest error message was: " + response.getStatusLine().getReasonPhrase()); } else { continue; } } // // Extract encrypted secret and sealed key // byte[] secretandsealedkey = Base64.decode(content); byte[] encryptedsecret = CryptoHelper.decodeNetworkString(secretandsealedkey, 0); byte[] sealedkey = CryptoHelper.decodeNetworkString(secretandsealedkey, 4 + encryptedsecret.length); // // Unseal key // byte[] wrappingkey = CryptoHelper.decryptRSA(rsapriv, sealedkey); // // Unwrap secret // return CryptoHelper.unwrapAES(wrappingkey, encryptedsecret); } } 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 null; }
From source file:org.opennms.smoketest.OpenNMSSeleniumTestCase.java
private Integer doRequest(final HttpRequestBase request) throws ClientProtocolException, IOException, InterruptedException { final CountDownLatch waitForCompletion = new CountDownLatch(1); final URI uri = request.getURI(); final HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("admin", "admin")); AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache);/*from w w w .jav a 2 s.co m*/ final CloseableHttpClient client = HttpClients.createDefault(); final ResponseHandler<Integer> responseHandler = new ResponseHandler<Integer>() { @Override public Integer handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { try { final int status = response.getStatusLine().getStatusCode(); // 400 because we return that if you try to delete something that is already deleted // 404 because it's OK if it's already not there if (status >= 200 && status < 300 || status == 400 || status == 404) { EntityUtils.consume(response.getEntity()); return status; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } finally { waitForCompletion.countDown(); } } }; final Integer status = client.execute(targetHost, request, responseHandler, context); waitForCompletion.await(); client.close(); return status; }
From source file:com.abiquo.api.services.RemoteServiceService.java
private ErrorsDto checkUniqueness(final Datacenter datacenter, final RemoteService remoteService, final boolean flushErrors) { ErrorsDto configurationErrors = new ErrorsDto(); if (infrastructureRepo.existAnyRemoteServiceWithTypeInDatacenter(datacenter, remoteService.getType())) { APIError error = APIError.REMOTE_SERVICE_TYPE_EXISTS; configurationErrors.add(/* www.j a v a2s.com*/ new ErrorDto(error.getCode(), remoteService.getType().getName() + " : " + error.getMessage())); if (flushErrors) { addConflictErrors(error); } } try { URI uriChecked = new URI(remoteService.getUri()); if (uriChecked.getPort() < 0) { APIError error = APIError.REMOTE_SERVICE_UNDEFINED_PORT; configurationErrors.add(new ErrorDto(error.getCode(), remoteService.getType().getName() + " : " + error.getMessage())); if (flushErrors) { addConflictErrors(error); } } else { if (remoteService.getType().checkUniqueness()) { if (infrastructureRepo.existAnyRemoteServiceWithUri(uriChecked.toString())) { APIError error = APIError.REMOTE_SERVICE_URL_ALREADY_EXISTS; configurationErrors.add(new ErrorDto(error.getCode(), remoteService.getType().getName() + " : " + error.getMessage())); if (flushErrors) { addConflictErrors(error); } } } } } catch (URISyntaxException e) { APIError error = APIError.REMOTE_SERVICE_MALFORMED_URL; configurationErrors.add( new ErrorDto(error.getCode(), remoteService.getType().getName() + " : " + error.getMessage())); if (flushErrors) { addValidationErrors(error); } } if (flushErrors) { flushErrors(); } return configurationErrors; }
From source file:org.kaaproject.kaa.server.common.admin.KaaRestTemplate.java
private URI updateUrl(URI url) { String currentUri = url.toString(); int sufixPartIdx = currentUri.indexOf(restApiSuffix); String defaultUriPartWithVariableHostPort = currentUri.substring(0, sufixPartIdx); String sufixPart = currentUri.substring(sufixPartIdx); defaultUriPartWithVariableHostPort = defaultUriPartWithVariableHostPort.replaceFirst(url.getHost(), getCurHost());//from w w w. j a v a2 s. c o m defaultUriPartWithVariableHostPort = defaultUriPartWithVariableHostPort .replaceFirst(String.valueOf(url.getPort()), String.valueOf(getCurPort())); return URI.create(defaultUriPartWithVariableHostPort + sufixPart); }
From source file:com.mirth.connect.connectors.file.FileReaderService.java
public Object invoke(String channelId, String method, Object object, String sessionsId) throws Exception { if (method.equals(FileServiceMethods.METHOD_TEST_READ)) { FileReceiverProperties connectorProperties = (FileReceiverProperties) object; String host = replacer.replaceValues(connectorProperties.getHost(), channelId); String username = replacer.replaceValues(connectorProperties.getUsername(), channelId); String password = replacer.replaceValues(connectorProperties.getPassword(), channelId); String fileHost = null;// w w w .j a va 2 s .c o m FileScheme scheme = connectorProperties.getScheme(); String addressHost = null; int port = 0; String dir = null; boolean secure = false; boolean passive = false; int timeout = Integer.parseInt(connectorProperties.getTimeout()); if (scheme.equals(FileScheme.FTP) || scheme.equals(FileScheme.SFTP)) { passive = connectorProperties.isPassive(); } if (scheme.equals(FileScheme.FILE)) { fileHost = host; dir = host; } else { URI address; if (scheme.equals(FileScheme.WEBDAV)) { if (connectorProperties.isSecure()) { secure = true; address = new URI("https://" + host); } else { address = new URI("http://" + host); } } else { address = new URI(scheme.getDisplayName() + "://" + host); } fileHost = address.toString(); addressHost = address.getHost(); port = address.getPort(); dir = address.getPath(); } FileSystemConnectionFactory factory = new FileSystemConnectionFactory(scheme, username, password, addressHost, port, passive, secure, timeout); FileSystemConnection connection = null; try { connection = ((PooledObject<FileSystemConnection>) factory.makeObject()).getObject(); if (connection.canRead(dir)) { return new ConnectionTestResponse(ConnectionTestResponse.Type.SUCCESS, "Successfully connected to: " + fileHost); } else { return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Unable to connect to: " + fileHost); } } catch (Exception e) { return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Unable to connect to: " + fileHost); } finally { if (connection != null) { connection.destroy(); } } } return null; }
From source file:com.mcxiaoke.next.http.util.URIBuilder.java
private void digestURI(final URI uri) { this.scheme = uri.getScheme(); this.encodedSchemeSpecificPart = uri.getRawSchemeSpecificPart(); this.encodedAuthority = uri.getRawAuthority(); this.host = uri.getHost(); this.port = uri.getPort(); this.encodedUserInfo = uri.getRawUserInfo(); this.userInfo = uri.getUserInfo(); this.encodedPath = uri.getRawPath(); this.path = uri.getPath(); this.encodedQuery = uri.getRawQuery(); this.queryParams = parseQuery(uri.getRawQuery(), Charsets.UTF_8); this.encodedFragment = uri.getRawFragment(); this.fragment = uri.getFragment(); }
From source file:com.mirth.connect.connectors.file.FileWriterService.java
public Object invoke(String channelId, String method, Object object, String sessionsId) throws Exception { if (method.equals(FileServiceMethods.METHOD_TEST_WRITE)) { FileDispatcherProperties connectorProperties = (FileDispatcherProperties) object; String host = replacer.replaceValues(connectorProperties.getHost(), channelId); String username = replacer.replaceValues(connectorProperties.getUsername(), channelId); String password = replacer.replaceValues(connectorProperties.getPassword(), channelId); String fileHost = null;/* w ww . j av a2 s . c o m*/ FileScheme scheme = connectorProperties.getScheme(); String addressHost = null; int port = 0; String dir = null; boolean secure = false; boolean passive = false; int timeout = Integer.parseInt(connectorProperties.getTimeout()); if (scheme.equals(FileScheme.FTP) || scheme.equals(FileScheme.SFTP)) { passive = connectorProperties.isPassive(); } if (scheme.equals(FileScheme.FILE)) { fileHost = host; dir = host; } else { URI address; if (scheme.equals(FileScheme.WEBDAV)) { if (connectorProperties.isSecure()) { secure = true; address = new URI("https://" + host); } else { address = new URI("http://" + host); } } else { address = new URI(scheme.getDisplayName(), "//" + host, null); } fileHost = address.toString(); addressHost = address.getHost(); port = address.getPort(); dir = address.getPath(); } FileSystemConnectionFactory factory = new FileSystemConnectionFactory(scheme, username, password, addressHost, port, passive, secure, timeout); FileSystemConnection connection = null; try { connection = ((PooledObject<FileSystemConnection>) factory.makeObject()).getObject(); if (connection.canWrite(dir)) { return new ConnectionTestResponse(ConnectionTestResponse.Type.SUCCESS, "Successfully connected to: " + fileHost); } else { return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Unable to connect to: " + fileHost); } } catch (Exception e) { return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Unable to connect to: " + fileHost + ", Reason: " + e.getMessage()); } finally { if (connection != null) { connection.destroy(); } } } return null; }