List of usage examples for org.apache.commons.httpclient URIException toString
public String toString()
From source file:org.apache.sling.discovery.impl.topology.connector.TopologyConnectorClient.java
/** ping the server and pass the announcements between the two **/ void ping(final boolean force) { if (autoStopped) { // then we suppress any further pings! logger.debug("ping: autoStopped=true, hence suppressing any further pings."); return;/*w w w . j a v a 2 s. c om*/ } if (force) { backoffPeriodEnd = -1; } else if (backoffPeriodEnd > 0) { if (System.currentTimeMillis() < backoffPeriodEnd) { logger.debug("ping: not issueing a heartbeat due to backoff instruction from peer."); return; } else { logger.debug("ping: backoff period ended, issuing another ping now."); } } final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json"; if (logger.isDebugEnabled()) { logger.debug("ping: connectorUrl=" + connectorUrl + ", complete uri=" + uri); } HttpClient httpClient = new HttpClient(); final PutMethod method = new PutMethod(uri); Announcement resultingAnnouncement = null; try { String userInfo = connectorUrl.getUserInfo(); if (userInfo != null) { Credentials c = new UsernamePasswordCredentials(userInfo); httpClient.getState() .setCredentials(new AuthScope(method.getURI().getHost(), method.getURI().getPort()), c); } Announcement topologyAnnouncement = new Announcement(clusterViewService.getSlingId()); topologyAnnouncement.setServerInfo(serverInfo); final ClusterView clusterView = clusterViewService.getClusterView(); topologyAnnouncement.setLocalCluster(clusterView); if (force) { logger.debug("ping: sending a resetBackoff"); topologyAnnouncement.setResetBackoff(true); } announcementRegistry.addAllExcept(topologyAnnouncement, clusterView, new AnnouncementFilter() { public boolean accept(final String receivingSlingId, final Announcement announcement) { // filter out announcements that are of old cluster instances // which I dont really have in my cluster view at the moment final Iterator<InstanceDescription> it = clusterViewService.getClusterView().getInstances() .iterator(); while (it.hasNext()) { final InstanceDescription instance = it.next(); if (instance.getSlingId().equals(receivingSlingId)) { // then I have the receiving instance in my cluster view // all fine then return true; } } // looks like I dont have the receiving instance in my cluster view // then I should also not propagate that announcement anywhere return false; } }); final String p = requestValidator.encodeMessage(topologyAnnouncement.asJSON()); if (logger.isDebugEnabled()) { logger.debug("ping: topologyAnnouncement json is: " + p); } requestValidator.trustMessage(method, p); if (config.isGzipConnectorRequestsEnabled()) { // tell the server that the content is gzipped: method.addRequestHeader("Content-Encoding", "gzip"); // and gzip the body: final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final GZIPOutputStream gzipOut = new GZIPOutputStream(baos); gzipOut.write(p.getBytes("UTF-8")); gzipOut.close(); final byte[] gzippedEncodedJson = baos.toByteArray(); method.setRequestEntity(new ByteArrayRequestEntity(gzippedEncodedJson, "application/json")); lastRequestEncoding = "gzip"; } else { // otherwise plaintext: method.setRequestEntity(new StringRequestEntity(p, "application/json", "UTF-8")); lastRequestEncoding = "plaintext"; } // independent of request-gzipping, we do accept the response to be gzipped, // so indicate this to the server: method.addRequestHeader("Accept-Encoding", "gzip"); DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false); httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler); httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(1000 * config.getConnectionTimeout()); httpClient.getHttpConnectionManager().getParams().setSoTimeout(1000 * config.getSoTimeout()); method.getParams().setSoTimeout(1000 * config.getSoTimeout()); httpClient.executeMethod(method); if (logger.isDebugEnabled()) { logger.debug("ping: done. code=" + method.getStatusCode() + " - " + method.getStatusText()); } lastStatusCode = method.getStatusCode(); lastResponseEncoding = null; if (method.getStatusCode() == HttpServletResponse.SC_OK) { final Header contentEncoding = method.getResponseHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue() != null && contentEncoding.getValue().contains("gzip")) { lastResponseEncoding = "gzip"; } else { lastResponseEncoding = "plaintext"; } String responseBody = requestValidator.decodeMessage(method); // limiting to 16MB, should be way enough if (logger.isDebugEnabled()) { logger.debug("ping: response body=" + responseBody); } if (responseBody != null && responseBody.length() > 0) { Announcement inheritedAnnouncement = Announcement.fromJSON(responseBody); final long backoffInterval = inheritedAnnouncement.getBackoffInterval(); if (backoffInterval > 0) { // then reset the backoffPeriodEnd: /* minus 1 sec to avoid slipping the interval by a few millis */ this.backoffPeriodEnd = System.currentTimeMillis() + (1000 * backoffInterval) - 1000; logger.debug("ping: servlet instructed to backoff: backoffInterval=" + backoffInterval + ", resulting in period end of " + new Date(backoffPeriodEnd)); } else { logger.debug("ping: servlet did not instruct any backoff-ing at this stage"); this.backoffPeriodEnd = -1; } if (inheritedAnnouncement.isLoop()) { if (logger.isDebugEnabled()) { logger.debug( "ping: connector response indicated a loop detected. not registering this announcement from " + inheritedAnnouncement.getOwnerId()); } if (inheritedAnnouncement.getOwnerId().equals(clusterViewService.getSlingId())) { // SLING-3316 : local-loop detected. Check config to see if we should stop this connector if (config.isAutoStopLocalLoopEnabled()) { inheritedAnnouncement = null; // results in connected -> false and representsloop -> true autoStopped = true; // results in isAutoStopped -> true } } } else { inheritedAnnouncement.setInherited(true); if (announcementRegistry.registerAnnouncement(inheritedAnnouncement) == -1) { if (logger.isDebugEnabled()) { logger.debug( "ping: connector response is from an instance which I already see in my topology" + inheritedAnnouncement); } statusDetails = "receiving side is seeing me via another path (connector or cluster) already (loop)"; return; } } resultingAnnouncement = inheritedAnnouncement; statusDetails = null; } else { statusDetails = "no response body received"; } } else { statusDetails = "got HTTP Status-Code: " + lastStatusCode; } // SLING-2882 : reset suppressPingWarnings_ flag in success case suppressPingWarnings_ = false; } catch (URIException e) { logger.warn("ping: Got URIException: " + e + ", uri=" + uri); statusDetails = e.toString(); } catch (IOException e) { // SLING-2882 : set/check the suppressPingWarnings_ flag if (suppressPingWarnings_) { if (logger.isDebugEnabled()) { logger.debug("ping: got IOException: " + e + ", uri=" + uri); } } else { suppressPingWarnings_ = true; logger.warn("ping: got IOException [suppressing further warns]: " + e + ", uri=" + uri); } statusDetails = e.toString(); } catch (JSONException e) { logger.warn("ping: got JSONException: " + e); statusDetails = e.toString(); } catch (RuntimeException re) { logger.warn("ping: got RuntimeException: " + re, re); statusDetails = re.toString(); } finally { method.releaseConnection(); lastInheritedAnnouncement = resultingAnnouncement; lastPingedAt = System.currentTimeMillis(); } }
From source file:org.apache.webdav.ant.WebdavFileSet.java
public CollectionScanner getCollectionScanner(Project project, HttpClient httpClient, HttpURL baseUrl) { validate();//from www . j a v a 2 s . com CollectionScanner scanner = new CollectionScanner(); try { scanner.setBaseURL(Utils.createHttpURL(baseUrl, directory)); } catch (URIException e) { throw new BuildException("Invalid URL. " + e.toString(), e); } scanner.setHttpClient(httpClient); scanner.setCaseSensitive(this.isCaseSensitive); if (this.patterns.getExcludePatterns(project) == null && this.patterns.getIncludePatterns(project) == null && this.patternSets.size() == 0) { scanner.setIncludes(DEFAULT_INCLUDES); } else { scanner.setExcludes(this.patterns.getExcludePatterns(project)); scanner.setIncludes(this.patterns.getIncludePatterns(project)); for (Iterator i = this.patternSets.iterator(); i.hasNext();) { PatternSet patternSet = (PatternSet) i.next(); scanner.addExcludes(patternSet.getExcludePatterns(project)); scanner.addIncludes(patternSet.getIncludePatterns(project)); } } scanner.scan(); return scanner; }
From source file:org.archive.modules.extractor.ExtractorYoutubeFormatStreamTest.java
public void logUriError(URIException e, UURI u, CharSequence l) { LOGGER.log(Level.INFO, u.toString(), e); System.out.println("Info - " + u.toString() + " " + e.toString()); }
From source file:org.archive.modules.fetcher.FetchHTTP.java
protected static String getServerKey(CrawlURI uri) { try {//from w w w.ja v a 2s . c o m return CrawlServer.getServerKey(uri.getUURI()); } catch (URIException e) { logger.log(Level.SEVERE, e.toString() + ": " + uri, e); return null; } }
From source file:org.archive.wayback.accesscontrol.staticmap.StaticMapExclusionFilter.java
protected boolean isExcluded(String url) { try {/*from www. j a v a 2 s. com*/ SURTTokenizer st = new SURTTokenizer(url, canonicalizer.isSurtForm()); while (true) { String nextSearch = st.nextSearch(); if (nextSearch == null) { break; } LOGGER.fine("EXCLUSION-MAP:Checking " + nextSearch); if (exclusionMap.containsKey(nextSearch)) { LOGGER.info("EXCLUSION-MAP: EXCLUDED: \"" + nextSearch + "\" (" + url + ")"); return true; } } } catch (URIException e) { LOGGER.warning(e.toString()); return true; } return false; }
From source file:org.netpreserve.openwayback.accesscontrol.staticmap.StaticMapWhitelistFilter.java
protected boolean isExcluded(String url) { try {//w ww. j ava2 s.c o m SURTTokenizer st = new SURTTokenizer(url, canonicalizer.isSurtForm()); while (true) { String nextSearch = st.nextSearch(); if (nextSearch == null) { break; } LOGGER.fine("WHITELIST-MAP:Checking " + nextSearch); if (inclusionMap.containsKey(nextSearch)) { LOGGER.info("WHITELIST-MAP: INCLUDED: \"" + nextSearch + "\" (" + url + ")"); return false; } } } catch (URIException e) { LOGGER.warning(e.toString()); return true; } return true; }
From source file:org.parosproxy.paros.network.HttpSender.java
public int executeMethod(HttpMethod method, HttpState state) throws IOException { int responseCode = -1; String hostName;//from w ww. j a va2 s . c o m hostName = method.getURI().getHost(); method.setDoAuthentication(true); HostConfiguration hc = null; HttpClient requestClient; if (param.isUseProxy(hostName)) { requestClient = clientViaProxy; } else { // ZAP: use custom client on upgrade connection and on event-source data type Header connectionHeader = method.getRequestHeader("connection"); boolean isUpgrade = connectionHeader != null && connectionHeader.getValue().toLowerCase().contains("upgrade"); // ZAP: try to apply original handling of ParosProxy requestClient = client; if (isUpgrade) { // Unless upgrade, when using another client that allows us to expose the socket // connection. requestClient = new HttpClient(new ZapHttpConnectionManager()); } } if (this.initiator == CHECK_FOR_UPDATES_INITIATOR) { // Use the 'strict' SSLConnector, ie one that performs all the usual cert checks // The 'standard' one 'trusts' everything // This is to ensure that all 'check-for update' calls are made to the expected https urls // without this is would be possible to intercept and change the response which could result // in the user downloading and installing a malicious add-on hc = new HostConfiguration() { @Override public synchronized void setHost(URI uri) { try { setHost(new HttpHost(uri.getHost(), uri.getPort(), getProtocol())); } catch (URIException e) { throw new IllegalArgumentException(e.toString()); } }; }; hc.setHost(hostName, method.getURI().getPort(), new Protocol("https", (ProtocolSocketFactory) new SSLConnector(false), 443)); if (param.isUseProxy(hostName)) { hc.setProxyHost(new ProxyHost(param.getProxyChainName(), param.getProxyChainPort())); if (param.isUseProxyChainAuth()) { requestClient.getState().setProxyCredentials(getAuthScope(param), getNTCredentials(param)); } } } // ZAP: Check if a custom state is being used if (state != null) { // Make sure cookies are enabled method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } responseCode = requestClient.executeMethod(hc, method, state); return responseCode; }
From source file:phex.download.swarming.SWDownloadCandidate.java
/** * Returns the url necessary for the download request. * * @return the download url./*from www . ja va 2 s . c om*/ */ public String getDownloadRequestUrl() { String requestUrl; if (downloadURI != null) { try { // Don't use whole uri.. only file and query part..!? requestUrl = URLUtil.getPathQueryFromUri(downloadURI); return requestUrl; } catch (URIException e) {// failed to use uri.. try other request urls.. logger.warn(e.toString(), e); } } if (resourceURN != null) { requestUrl = URLUtil.buildName2ResourceURL(resourceURN); } else { // build standard old style gnutella request. String fileIndexStr = String.valueOf(fileIndex); StringBuffer urlBuffer = new StringBuffer(6 + fileIndexStr.length() + fileName.length()); urlBuffer.append("/get/"); urlBuffer.append(fileIndexStr); urlBuffer.append('/'); urlBuffer.append(URLCodecUtils.encodeURL(fileName)); requestUrl = urlBuffer.toString(); } return requestUrl; }