List of usage examples for java.net URL getPort
public int getPort()
From source file:com.sonymobile.tools.gerrit.gerritevents.workers.rest.AbstractRestCommandJob2.java
@Override public String call() throws IOException { String response = ""; ReviewInput reviewInput = createReview(); String reviewEndpoint = resolveEndpointURL(); HttpPost httpPost = createHttpPostEntity(reviewInput, reviewEndpoint); if (httpPost == null) { return response; }/*w w w. j a va 2 s . c o m*/ CredentialsProvider credProvider = new BasicCredentialsProvider(); credProvider.setCredentials(AuthScope.ANY, credentials); HttpHost proxy = null; if (httpProxy != null && !httpProxy.isEmpty()) { try { URL url = new URL(httpProxy); proxy = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); } catch (MalformedURLException e) { logger.error("Could not parse proxy URL, attempting without proxy.", e); if (altLogger != null) { altLogger.print("ERROR Could not parse proxy URL, attempting without proxy. " + e.getMessage()); } } } HttpClientBuilder builder = HttpClients.custom(); builder.setDefaultCredentialsProvider(credProvider); if (proxy != null) { builder.setProxy(proxy); } CloseableHttpClient httpClient = builder.build(); try { CloseableHttpResponse httpResponse = httpClient.execute(httpPost); response = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8"); if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { logger.error("Gerrit response: {}", httpResponse.getStatusLine().getReasonPhrase()); if (altLogger != null) { altLogger.print("ERROR Gerrit response: " + httpResponse.getStatusLine().getReasonPhrase()); } } } catch (Exception e) { logger.error("Failed to submit result to Gerrit", e); if (altLogger != null) { altLogger.print("ERROR Failed to submit result to Gerrit" + e.toString()); } } return response; }
From source file:it.tidalwave.bluemarine2.downloader.impl.SimpleHttpCacheStorage.java
/******************************************************************************************************************* * * /* w ww.j a v a 2s. c o m*/ * ******************************************************************************************************************/ @Nonnull private Path getCacheItemPath(final @Nonnull URL url) throws MalformedURLException { final int port = url.getPort(); final URL url2 = new URL(url.getProtocol(), url.getHost(), (port == 80) ? -1 : port, url.getFile()); final Path cachePath = Paths.get(url2.toString().replaceAll(":", "")); return folderPath.resolve(cachePath); }
From source file:org.wso2.carbon.apimgt.gateway.handlers.analytics.APIMgtResponseHandler.java
public boolean mediate(MessageContext mc) { super.mediate(mc); if (publisher == null) { this.initializeDataPublisher(); }/*from w ww . j a va2s . c o m*/ try { if (!enabled || skipEventReceiverConnection) { return true; } long responseSize = 0; long responseTime = 0; long serviceTime = 0; long backendTime = 0; long endTime = System.currentTimeMillis(); boolean cacheHit = false; Object startTimeProperty = mc.getProperty(APIMgtGatewayConstants.REQUEST_START_TIME); long startTime = (startTimeProperty == null ? 0 : Long.parseLong((String) startTimeProperty)); Object beStartTimeProperty = mc.getProperty(APIMgtGatewayConstants.BACKEND_REQUEST_START_TIME); long backendStartTime = (beStartTimeProperty == null ? 0 : Long.parseLong((String) beStartTimeProperty)); Object beEndTimeProperty = mc.getProperty(APIMgtGatewayConstants.BACKEND_REQUEST_END_TIME); long backendEndTime = (beEndTimeProperty == null ? 0 : ((Number) beEndTimeProperty).longValue()); //Check the config property is set to true to build the response message in-order //to get the response message size boolean isBuildMsg = UsageComponent.getAmConfigService().getAPIAnalyticsConfiguration().isBuildMsg(); org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) mc).getAxis2MessageContext(); if (isBuildMsg) { Map headers = (Map) axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); String contentLength = (String) headers.get(HttpHeaders.CONTENT_LENGTH); if (contentLength != null) { responseSize = Integer.parseInt(contentLength); } else { //When chunking is enabled try { RelayUtils.buildMessage(axis2MC); } catch (IOException ex) { //In case of an exception, it won't be propagated up,and set response size to 0 log.error("Error occurred while building the message to" + " calculate the response body size", ex); } catch (XMLStreamException ex) { log.error("Error occurred while building the message to calculate the response" + " body size", ex); } SOAPEnvelope env = mc.getEnvelope(); if (env != null) { SOAPBody soapbody = env.getBody(); if (soapbody != null) { byte[] size = soapbody.toString().getBytes(Charset.defaultCharset()); responseSize = size.length; } } } } //When start time not properly set if (startTime == 0) { responseTime = 0; backendTime = 0; serviceTime = 0; } else if (endTime != 0 && backendStartTime != 0 && backendEndTime != 0) { //When // response caching is disabled responseTime = endTime - startTime; backendTime = backendEndTime - backendStartTime; serviceTime = responseTime - backendTime; } else if (endTime != 0 && backendStartTime == 0) {//When response caching enabled responseTime = endTime - startTime; serviceTime = responseTime; backendTime = 0; cacheHit = true; } ResponsePublisherDTO responsePublisherDTO = new ResponsePublisherDTO(); responsePublisherDTO.setConsumerKey((String) mc.getProperty(APIMgtGatewayConstants.CONSUMER_KEY)); responsePublisherDTO.setUsername((String) mc.getProperty(APIMgtGatewayConstants.USER_ID)); String fullRequestPath = (String) mc.getProperty(RESTConstants.REST_FULL_REQUEST_PATH); String tenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(fullRequestPath); responsePublisherDTO.setContext((String) mc.getProperty(APIMgtGatewayConstants.CONTEXT)); String apiVersion = (String) mc.getProperty(RESTConstants.SYNAPSE_REST_API); responsePublisherDTO.setApiVersion(apiVersion); responsePublisherDTO.setApi((String) mc.getProperty(APIMgtGatewayConstants.API)); responsePublisherDTO.setVersion((String) mc.getProperty(APIMgtGatewayConstants.VERSION)); responsePublisherDTO.setResourcePath((String) mc.getProperty(APIMgtGatewayConstants.RESOURCE)); responsePublisherDTO.setResourceTemplate((String) mc.getProperty(APIConstants.API_ELECTED_RESOURCE)); responsePublisherDTO.setMethod((String) mc.getProperty(APIMgtGatewayConstants.HTTP_METHOD)); responsePublisherDTO.setResponseTime(responseTime); responsePublisherDTO.setServiceTime(serviceTime); responsePublisherDTO.setBackendTime(backendTime); responsePublisherDTO.setHostName((String) mc.getProperty(APIMgtGatewayConstants.HOST_NAME)); String apiPublisher = (String) mc.getProperty(APIMgtGatewayConstants.API_PUBLISHER); if (apiPublisher == null) { apiPublisher = APIUtil.getAPIProviderFromRESTAPI(apiVersion, tenantDomain); } responsePublisherDTO.setApiPublisher(apiPublisher); responsePublisherDTO.setTenantDomain(MultitenantUtils.getTenantDomain(apiPublisher)); responsePublisherDTO .setApplicationName((String) mc.getProperty(APIMgtGatewayConstants.APPLICATION_NAME)); responsePublisherDTO.setApplicationId((String) mc.getProperty(APIMgtGatewayConstants.APPLICATION_ID)); responsePublisherDTO.setCacheHit(cacheHit); responsePublisherDTO.setResponseSize(responseSize); responsePublisherDTO.setEventTime(endTime);//This is the timestamp response event published responsePublisherDTO .setDestination((String) mc.getProperty(APIMgtGatewayConstants.SYNAPSE_ENDPOINT_ADDRESS)); responsePublisherDTO.setResponseCode((Integer) axis2MC.getProperty(SynapseConstants.HTTP_SC)); String url = (String) mc.getProperty(RESTConstants.REST_URL_PREFIX); URL apiurl = new URL(url); int port = apiurl.getPort(); String protocol = mc.getProperty(SynapseConstants.TRANSPORT_IN_NAME) + "-" + port; responsePublisherDTO.setProtocol(protocol); publisher.publishEvent(responsePublisherDTO); } catch (Exception e) { log.error("Cannot publish response event. " + e.getMessage(), e); } return true; // Should never stop the message flow }
From source file:uk.ac.ox.oucs.vle.TestPopulatorInput.java
public InputStream getInput(PopulatorContext context) { InputStream input;/* w ww .j a v a2s.c om*/ DefaultHttpClient httpclient = new DefaultHttpClient(); try { URL xcri = new URL(context.getURI()); if ("file".equals(xcri.getProtocol())) { input = xcri.openStream(); } else { HttpHost targetHost = new HttpHost(xcri.getHost(), xcri.getPort(), xcri.getProtocol()); httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(context.getUser(), context.getPassword())); HttpGet httpget = new HttpGet(xcri.toURI()); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) { throw new IllegalStateException( "Invalid response [" + response.getStatusLine().getStatusCode() + "]"); } input = entity.getContent(); } } catch (MalformedURLException e) { throw new PopulatorException(e.getLocalizedMessage()); } catch (IllegalStateException e) { throw new PopulatorException(e.getLocalizedMessage()); } catch (IOException e) { throw new PopulatorException(e.getLocalizedMessage()); } catch (URISyntaxException e) { throw new PopulatorException(e.getLocalizedMessage()); } return input; }
From source file:fr.eolya.utils.http.HttpUtils.java
public static String urlGetAbsoluteURL(String urlReferer, String urlHref) { try {//from w w w. j av a2s .co m if (urlHref.equals("")) return ""; // Case 1 : urlHref starts with "http://" if (urlHref.startsWith("http://") || urlHref.startsWith("https://")) { return urlHref; } URL url = new URL(urlReferer); // Case 1.1 : urlHref starts with "//" if (urlHref.startsWith("//")) { return url.getProtocol() + ":" + urlHref; } String urlRefererHost = url.getProtocol() + "://" + url.getHost(); if (url.getPort() != -1) { urlRefererHost = urlRefererHost + ":" + String.valueOf(url.getPort()); } // Case 2 : urlHref looks like "?..." if (urlHref.startsWith("?")) { // find "?" in urlReferer /* if (urlReferer.indexOf("?")!=-1) return urlReferer.substring(0,urlReferer.indexOf("?")) + urlHref; else return urlReferer + urlHref; */ return urlRefererHost + "/" + url.getPath() + urlHref; } // Case 3 : urlHref looks like "/path/file.html..." if (urlHref.startsWith("/")) { return urlRefererHost + urlHref; } // Case 4 : urlHref looks like "path/file.html..." String urlRefererPath = url.getPath(); if ("".equals(urlRefererPath)) urlRefererPath = "/"; //if (urlRefererPath.indexOf(".")==-1 && urlRefererPath.lastIndexOf("/") != urlRefererPath.length()-1) // urlRefererPath = urlRefererPath + "/"; int offset = urlRefererPath.lastIndexOf("/"); /* if (offset <= 0) { urlRefererPath = ""; } else { urlRefererPath = urlRefererPath.substring(0, offset); } */ urlRefererPath = urlRefererPath.substring(0, offset); return urlRefererHost + urlRefererPath + "/" + urlHref; } catch (Exception e) { //e.printStackTrace (); } return ""; }
From source file:org.ebayopensource.twin.TwinConnection.java
public TwinConnection(URL url) { if (url.getPath().endsWith("/")) try {/*from w ww .ja v a 2 s.c o m*/ url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getPath().substring(0, url.getPath().length() - 1)); } catch (MalformedURLException e) { throw new RuntimeException(e); } this.url = url; }
From source file:com.github.ibm.domino.client.BaseClient.java
public void setAddress(String address) { try {//from w ww .j av a2s . c o m URL url = new URL(address); setHost(url.getHost()); if (url.getPort() > 0) { setPort(url.getPort()); } setProtocol(url.getProtocol()); } catch (MalformedURLException ex) { Logger.getLogger(BaseClient.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:net.sourceforge.jwbf.bots.HttpBot.java
/** * /*from w ww. ja va 2 s.c o m*/ * @param client * if you whant to add some specials * @param u * like http://www.yourOwnWiki.org/w/index.php * */ protected final void setConnection(final HttpClient client, final URL u) { this.client = client; client.getParams().setParameter("http.useragent", "JWBF " + JWBF.getVersion()); client.getHostConfiguration().setHost(u.getHost(), u.getPort(), u.getProtocol()); cc = new HttpActionClient(client, u.getPath()); }
From source file:com.hp.mercury.ci.jenkins.plugins.OOBuildStep.java
private static void initializeHttpClient(DescriptorImpl descriptor) { final int maxConnectionsPerRoute = 100; final int maxConnectionsTotal = 100; ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager(); threadSafeClientConnManager.setDefaultMaxPerRoute(maxConnectionsPerRoute); threadSafeClientConnManager.setMaxTotal(maxConnectionsTotal); httpClient = new DefaultHttpClient(threadSafeClientConnManager); if (descriptor.isIgnoreSsl()) { threadSafeClientConnManager.getSchemeRegistry() .register(new Scheme("https", 443, new FakeSocketFactory())); } else if (descriptor.getKeystorePath() != null) { try {/* ww w. j ava 2 s. c om*/ SSLSocketFactory sslSocketFactory = sslSocketFactoryFromCertificateFile( descriptor.getKeystorePath(), decrypt(descriptor.getKeystorePassword()).toCharArray()); sslSocketFactory.setHostnameVerifier(new BrowserCompatHostnameVerifier()); // For less strict rules in dev mode you can try //sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier()); threadSafeClientConnManager.getSchemeRegistry() .register(new Scheme("https", 443, sslSocketFactory)); } catch (NoSuchAlgorithmException e) { LOG.error("Could not register https scheme: ", e); } catch (KeyManagementException e) { LOG.error("Could not register https scheme: ", e); } catch (KeyStoreException e) { LOG.error("Could not register https scheme: ", e); } catch (UnrecoverableKeyException e) { LOG.error("Could not register https scheme: ", e); } catch (IOException e) { LOG.error("Could not load keystore file: ", e); } catch (CertificateException e) { LOG.error("Could not load keystore file: ", e); } } final HttpParams params = httpClient.getParams(); final int timeoutInSeconds = descriptor.getTimeout() * 1000; HttpConnectionParams.setConnectionTimeout(params, timeoutInSeconds); HttpConnectionParams.setSoTimeout(params, timeoutInSeconds); HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false); for (OOServer s : descriptor.getOoServers(true).values()) { URL url = null; try { url = new URL(s.getUrl()); } catch (MalformedURLException mue) { //can't happen, we pre-validate the URLS during configuration and set active to false if bad. } //check why it doesn't use the credentials provider httpClient.getCredentialsProvider().setCredentials( new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM, "basic"), new UsernamePasswordCredentials(s.getUsername(), decrypt(s.getPassword()))); } }
From source file:cn.openwatch.internal.http.loopj.AsyncHttpClient.java
/** * Will encode url, if not disabled, and adds params on the end of it * * @param url String with URL, should be valid URL without params * @param params RequestParams to be appended on the end of URL * @param shouldEncodeUrl whether url should be encoded (replaces spaces with %20) * @return encoded url if requested with params appended if any available *//*from w w w .ja va 2 s . c o m*/ public static String getUrlWithQueryString(boolean shouldEncodeUrl, String url, RequestParams params) { if (url == null) return null; if (shouldEncodeUrl) { try { String decodedURL = URLDecoder.decode(url, "UTF-8"); URL _url = new URL(decodedURL); URI _uri = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url.getPort(), _url.getPath(), _url.getQuery(), _url.getRef()); url = _uri.toASCIIString(); } catch (Exception ex) { // Should not really happen, added just for sake of validity } } if (params != null) { // Construct the query string and trim it, in case it // includes any excessive white spaces. String paramString = params.getParamString().trim(); // Only add the query string if it isn't empty and it // isn't equal to '?'. if (!paramString.equals("") && !paramString.equals("?")) { url += url.contains("?") ? "&" : "?"; url += paramString; } } return url; }