List of usage examples for java.net URL getPort
public int getPort()
From source file:com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.Utils.java
/** * Builds rewrite domain from backend route url. * * @param backendRoute Backend route.// w w w .jav a 2s . c o m * @param subzone Subzone * @return Rewrite domain. * @throws MalformedURLException if backendRoute parameter has invalid format. */ public static String buildRewriteDomain(String backendRoute, String subzone) throws MalformedURLException { if (backendRoute == null || backendRoute.isEmpty()) { logger.error("Backend route can't be null."); return null; } String applicationRoute = backendRoute; if (!applicationRoute.startsWith(BMSClient.HTTP_SCHEME)) { applicationRoute = String.format("%s://%s", BMSClient.HTTPS_SCHEME, applicationRoute); } else if (!applicationRoute.startsWith(BMSClient.HTTPS_SCHEME) && applicationRoute.contains(BLUEMIX_NAME)) { applicationRoute = applicationRoute.replace(BMSClient.HTTP_SCHEME, BMSClient.HTTPS_SCHEME); } URL url = new URL(applicationRoute); String host = url.getHost(); String rewriteDomain; String regionInDomain = "ng"; int port = url.getPort(); String serviceUrl = String.format("%s://%s", url.getProtocol(), host); if (port != 0) { serviceUrl += ":" + String.valueOf(port); } String[] hostElements = host.split("\\."); if (!serviceUrl.contains(STAGE1_NAME)) { // Multi-region: myApp.eu-gb.mybluemix.net // US: myApp.mybluemix.net if (hostElements.length == 4) { regionInDomain = hostElements[hostElements.length - 3]; } // this is production, because STAGE1 is not found // Multi-Region Eg: eu-gb.bluemix.net // US Eg: ng.bluemix.net rewriteDomain = String.format("%s.%s", regionInDomain, BLUEMIX_DOMAIN); } else { // Multi-region: myApp.stage1.eu-gb.mybluemix.net // US: myApp.stage1.mybluemix.net if (hostElements.length == 5) { regionInDomain = hostElements[hostElements.length - 3]; } if (subzone != null && !subzone.isEmpty()) { // Multi-region Dev subzone Eg: stage1-Dev.eu-gb.bluemix.net // US Dev subzone Eg: stage1-Dev.ng.bluemix.net rewriteDomain = String.format("%s-%s.%s.%s", STAGE1_NAME, subzone, regionInDomain, BLUEMIX_DOMAIN); } else { // Multi-region Eg: stage1.eu-gb.bluemix.net // US Eg: stage1.ng.bluemix.net rewriteDomain = String.format("%s.%s.%s", STAGE1_NAME, regionInDomain, BLUEMIX_DOMAIN); } } return rewriteDomain; }
From source file:de.pdark.dsmp.RequestHandler.java
public static File getCacheFile(URL url, File root) { root = new File(root, url.getHost()); if (url.getPort() != -1 && url.getPort() != 80) root = new File(root, String.valueOf(url.getPort())); File f = new File(root, url.getPath()); return f;//from w w w. j a va2 s .c om }
From source file:org.wso2.developerstudio.appcloud.utils.client.HttpsJaggeryClient.java
@SuppressWarnings("deprecation") public static HttpClient wrapClient(HttpClient base, String urlStr) { try {/*from www.j a v a2 s . co m*/ SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = new ThreadSafeClientConnManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); URL url = new URL(urlStr); int port = url.getPort(); if (port == -1) { port = 443; } String protocol = url.getProtocol(); if ("https".equals(protocol)) { if (port == -1) { port = 443; } } else if ("http".equals(protocol)) { if (port == -1) { port = 80; } } sr.register(new Scheme(protocol, ssf, port)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Throwable ex) { ex.printStackTrace(); log.error("Trust Manager Error", ex); return null; } }
From source file:org.elasticsearch.test.rest.client.RestTestClient.java
private static RestClient createRestClient(URL[] urls, Settings settings) throws IOException { String protocol = settings.get(PROTOCOL, "http"); HttpHost[] hosts = new HttpHost[urls.length]; for (int i = 0; i < hosts.length; i++) { URL url = urls[i]; hosts[i] = new HttpHost(url.getHost(), url.getPort(), protocol); }/* ww w.j ava 2 s . c om*/ RestClient.Builder builder = RestClient.builder(hosts).setMaxRetryTimeoutMillis(30000) .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setSocketTimeout(30000)); String keystorePath = settings.get(TRUSTSTORE_PATH); if (keystorePath != null) { final String keystorePass = settings.get(TRUSTSTORE_PASSWORD); if (keystorePass == null) { throw new IllegalStateException(TRUSTSTORE_PATH + " is provided but not " + TRUSTSTORE_PASSWORD); } Path path = PathUtils.get(keystorePath); if (!Files.exists(path)) { throw new IllegalStateException(TRUSTSTORE_PATH + " is set but points to a non-existing file"); } try { KeyStore keyStore = KeyStore.getInstance("jks"); try (InputStream is = Files.newInputStream(path)) { keyStore.load(is, keystorePass.toCharArray()); } SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext); builder.setHttpClientConfigCallback( new SSLSocketFactoryHttpConfigCallback(sslConnectionSocketFactory)); } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException | CertificateException e) { throw new RuntimeException(e); } } try (ThreadContext threadContext = new ThreadContext(settings)) { Header[] defaultHeaders = new Header[threadContext.getHeaders().size()]; int i = 0; for (Map.Entry<String, String> entry : threadContext.getHeaders().entrySet()) { defaultHeaders[i++] = new BasicHeader(entry.getKey(), entry.getValue()); } builder.setDefaultHeaders(defaultHeaders); } return builder.build(); }
From source file:org.eclipse.wst.json.core.internal.download.HttpClientProvider.java
private static long getLastModified(URL url) { CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = null; try {/* www. j ava 2 s . com*/ HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); Builder builder = RequestConfig.custom(); HttpHost proxy = getProxy(target); if (proxy != null) { builder = builder.setProxy(proxy); } RequestConfig config = builder.build(); HttpHead request = new HttpHead(url.toURI()); request.setConfig(config); response = httpclient.execute(target, request); Header[] s = response.getHeaders("last-modified"); if (s != null && s.length > 0) { String lastModified = s[0].getValue(); return new Date(lastModified).getTime(); } } catch (Exception e) { logWarning(e); return -1; } finally { if (response != null) { try { response.close(); } catch (IOException e) { } } try { httpclient.close(); } catch (IOException e) { } } return -1; }
From source file:net.daporkchop.porkselfbot.util.HTTPUtils.java
/** * Concatenates the given {@link java.net.URL} and query. * * @param url URL to base off/*from w w w . j a va 2 s.c o m*/ * @param query Query to append to URL * @return URL constructed */ public static URL concatenateURL(final URL url, final String query) { try { if (url.getQuery() != null && url.getQuery().length() > 0) { return new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile() + "&" + query); } else { return new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile() + "?" + query); } } catch (final MalformedURLException ex) { throw new IllegalArgumentException("Could not concatenate given URL with GET arguments!", ex); } }
From source file:com.doculibre.constellio.utils.ConnectorManagerRequestUtils.java
public static Element sendPost(ConnectorManager connectorManager, String servletPath, Document document) { try {// w w w. j av a2s . c om HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); BasicHttpProcessor httpproc = new BasicHttpProcessor(); // Required protocol interceptors httpproc.addInterceptor(new RequestContent()); httpproc.addInterceptor(new RequestTargetHost()); // Recommended protocol interceptors httpproc.addInterceptor(new RequestConnControl()); httpproc.addInterceptor(new RequestUserAgent()); httpproc.addInterceptor(new RequestExpectContinue()); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); URL connectorManagerURL = new URL(connectorManager.getUrl()); HttpHost host = new HttpHost(connectorManagerURL.getHost(), connectorManagerURL.getPort()); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try { HttpEntity requestBody; if (document != null) { // OutputFormat format = OutputFormat.createPrettyPrint(); OutputFormat format = OutputFormat.createCompactFormat(); StringWriter stringWriter = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(stringWriter, format); xmlWriter.write(document); String xmlAsString = stringWriter.toString(); requestBody = new StringEntity(xmlAsString, "UTF-8"); } else { requestBody = null; } if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } String target = connectorManager.getUrl() + servletPath; BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", target); request.setEntity(requestBody); LOGGER.info(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); LOGGER.info("<< Response: " + response.getStatusLine()); String entityText = EntityUtils.toString(response.getEntity()); LOGGER.info(entityText); LOGGER.info("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { LOGGER.info("Connection kept alive..."); } Document xml = DocumentHelper.parseText(entityText); return xml.getRootElement(); } finally { conn.close(); } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:eu.trentorise.smartcampus.protocolcarrier.Communicator.java
private static HttpRequestBase buildRequest(MessageRequest msgRequest, String appToken, String authToken) throws URISyntaxException, UnsupportedEncodingException { String host = msgRequest.getTargetHost(); if (host == null) throw new URISyntaxException(host, "null URI"); if (!host.endsWith("/")) host += '/'; String address = msgRequest.getTargetAddress(); if (address == null) address = ""; if (address.startsWith("/")) address = address.substring(1);/* w ww . j ava 2s . c o m*/ String uriString = host + address; try { URL url = new URL(uriString); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); uriString = uri.toURL().toString(); } catch (MalformedURLException e) { throw new URISyntaxException(uriString, e.getMessage()); } if (msgRequest.getQuery() != null) uriString += "?" + msgRequest.getQuery(); // new URI(uriString); HttpRequestBase request = null; if (msgRequest.getMethod().equals(Method.POST)) { HttpPost post = new HttpPost(uriString); HttpEntity httpEntity = null; if (msgRequest.getRequestParams() != null) { // if body and requestparams are either not null there is an // exception if (msgRequest.getBody() != null && msgRequest != null) { throw new IllegalArgumentException("body and requestParams cannot be either populated"); } httpEntity = new MultipartEntity(); for (RequestParam param : msgRequest.getRequestParams()) { if (param.getParamName() == null || param.getParamName().trim().length() == 0) { throw new IllegalArgumentException("paramName cannot be null or empty"); } if (param instanceof FileRequestParam) { FileRequestParam fileparam = (FileRequestParam) param; ((MultipartEntity) httpEntity).addPart(param.getParamName(), new ByteArrayBody( fileparam.getContent(), fileparam.getContentType(), fileparam.getFilename())); } if (param instanceof ObjectRequestParam) { ObjectRequestParam objectparam = (ObjectRequestParam) param; ((MultipartEntity) httpEntity).addPart(param.getParamName(), new StringBody(convertObject(objectparam.getVars()))); } } // mpe.addPart("file", // new ByteArrayBody(msgRequest.getFileContent(), "")); // post.setEntity(mpe); } if (msgRequest.getBody() != null) { httpEntity = new StringEntity(msgRequest.getBody(), Constants.CHARSET); ((StringEntity) httpEntity).setContentType(msgRequest.getContentType()); } post.setEntity(httpEntity); request = post; } else if (msgRequest.getMethod().equals(Method.PUT)) { HttpPut put = new HttpPut(uriString); if (msgRequest.getBody() != null) { StringEntity se = new StringEntity(msgRequest.getBody(), Constants.CHARSET); se.setContentType(msgRequest.getContentType()); put.setEntity(se); } request = put; } else if (msgRequest.getMethod().equals(Method.DELETE)) { request = new HttpDelete(uriString); } else { // default: GET request = new HttpGet(uriString); } Map<String, String> headers = new HashMap<String, String>(); // default headers if (appToken != null) { headers.put(RequestHeader.APP_TOKEN.toString(), appToken); } if (authToken != null) { // is here for compatibility headers.put(RequestHeader.AUTH_TOKEN.toString(), authToken); headers.put(RequestHeader.AUTHORIZATION.toString(), "Bearer " + authToken); } headers.put(RequestHeader.ACCEPT.toString(), msgRequest.getContentType()); if (msgRequest.getCustomHeaders() != null) { headers.putAll(msgRequest.getCustomHeaders()); } for (String key : headers.keySet()) { request.addHeader(key, headers.get(key)); } return request; }
From source file:org.commonjava.redhat.maven.rv.util.InputUtils.java
public static File getFile(final String location, final File downloadsDir, final boolean deleteExisting) throws ValidationException { if (client == null) { final DefaultHttpClient hc = new DefaultHttpClient(); hc.setRedirectStrategy(new DefaultRedirectStrategy()); final String proxyHost = System.getProperty("http.proxyHost"); final int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort", "-1")); if (proxyHost != null && proxyPort > 0) { final HttpHost proxy = new HttpHost(proxyHost, proxyPort); hc.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); }/*from ww w .ja v a 2s . com*/ client = hc; } File result = null; if (location.startsWith("http")) { LOGGER.info("Downloading: '" + location + "'..."); try { final URL url = new URL(location); final String userpass = url.getUserInfo(); if (!isEmpty(userpass)) { final AuthScope scope = new AuthScope(url.getHost(), url.getPort()); final Credentials creds = new UsernamePasswordCredentials(userpass); client.getCredentialsProvider().setCredentials(scope, creds); } } catch (final MalformedURLException e) { LOGGER.error("Malformed URL: '" + location + "'", e); throw new ValidationException("Failed to download: %s. Reason: %s", e, location, e.getMessage()); } final File downloaded = new File(downloadsDir, new File(location).getName()); if (deleteExisting && downloaded.exists()) { downloaded.delete(); } if (!downloaded.exists()) { HttpGet get = new HttpGet(location); OutputStream out = null; try { HttpResponse response = client.execute(get); // Work around for scenario where we are loading from a server // that does a refresh e.g. gitweb if (response.containsHeader("Cache-control")) { LOGGER.info("Waiting for server to generate cache..."); try { Thread.sleep(5000); } catch (final InterruptedException e) { } get.abort(); get = new HttpGet(location); response = client.execute(get); } final int code = response.getStatusLine().getStatusCode(); if (code == 200) { final InputStream in = response.getEntity().getContent(); out = new FileOutputStream(downloaded); copy(in, out); } else { LOGGER.info(String.format("Received status: '%s' while downloading: %s", response.getStatusLine(), location)); throw new ValidationException("Received status: '%s' while downloading: %s", response.getStatusLine(), location); } } catch (final ClientProtocolException e) { throw new ValidationException("Failed to download: '%s'. Error: %s", e, location, e.getMessage()); } catch (final IOException e) { throw new ValidationException("Failed to download: '%s'. Error: %s", e, location, e.getMessage()); } finally { closeQuietly(out); get.abort(); } } result = downloaded; } else { LOGGER.info("Using local file: '" + location + "'..."); result = new File(location); } return result; }
From source file:mobi.jenkinsci.ci.client.JenkinsFormAuthHttpClient.java
public static final String getDomainFromUrl(final URL url) { return String.format("%s://%s%s", url.getProtocol(), url.getHost(), url.getPort() > 0 ? ":" + url.getPort() : ""); }