List of usage examples for java.net URI getPort
public int getPort()
From source file:com.mesosphere.dcos.cassandra.executor.backup.S3StorageDriver.java
String getEndpoint(BackupRestoreContext ctx) throws URISyntaxException { URI uri = new URI(ctx.getExternalLocation()); String scheme = uri.getScheme(); if (scheme.equals(AmazonS3Client.S3_SERVICE_NAME)) { return Constants.S3_HOSTNAME; } else {/* www . j a v a 2 s . c om*/ String endpoint = scheme + "://" + uri.getHost(); int port = uri.getPort(); if (port != -1) { endpoint += ":" + Integer.toString(port); } return endpoint; } }
From source file:org.sonatype.nexus.testsuite.security.nexus4257.Nexus4257CookieVerificationIT.java
@Test public void testCookieForStateFullClient() throws Exception { setAnonymousAccess(false);//from ww w . j a v a2 s .co m TestContext context = TestContainer.getInstance().getTestContext(); String username = context.getAdminUsername(); String password = context.getPassword(); String url = this.getBaseNexusUrl() + "content/"; URI nexusBaseURI = new URI(url); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "SomeUAThatWillMakeMeLookStateful/1.0"); final BasicHttpContext localcontext = new BasicHttpContext(); final HttpHost targetHost = new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(), nexusBaseURI.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); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); // stateful clients must login first, since other rest urls create no sessions String loginUrl = this.getBaseNexusUrl() + "service/local/authentication/login"; assertThat(executeAndRelease(httpClient, new HttpGet(loginUrl), localcontext), equalTo(200)); // after login check content but make sure only cookie is used httpClient.getCredentialsProvider().clear(); HttpGet getMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200)); Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies()); assertThat("Session Cookie not set", sessionCookie, notNullValue()); httpClient.getCookieStore().clear(); // remove cookies // do not set the cookie, expect failure HttpGet failedGetMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, failedGetMethod, null), equalTo(401)); // set the cookie expect a 200, If a cookie is set, and cannot be found on the server, the response will fail // with a 401 httpClient.getCookieStore().addCookie(sessionCookie); getMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200)); }
From source file:org.apache.olingo.samples.client.core.http.SocketFactoryHttpClientFactory.java
@Override public DefaultHttpClient create(final HttpMethod method, final URI uri) { final TrustStrategy acceptTrustStrategy = new TrustStrategy() { @Override//from ww w .ja v a 2s . c om public boolean isTrusted(final X509Certificate[] certificate, final String authType) { return true; } }; final SchemeRegistry registry = new SchemeRegistry(); try { final SSLSocketFactory ssf = new SSLSocketFactory(acceptTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registry.register(new Scheme(uri.getScheme(), uri.getPort(), ssf)); } catch (Exception e) { throw new ODataRuntimeException(e); } final DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(registry)); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT); return httpClient; }
From source file:org.mobicents.servlet.restcomm.http.client.Downloader.java
public HttpUriRequest request(final HttpRequestDescriptor descriptor) throws IllegalArgumentException, URISyntaxException, UnsupportedEncodingException { final URI uri = descriptor.getUri(); final String method = descriptor.getMethod(); if ("GET".equalsIgnoreCase(method)) { final String query = descriptor.getParametersAsString(); URI result = null;//ww w . j av a 2 s.com if (query != null && !query.isEmpty()) { result = new URIBuilder().setScheme(uri.getScheme()).setHost(uri.getHost()).setPort(uri.getPort()) .setPath(uri.getPath()).setQuery(query).build(); } else { result = uri; } return new HttpGet(result); } else if ("POST".equalsIgnoreCase(method)) { final List<NameValuePair> parameters = descriptor.getParameters(); final HttpPost post = new HttpPost(uri); post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); return post; } else { throw new IllegalArgumentException(method + " is not a supported downloader method."); } }
From source file:com.monarchapis.client.authentication.HawkV1RequestProcessor.java
private String getHawkHeader(BaseClient<?> client, String accessToken, String payloadHash, String extData) { try {/* w w w . j a va 2 s . co m*/ StringBuilder sb = new StringBuilder(); long ts = System.currentTimeMillis() / 1000; String nonce = RandomStringUtils.randomAlphanumeric(6); URI uri = URI.create(client.getUrl()); sb.append("hawk.1.header\n"); sb.append(ts); sb.append("\n"); sb.append(nonce); sb.append("\n"); sb.append(client.getMethod()); sb.append("\n"); sb.append(uri.getRawPath()); sb.append("\n"); sb.append(uri.getHost()); sb.append("\n"); sb.append(uri.getPort()); sb.append("\n"); if (payloadHash != null) { sb.append(payloadHash); } sb.append("\n"); if (extData != null) { sb.append(extData); } sb.append("\n"); if (accessToken != null) { sb.append(apiKey); sb.append("\n"); } String stringData = sb.toString(); String algo = HmacUtils.getHMacAlgorithm(algorithm); byte[] key = sharedSecret.getBytes(); SecretKeySpec signingKey = new SecretKeySpec(key, algo); Mac mac256 = Mac.getInstance(algo); mac256.init(signingKey); // compute the hmac on input data bytes byte[] hash = mac256.doFinal(stringData.getBytes("UTF-8")); String mac = Base64.encodeBase64String(hash); return "Hawk id=\"" + (accessToken != null ? accessToken : apiKey) + "\", ts=\"" + ts + "\", nonce=\"" + nonce + "\"" + (payloadHash != null ? ", hash=\"" + payloadHash + "\"" : "") + (extData != null ? ", ext=\"" + extData + "\"," : "") + ", mac=\"" + mac + "\"" + (accessToken != null ? ", app=\"" + apiKey + "\"" : ""); } catch (Exception e) { throw new RuntimeException("Could not create hawk header", e); } }
From source file:com.microsoft.teamfoundation.plugin.impl.TfsClient.java
private Client getClient(URI uri, TfsClientFactoryImpl.ServiceProvider provider, String username, TfsSecret password) {//from ww w . jav a 2s . c om ClientConfig clientConfig = new ClientConfig(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (TfsClientFactoryImpl.ServiceProvider.TFS == provider) { /* NTLM auth for on premise installation */ credentialsProvider.setCredentials( new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM, AuthSchemes.NTLM), new NTCredentials(username, password.getSecret(), uri.getHost(), "")); logger.info("Using NTLM authentication for on premise TeamFoundationServer"); } else if (TfsClientFactoryImpl.ServiceProvider.VSO == provider) { // Basic Auth for VSO services credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password.getSecret())); logger.info("Using user/pass authentication for Visual Studio Online services"); // Preemptive send basic auth header, or we will be redirected for oauth login clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true); } clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED); if (System.getProperty(PROXY_URL_PROPERTY) != null) { clientConfig.property(ClientProperties.PROXY_URI, System.getProperty(PROXY_URL_PROPERTY)); clientConfig.property(ApacheClientProperties.SSL_CONFIG, getSslConfigurator()); } clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider); clientConfig.connectorProvider(new ApacheConnectorProvider()); return ClientBuilder.newClient(clientConfig); }
From source file:com.mirth.connect.connectors.mllp.MllpMessageDispatcher.java
protected StateAwareSocket initSocket(String endpoint) throws IOException, URISyntaxException { if (connectedSockets.get(endpoint) != null) { monitoringController.updateStatus(connector, connectorType, Event.DISCONNECTED, connectedSockets.get(endpoint)); }/* w ww .ja v a 2 s . co m*/ URI uri = new URI(endpoint); int port = uri.getPort(); InetAddress inetAddress = InetAddress.getByName(uri.getHost()); InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, port); StateAwareSocket socket = new StateAwareSocket(); createSocket(socket, inetSocketAddress); socket.setReuseAddress(true); socket.setReceiveBufferSize(connector.getBufferSize()); socket.setSendBufferSize(connector.getBufferSize()); socket.setSoTimeout(connector.getSendTimeout()); socket.setKeepAlive(connector.isKeepAlive()); connectedSockets.put(endpoint, socket); monitoringController.updateStatus(connector, connectorType, Event.CONNECTED, socket); return socket; }
From source file:com.geoxp.oss.client.OSSClient.java
public static void genSecret(String ossURL, String secretName, String sshKeyFingerprint) throws OSSException { SSHAgentClient agent = null;/*from ww w. ja v a 2 s . co 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++; // // 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."); } // // Build OSS Token // // <TS> <SECRET_NAME> <SSH Signing Key Blob> <SSH Signature Blob> // ByteArrayOutputStream token = new ByteArrayOutputStream(); byte[] tsdata = nowBytes(); token.write(CryptoHelper.encodeNetworkString(tsdata)); token.write(CryptoHelper.encodeNetworkString(secretName.getBytes("UTF-8"))); 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_GEN_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); 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 generate 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(); } } }
From source file:com.dhenton9000.birt.configs.DatabaseConfig.java
@Bean public DataSource dataSource() { URI dbUrl = null; String dbString = env.getProperty("DATABASE_URL"); log.debug("database string " + dbString); try {/*from ww w .j a v a 2 s . c o m*/ dbUrl = new URI(dbString); } catch (URISyntaxException ex) { throw new RuntimeException(ex.getMessage()); } DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); String url = "jdbc:postgresql://" + dbUrl.getHost() + ":" + dbUrl.getPort() + dbUrl.getPath(); // log.debug("url "+url); dataSource.setUrl(url); // log.debug("info user "+dbUrl.getUserInfo()); dataSource.setUsername(dbUrl.getUserInfo().split(":")[0]); dataSource.setPassword(dbUrl.getUserInfo().split(":")[1]); return dataSource; }
From source file:AuctionServlet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { PreparedStatement stmt = null; try {/* www . ja va 2s.co m*/ Class.forName("org.postgresql.Driver"); URI dbUri = new URI( "postgres://mvraljhmxcpilo:bKYSixo3rO1Z0cxAmyqMMcK7PG@ec2-75-101-162-243.compute-1.amazonaws.com:5432/d89kgd9u0h1bk3?username=mvraljhmxcpilo&password=bKYSixo3rO1Z0cxAmyqMMcK7PG&ssl.true&sslfactory=org.postgresql.ssl.NonValidatingFactory"); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath(); this.conn = DriverManager.getConnection(dbUrl, username, password); String sql; sql = "Select * \n" + " from BidData inner join CustomerData on \n" + "BidData.CustomerID=CustomerData.CustomerID inner join \n" + "ProductData on ProductData.ProductID=BidData.ProductID;"; stmt = conn.prepareStatement(sql); ResultSet rs; rs = stmt.executeQuery(sql); JSONObject dataobj = new JSONObject(); while (rs.next()) { dataobj.put("ProductID", rs.getInt("ProductID")); dataobj.put("ProductName", rs.getString("ProductName")); dataobj.put("SellerPrice", rs.getInt("SellerPrice")); dataobj.put("TimeLimit", rs.getInt("TimeLimit")); dataobj.put("ItemCondition", rs.getString("ItemCondition")); dataobj.put("DateSubmitted", rs.getDate("DateSubmitted")); dataobj.put("ProductPrice", rs.getInt("ProductPrice")); } out.println(dataobj); rs.close(); stmt.close(); conn.close(); } catch (Exception E) { out.println(E.getMessage()); } } }