List of usage examples for java.net URL getPort
public int getPort()
From source file:org.uiautomation.ios.inspector.model.IDESessionModelImpl.java
@Override public JSONObject getStatus() { try {/*from www . ja v a2 s . c o m*/ HttpClient client = HttpClientFactory.getClient(); String url = getEndPoint() + "/status"; URL u = new URL(url); BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("GET", url); HttpHost h = new HttpHost(u.getHost(), u.getPort()); HttpResponse response = client.execute(h, r); JSONObject o = Helper.extractObject(response); return o; } catch (Exception e) { throw new WebDriverException(e.getMessage(), e); } }
From source file:org.fao.geonet.utils.GeonetHttpRequestFactory.java
/** * Ceate an XmlRequest from a url./*from w ww. j a va 2s .c o m*/ * * @param url the url of the request. * @return the XmlRequest. */ public final XmlRequest createXmlRequest(URL url) { final int port = url.getPort(); final XmlRequest request = createXmlRequest(url.getHost(), port, url.getProtocol()); request.setAddress(url.getPath()); request.setQuery(url.getQuery()); request.setFragment(url.getRef()); request.setUserInfo(url.getUserInfo()); request.setCookieStore(new BasicCookieStore()); return request; }
From source file:org.jboss.as.test.integration.web.security.servlet3.ServletSecurityRoleNamesCommon.java
/** * Method that needs to be overridden with the HTTPClient code. * * @param user username// w ww . j a va2 s. c om * @param pass password * @param expectedCode http status code * @throws Exception */ protected void makeCall(String user, String pass, int expectedCode, URL url) throws Exception { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(user, pass)); try (CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credentialsProvider).build()) { HttpGet httpget = new HttpGet(url.toExternalForm()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); assertEquals(expectedCode, statusLine.getStatusCode()); EntityUtils.consume(entity); } }
From source file:crawler.java.edu.uci.ics.crawler4j.robotstxt.RobotstxtServer.java
private HostDirectives fetchDirectives(URL url) { WebURL robotsTxtUrl = new WebURL(); String host = getHost(url);/*from w ww.ja v a2s . c o m*/ String port = ((url.getPort() == url.getDefaultPort()) || (url.getPort() == -1)) ? "" : (":" + url.getPort()); robotsTxtUrl.setURL("http://" + host + port + "/robots.txt"); HostDirectives directives = null; PageFetchResult fetchResult = null; try { fetchResult = pageFetcher.fetchPage(robotsTxtUrl); if (fetchResult.getStatusCode() == HttpStatus.SC_OK) { Page page = new Page(robotsTxtUrl); fetchResult.fetchContent(page); if (Util.hasPlainTextContent(page.getContentType())) { String content; if (page.getContentCharset() == null) { content = new String(page.getContentData()); } else { content = new String(page.getContentData(), page.getContentCharset()); } directives = RobotstxtParser.parse(content, config.getUserAgentName()); } else if (page.getContentType().contains("html")) { // TODO This one should be upgraded to remove all html tags String content = new String(page.getContentData()); directives = RobotstxtParser.parse(content, config.getUserAgentName()); } else { logger.warn( "Can't read this robots.txt: {} as it is not written in plain text, contentType: {}", robotsTxtUrl.getURL(), page.getContentType()); } } else { logger.debug("Can't read this robots.txt: {} as it's status code is {}", robotsTxtUrl.getURL(), fetchResult.getStatusCode()); } } catch (SocketException | UnknownHostException | SocketTimeoutException | NoHttpResponseException se) { // No logging here, as it just means that robots.txt doesn't exist on this server which is perfectly ok } catch (PageBiggerThanMaxSizeException pbtms) { logger.error("Error occurred while fetching (robots) url: {}, {}", robotsTxtUrl.getURL(), pbtms.getMessage()); } catch (Exception e) { logger.error("Error occurred while fetching (robots) url: " + robotsTxtUrl.getURL(), e); } finally { if (fetchResult != null) { fetchResult.discardContentIfNotConsumed(); } } if (directives == null) { // We still need to have this object to keep track of the time we fetched it directives = new HostDirectives(); } synchronized (host2directivesCache) { if (host2directivesCache.size() == config.getCacheSize()) { String minHost = null; long minAccessTime = Long.MAX_VALUE; for (Map.Entry<String, HostDirectives> entry : host2directivesCache.entrySet()) { if (entry.getValue().getLastAccessTime() < minAccessTime) { minAccessTime = entry.getValue().getLastAccessTime(); minHost = entry.getKey(); } } host2directivesCache.remove(minHost); } host2directivesCache.put(host, directives); } return directives; }
From source file:com.sonymobile.tools.gerrit.gerritevents.workers.rest.AbstractRestCommandJob.java
@Override public void run() { ReviewInput reviewInput = createReview(); String reviewEndpoint = resolveEndpointURL(); HttpPost httpPost = createHttpPostEntity(reviewInput, reviewEndpoint); if (httpPost == null) { return;//from w w w . j av a 2s . co m } DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), config.getHttpCredentials()); if (config.getGerritProxy() != null && !config.getGerritProxy().isEmpty()) { try { URL url = new URL(config.getGerritProxy()); HttpHost proxy = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } 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()); } } } try { HttpResponse httpResponse = httpclient.execute(httpPost); String 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()); } } }
From source file:org.aludratest.service.gui.web.selenium.httpproxy.AuthenticatingHttpProxy.java
public String mapTargetToProxyUrl(String requestedUrlString) { try {//from w ww . j a v a 2 s . com URL requestedUrl = new URL(requestedUrlString); int requestedPort = requestedUrl.getPort(); if (requestedPort == -1) { requestedPort = 80; // NOSONAR } if (requestedUrl.getHost().equals(realHost.getHostName()) && requestedPort == realHost.getPort()) { URL proxyUrl = new URL(requestedUrl.getProtocol(), localHost, localPort, requestedUrl.getFile()); return proxyUrl.toString(); } else { return requestedUrlString; } } catch (MalformedURLException e) { throw new RuntimeException(e); } }
From source file:com.basetechnology.s0.agentserver.webaccessmanager.WebAccessManager.java
public WebSite getWebSite(String url) { String webSiteUrl = null;//from w ww.j a v a2s . c o m try { URL tempUrl = new URL(url); String protocol = tempUrl.getProtocol(); String host = tempUrl.getHost(); int port = tempUrl.getPort(); webSiteUrl = protocol + "://" + host + (port > 0 ? ":" + port : "") + "/"; } catch (MalformedURLException e) { throw new InvalidUrlException(e.getMessage()); } // Check if we already know about this site if (!webSites.containsKey(webSiteUrl)) { // No, create a new WebSite entry WebSite webSite = new WebSite(this, webSiteUrl); webSites.put(webSiteUrl, webSite); } // Return the WebSite for this URL return webSites.get(webSiteUrl); }
From source file:com.beyondjservlet.gateway.servlet.ProxyDetails.java
public ProxyDetails(boolean valid, String stringProxyURL, HttpProxyRule proxyRule) { this.valid = valid; this.stringProxyURL = stringProxyURL; this.proxyRule = proxyRule; int port = 0; String host = ""; try {/*from w w w . j av a 2 s . co m*/ URL url = new URL(stringProxyURL); proxyPath = url.getPath(); protocol = url.getProtocol(); proxyHostAndPort = url.getHost() + ":" + url.getPort(); } catch (Exception e) { while (proxyHostAndPort.startsWith("/")) { proxyHostAndPort = proxyHostAndPort.substring(1); } host = proxyHostAndPort; int idx = indexOf(proxyHostAndPort, ":", "/"); if (idx > 0) { host = proxyHostAndPort.substring(0, idx); String portText = proxyHostAndPort.substring(idx + 1); idx = portText.indexOf("/"); if (idx >= 0) { proxyPath = portText.substring(idx); portText = portText.substring(0, idx); } if (StringUtils.isNotBlank(portText)) { // portText may be a port unless its default try { port = Integer.parseInt(portText); proxyHostAndPort = host + ":" + port; } catch (NumberFormatException ex) { port = 80; // we do not have a port, so proxyPath is the portText proxyPath = "/" + portText + proxyPath; proxyHostAndPort = host; } } else { proxyHostAndPort = host; } } } }
From source file:org.pentaho.reporting.platform.plugin.PentahoReportEnvironment.java
private String getBaseServerURL(final String fullyQualifiedServerUrl) { try {//from www. j av a 2s. c om final URL url = new URL(fullyQualifiedServerUrl); return url.getProtocol() + "://" + url.getHost() + ":" + url.getPort(); //$NON-NLS-1$ //$NON-NLS-2$ } catch (Exception e) { // ignore logger.warn(Messages.getInstance().getString("ReportPlugin.warnNoBaseServerURL"), e); } return null; }
From source file:com.comcast.cns.io.HTTPEndpointAsyncPublisher.java
@Override public void send() throws Exception { HttpAsyncRequester requester = new HttpAsyncRequester(httpProcessor, new DefaultConnectionReuseStrategy(), httpParams);/*from w w w . j a v a 2 s. c om*/ final URL url = new URL(endpoint); final HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", url.getPath() + (url.getQuery() == null ? "" : "?" + url.getQuery())); composeHeader(request); String msg = null; if (message.getMessageStructure() == CNSMessageStructure.json) { msg = message.getProtocolSpecificMessage(CnsSubscriptionProtocol.http); } else { msg = message.getMessage(); } if (!rawMessageDelivery && message.getMessageType() == CNSMessageType.Notification) { msg = com.comcast.cns.util.Util.generateMessageJson(message, CnsSubscriptionProtocol.http); } logger.debug("event=send_async_http_request endpoint=" + endpoint + "\" message=\"" + msg + "\""); request.setEntity(new NStringEntity(msg)); requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), connectionPool, new BasicHttpContext(), new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { int statusCode = response.getStatusLine().getStatusCode(); // accept all 2xx status codes if (statusCode >= 200 && statusCode < 300) { callback.onSuccess(); } else { logger.warn(target + "://" + url.getPath() + "?" + url.getQuery() + " -> " + response.getStatusLine()); callback.onFailure(statusCode); } } public void failed(final Exception ex) { logger.warn(target + " " + url.getPath() + " " + url.getQuery(), ex); callback.onFailure(0); } public void cancelled() { logger.warn(target + " " + url.getPath() + " " + url.getQuery() + " -> " + "cancelled"); callback.onFailure(1); } }); }