List of usage examples for java.net URISyntaxException getMessage
public String getMessage()
From source file:com.amytech.android.library.utils.asynchttp.MyRedirectHandler.java
@Override public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); }//from ww w . j a v a 2 s . c o m // get the location header to find out where to redirect to Header locationHeader = response.getFirstHeader("location"); if (locationHeader == null) { // got a redirect response, but no location header throw new ProtocolException( "Received redirect response " + response.getStatusLine() + " but no location header"); } // HERE IS THE MODIFIED LINE OF CODE String location = locationHeader.getValue().replaceAll(" ", "%20"); URI uri; try { uri = new URI(location); } catch (URISyntaxException ex) { throw new ProtocolException("Invalid redirect URI: " + location, ex); } HttpParams params = response.getParams(); // rfc2616 demands the location value be a complete URI // Location = "Location" ":" absoluteURI if (!uri.isAbsolute()) { if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) { throw new ProtocolException("Relative redirect location '" + uri + "' not allowed"); } // Adjust location URI HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (target == null) { throw new IllegalStateException("Target host not available " + "in the HTTP context"); } HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); try { URI requestURI = new URI(request.getRequestLine().getUri()); URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true); uri = URIUtils.resolve(absoluteRequestURI, uri); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) { RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS); if (redirectLocations == null) { redirectLocations = new RedirectLocations(); context.setAttribute(REDIRECT_LOCATIONS, redirectLocations); } URI redirectURI; if (uri.getFragment() != null) { try { HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); redirectURI = URIUtils.rewriteURI(uri, target, true); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } else { redirectURI = uri; } if (redirectLocations.contains(redirectURI)) { throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'"); } else { redirectLocations.add(redirectURI); } } return uri; }
From source file:cn.com.loopj.android.http.MyRedirectHandler.java
@Override public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); }// www . ja v a2 s . c om //get the location header to find out where to redirect to Header locationHeader = response.getFirstHeader("location"); if (locationHeader == null) { // got a redirect response, but no location header throw new ProtocolException( "Received redirect response " + response.getStatusLine() + " but no location header"); } //HERE IS THE MODIFIED LINE OF CODE String location = locationHeader.getValue().replaceAll(" ", "%20"); URI uri; try { uri = new URI(location); } catch (URISyntaxException ex) { throw new ProtocolException("Invalid redirect URI: " + location, ex); } HttpParams params = response.getParams(); // rfc2616 demands the location value be a complete URI // Location = "Location" ":" absoluteURI if (!uri.isAbsolute()) { if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) { throw new ProtocolException("Relative redirect location '" + uri + "' not allowed"); } // Adjust location URI HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (target == null) { throw new IllegalStateException("Target host not available " + "in the HTTP context"); } HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); try { URI requestURI = new URI(request.getRequestLine().getUri()); URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true); uri = URIUtils.resolve(absoluteRequestURI, uri); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) { RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS); if (redirectLocations == null) { redirectLocations = new RedirectLocations(); context.setAttribute(REDIRECT_LOCATIONS, redirectLocations); } URI redirectURI; if (uri.getFragment() != null) { try { HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); redirectURI = URIUtils.rewriteURI(uri, target, true); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } else { redirectURI = uri; } if (redirectLocations.contains(redirectURI)) { throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'"); } else { redirectLocations.add(redirectURI); } } return uri; }
From source file:org.apache.synapse.transport.nhttp.ClientHandler.java
private void setHeaders(HttpContext context, HttpResponse response, MessageContext outMsgCtx, MessageContext responseMsgCtx) { Header[] headers = response.getAllHeaders(); if (headers != null && headers.length > 0) { Map<String, String> headerMap = new TreeMap<String, String>(new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); }/*from w ww.j av a 2 s . c o m*/ }); String endpointURLPrefix = (String) context.getAttribute(NhttpConstants.ENDPOINT_PREFIX); String servicePrefix = (String) outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX); for (int i = 0; i < headers.length; i++) { Header header = headers[i]; // if this header is already added if (headerMap.containsKey(header.getName())) { /* this is a multi-value header */ // generate the key String key = NhttpConstants.EXCESS_TRANSPORT_HEADERS; // get the old value String oldValue = headerMap.get(header.getName()); // adds additional values to a list in a property of message // context Map map; if (responseMsgCtx.getProperty(key) != null) { map = (Map) responseMsgCtx.getProperty(key); map.put(header.getName(), oldValue); } else { map = new MultiValueMap(); map.put(header.getName(), oldValue); // set as a property in message context responseMsgCtx.setProperty(key, map); } } if ("Location".equals(header.getName()) && endpointURLPrefix != null && servicePrefix != null) { // Here, we are changing only the host name and the port of // the new URI - value of the Location // header. // If the new URI is again referring to a resource in the // server to which the original request // is sent, then replace the hostname and port of the URI // with the hostname and port of synapse // We are not changing the request url here, only the host // name and the port. try { URI serviceURI = new URI(servicePrefix); URI endpointURI = new URI(endpointURLPrefix); URI locationURI = new URI(header.getValue()); if (locationURI.getHost().equalsIgnoreCase(endpointURI.getHost())) { URI newURI = new URI(locationURI.getScheme(), locationURI.getUserInfo(), serviceURI.getHost(), serviceURI.getPort(), locationURI.getPath(), locationURI.getQuery(), locationURI.getFragment()); headerMap.put(header.getName(), newURI.toString()); responseMsgCtx.setProperty(NhttpConstants.SERVICE_PREFIX, outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX)); } } catch (URISyntaxException e) { log.error(e.getMessage(), e); } } else { headerMap.put(header.getName(), header.getValue()); } } responseMsgCtx.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap); } }
From source file:com.bincode.util.DefaultRedirectHandler.java
public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); }/*from w ww . j a v a 2 s .c o m*/ //get the location header to find out where to redirect to Header locationHeader = response.getFirstHeader("location"); if (locationHeader == null) { // got a redirect response, but no location header throw new ProtocolException( "Received redirect response " + response.getStatusLine() + " but no location header"); } String location = locationHeader.getValue(); if (this.log.isDebugEnabled()) { this.log.debug("Redirect requested to location '" + location + "'"); } URI uri; try { uri = new URI(location); } catch (URISyntaxException ex) { throw new ProtocolException("Invalid redirect URI: " + location, ex); } HttpParams params = response.getParams(); // rfc2616 demands the location value be a complete URI // Location = "Location" ":" absoluteURI if (!uri.isAbsolute()) { if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) { throw new ProtocolException("Relative redirect location '" + uri + "' not allowed"); } // Adjust location URI HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (target == null) { throw new IllegalStateException("Target host not available " + "in the HTTP context"); } HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); try { URI requestURI = new URI(request.getRequestLine().getUri()); URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true); uri = URIUtils.resolve(absoluteRequestURI, uri); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) { RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS); if (redirectLocations == null) { redirectLocations = new RedirectLocations(); context.setAttribute(REDIRECT_LOCATIONS, redirectLocations); } URI redirectURI; if (uri.getFragment() != null) { try { HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); redirectURI = URIUtils.rewriteURI(uri, target, true); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } else { redirectURI = uri; } if (redirectLocations.contains(redirectURI)) { throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'"); } else { redirectLocations.add(redirectURI); } } return uri; }
From source file:Jigs_Desktop_Client.GUI.FXMLDocumentController.java
private void connectToUser(String user_to_search) { if (user_to_search.equals("")) user_to_search = this.to_user; try {/*from ww w .j ava2 s.c om*/ System.out.println("Searching for: " + user_to_search); if (jc.findUser(user_to_search)) { String to_user_status = "offline"; this.to_user = user_to_search; for (UserStatus us : this.users_available) { if (us.getUsername().equalsIgnoreCase(user_to_search)) to_user_status = us.getStatus(); } if (to_user_status.equals("online")) { this.connection_circle.setFill(Color.LIGHTGREEN); search_user_result.setText("Connected to @" + user_to_search); this.selected_user.setText("Connected to @" + user_to_search); try { this.spin_earth_image.setImage(new Image( getClass().getResource("resources/spin_earth_bright.gif").toURI().toString())); } catch (URISyntaxException ex) { this.alert("resources/app_error.mp3"); } } else { this.connection_circle.setFill(Color.YELLOW); search_user_result.setText("Offline messaging @" + user_to_search); this.selected_user.setText("Sending offline messages @" + user_to_search); } this.btn_send.setDisable(false); this.alert("resources/app_user_connected.mp3"); main_tab_pane.getSelectionModel().select(2); } else { this.connection_circle.setFill(Color.RED); search_user_result.setText("No user found for @" + user_to_search); this.btn_send.setDisable(true); this.alert("resources/app_no_such_user.mp3"); } } catch (IOException ex) { this.connection_circle.setFill(Color.RED); search_user_result.setText(ex.getMessage()); this.btn_send.setDisable(true); this.alert("resources/app_error.mp3"); } }
From source file:com.clustercontrol.http.factory.RunMonitorHttpScenario.java
/** * HTTP ?/* w w w. j a v a 2 s . c om*/ * * @param facilityId ID * @return ???????true */ public List<MonitorRunResultInfo> collectList(String facilityId) { // ??????? if (!m_isMonitorJob && (!m_httpScenarioCheckInfo.getMonitorInfo().getMonitorFlg() && !m_httpScenarioCheckInfo.getMonitorInfo().getCollectorFlg())) { if (m_log.isDebugEnabled()) { m_log.debug("http scenario monitor " + m_httpScenarioCheckInfo.getMonitorId() + " is not enabled, skip filtering."); } return Collections.emptyList(); } if (m_now != null) { m_nodeDate = m_now.getTime(); } m_value = 0; GetHttpResponse.GetHttpResponseBuilder builder = null; try { builder = GetHttpResponse.custom() .setAuthType(m_httpScenarioCheckInfo.getAuthType() == null ? GetHttpResponse.AuthType.NONE : AuthType.valueOf(m_httpScenarioCheckInfo.getAuthType())) .setAuthUser(m_httpScenarioCheckInfo.getAuthUser()) .setAuthPassword(m_httpScenarioCheckInfo.getAuthPassword()) .setUserAgent(m_httpScenarioCheckInfo.getUserAgent()) .setConnectTimeout(m_httpScenarioCheckInfo.getConnectTimeout() == null ? 0 : m_httpScenarioCheckInfo.getConnectTimeout()) .setRequestTimeout(m_httpScenarioCheckInfo.getRequestTimeout() == null ? 0 : m_httpScenarioCheckInfo.getRequestTimeout()) .setCancelProxyCache(HinemosPropertyUtil .getHinemosPropertyBool("monitor.http.scenario.disable.proxy.cache", true)) .setKeepAlive(true).setNeedAuthSSLCert( !HinemosPropertyUtil.getHinemosPropertyBool("monitor.http.ssl.trustall", true)); if (m_httpScenarioCheckInfo.getProxyFlg()) { builder.setProxyURL(m_httpScenarioCheckInfo.getProxyUrl()) .setProxyPort(m_httpScenarioCheckInfo.getProxyPort() == null ? 0 : m_httpScenarioCheckInfo.getProxyPort()) .setProxyUser(m_httpScenarioCheckInfo.getProxyUser()) .setProxyPassword(m_httpScenarioCheckInfo.getProxyPassword()); } } catch (URISyntaxException e) { m_log.warn("fail to initialize GetHttpResponse : " + e.getMessage(), e); MonitorRunResultInfo info = new MonitorRunResultInfo(); info.setFacilityId(facilityId); info.setMonitorFlg(m_httpScenarioCheckInfo.getMonitorInfo().getMonitorFlg()); info.setCollectorFlg(false); info.setCollectorResult(false); info.setCheckResult(-1); info.setPriority(PriorityConstant.TYPE_UNKNOWN); info.setMessage(MessageConstant.MESSAGE_FAIL_TO_ANALYZE_PROXY_URL.getMessage()); StringBuffer messageOrg = new StringBuffer(); messageOrg.append(e.getMessage()); messageOrg.append("\n"); messageOrg.append(MessageConstant.MONITOR_HTTP_SCENARIO_PROXYURL.getMessage()); messageOrg.append(" : "); messageOrg.append(m_httpScenarioCheckInfo.getProxyUrl()); info.setMessageOrg(messageOrg.toString()); info.setNodeDate(m_nodeDate); info.setProcessType(true); info.setNotifyGroupId(m_httpScenarioCheckInfo.getMonitorInfo().getNotifyGroupId()); return Arrays.asList(info); } int responseTime = 0; ResultType endResultType = ResultType.SUCCESS; MonitorRunResultInfo errorResultInfo = null; List<PageResponse> responses = new ArrayList<PageResponse>(); try (GetHttpResponse m_request = builder.build()) { Map<String, String> variables = RepositoryUtil.createNodeParameter(nodeInfo.get(facilityId)); List<Page> pages = new ArrayList<>(m_httpScenarioCheckInfo.getPages()); Collections.sort(pages, new Comparator<Page>() { @Override public int compare(Page o1, Page o2) { return o1.getId().getPageOrderNo().compareTo(o2.getId().getPageOrderNo()); } }); loopEnd: for (Page page : pages) { ResultType resultType = ResultType.SUCCESS; MonitorRunResultInfo resultInfo = null; StringBinder strbinder = new StringBinder(variables); String url = page.getUrl(); url = strbinder.bindParam(url); String post = page.getPost(); if (post != null && !post.isEmpty()) post = strbinder.bindParam(post); if (m_log.isTraceEnabled()) m_log.trace("http request. (nodeInfo = " + nodeInfo + ", facilityId = " + facilityId + ", url = " + url + ")"); PageResponse response = null; List<String> rurls = new ArrayList<>(); String nextUrl = url; String nextPost = post; while (true) { m_request.execute(nextUrl, nextPost); response = new PageResponse(page, m_request.getResult()); if (response.response.exception == null) { // ?????? if (response.response.statusCode == 301 || response.response.statusCode == 302 || response.response.statusCode == 303 || response.response.statusCode == 307) { for (Header h : response.response.headers) { if (h.getName().equals("Location")) { nextUrl = h.getValue(); nextPost = null; break; } } if (nextUrl != null) { rurls.add(nextUrl); } else { // ????? resultType = ResultType.NOT_FOUND_URL_FOR_REDIRECT; break; } } else { break; } } else { break; } } if (ResultType.NOT_FOUND_URL_FOR_REDIRECT.equals(resultType)) { resultInfo = createNotFoundUrlForRedirectMonitorRunResultInfo(page, response.response, url, rurls); resultInfo.setFacilityId(facilityId); } if (ResultType.SUCCESS.equals(resultType) && response.response.exception != null) { if (SocketTimeoutException.class.equals(response.response.exception.getClass())) { resultType = ResultType.TIMEOUT; resultInfo = createTimeoutMonitorRunResultInfo(page, response.response, url, rurls); resultInfo.setFacilityId(facilityId); } else { resultType = ResultType.UNEXPECTED; resultInfo = createUnexpectedMonitorRunResultInfo(page, response.response, url, rurls); resultInfo.setFacilityId(facilityId); } } if (ResultType.SUCCESS.equals(resultType) && !(page.getStatusCode() == null || Pattern.matches("(\\s*|.*,\\s*)" + response.response.statusCode + "(\\s*,.*|\\s*)", page.getStatusCode()))) { resultType = ResultType.NOT_MATCH_EXPECTED_STATUS_CODES; resultInfo = createUnmatchedStatusCodeMonitorRunResultInfo(page, m_request.getResult(), url); resultInfo.setFacilityId(facilityId); } if (ResultType.SUCCESS.equals(resultType) && !page.getPatterns().isEmpty()) { List<com.clustercontrol.http.model.Pattern> patterns = new ArrayList<>(page.getPatterns()); Collections.sort(patterns, new Comparator<com.clustercontrol.http.model.Pattern>() { @Override public int compare(com.clustercontrol.http.model.Pattern o1, com.clustercontrol.http.model.Pattern o2) { return o1.getId().getPatternOrderNo().compareTo(o2.getId().getPatternOrderNo()); } }); com.clustercontrol.http.model.Pattern matchedPattern = null; Boolean exceptionProcessType = null; for (int i = 0; i < patterns.size(); ++i) { com.clustercontrol.http.model.Pattern pe = patterns.get(i); if (!pe.getValidFlg() || pe.getPattern() == null) continue; try { // ????? Pattern pattern = null; if (pe.getCaseSensitivityFlg()) { pattern = Pattern.compile(pe.getPattern(), Pattern.DOTALL | Pattern.CASE_INSENSITIVE); } // ??? else { pattern = Pattern.compile(pe.getPattern(), Pattern.DOTALL); } // ???? String body = response.response.responseBody; if (body == null) { body = ""; } ; // 404?????body?null??????? Matcher matcher = pattern.matcher(body); if (matcher.matches()) { matchedPattern = pe; break; } } catch (PatternSyntaxException e) { m_log.info("collectList(): PatternSyntax is not valid." + " description=" + pe.getDescription() + ", patternSyntax=" + pe.getPattern() + ", value=" + response.response.responseBody + " : " + e.getClass().getSimpleName() + ", " + e.getMessage()); exceptionProcessType = pe.getProcessType(); } catch (Exception e) { m_log.warn("collectList(): PatternSyntax is not valid." + " description=" + pe.getDescription() + ", patternSyntax=" + pe.getPattern() + ", value=" + response.response.responseBody + " : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e); exceptionProcessType = pe.getProcessType(); } } if (matchedPattern != null) { resultType = ResultType.MATCH_PATTERN; resultInfo = createMatchedPatternMonitorRunResultInfo(page, matchedPattern, response.response, url); resultInfo.setFacilityId(facilityId); } else { resultType = ResultType.NOT_MATCH_PATTERNS; resultInfo = createNotmatchedPatternsMonitorRunResultInfo(page, response.response, url, exceptionProcessType); resultInfo.setFacilityId(facilityId); } } // ??? switch (resultType) { case NOT_MATCH_EXPECTED_STATUS_CODES: case NOT_MATCH_PATTERNS: case TIMEOUT: case UNEXPECTED: case NOT_FOUND_URL_FOR_REDIRECT: errorResultInfo = resultInfo; endResultType = resultType; break loopEnd; case MATCH_PATTERN: if (resultInfo.getProcessType().booleanValue()) { endResultType = resultType; errorResultInfo = resultInfo; break loopEnd; } break; default: // SUCCESS break; } // ?? for (Variable variable : page.getVariables()) { String value = null; if (variable.getMatchingWithResponseFlg()) { if (response.response.responseBody != null) { Matcher m = Pattern.compile(variable.getValue(), Pattern.DOTALL) .matcher(response.response.responseBody); if (m.matches()) { try { value = m.group(1); } catch (IndexOutOfBoundsException e) { m_log.warn(String.format( "not contain group paragraph in pattern for variable. facilityId=%s, monitorId=%s, pageNo=%d, variableName=%s, value=%s", facilityId, m_httpScenarioCheckInfo.getMonitorId(), page.getId().getPageOrderNo(), variable.getId().getName(), variable.getValue())); } } else { // ???? m_log.debug(String.format( "variable not match. facilityId=%s, monitorId=%s, pageNo=%d, variableName=%s, value=%s", facilityId, m_httpScenarioCheckInfo.getMonitorId(), page.getId().getPageOrderNo(), variable.getId().getName(), variable.getValue())); } } else { // ???? m_log.warn(String.format( "Not foudnd previous post. facilityId=%s, monitorId=%s, pageNo=%d, variableName=%s, value=%s", facilityId, m_httpScenarioCheckInfo.getMonitorId(), page.getId().getPageOrderNo(), variable.getId().getName(), variable.getValue())); } } else { value = variable.getValue(); } if (value != null) { variables.put(variable.getId().getName(), value); } } responses.add(response); responseTime += m_request.getResult().responseTime; } } catch (IOException e) { m_log.warn("fail to close HttpClient : " + e.getMessage(), e); } List<MonitorRunResultInfo> resultInfos = new ArrayList<>(); if (ResultType.SUCCESS.equals(endResultType)) { MonitorRunResultInfo info = new MonitorRunResultInfo(); info.setFacilityId(facilityId); info.setMonitorFlg(m_httpScenarioCheckInfo.getMonitorInfo().getMonitorFlg()); info.setCollectorFlg(m_httpScenarioCheckInfo.getMonitorInfo().getCollectorFlg()); info.setCollectorResult(true); info.setCheckResult(0); info.setItemCode("0"); info.setItemName(m_httpScenarioCheckInfo.getMonitorInfo().getItemName()); info.setDisplayName(""); info.setPriority(PriorityConstant.TYPE_INFO); info.setMessage(String.format("%s : %s", MessageConstant.MONITOR_HTTP_SCENARIO_TOTAL_RESPONSETIME_MS.getMessage(), NumberFormat.getNumberInstance().format(responseTime))); int pageOrderNo = 1; StringBuffer messageOrg = new StringBuffer(); messageOrg.append(MessageConstant.MONITOR_HTTP_SCENARIO_TOTAL_RESPONSETIME.getMessage()); messageOrg.append(" : "); messageOrg.append(responseTime); messageOrg.append("\n"); for (PageResponse pr : responses) { messageOrg.append(MessageConstant.MONITOR_HTTP_SCENARIO_PAGE_ORDERNO.getMessage()); messageOrg.append(" : "); messageOrg.append(pageOrderNo++); messageOrg.append("\n"); messageOrg.append(MessageConstant.MONITOR_HTTP_SCENARIO_PAGE_URL.getMessage()); messageOrg.append(" : "); messageOrg.append(pr.response.url); messageOrg.append("\n"); messageOrg.append(MessageConstant.MONITOR_HTTP_SCENARIO_PAGE_STATUSCODE.getMessage()); messageOrg.append(" : "); messageOrg.append(pr.response.statusCode); messageOrg.append("\n"); messageOrg.append(MessageConstant.RESPONSE_TIME_MILLI_SEC.getMessage()); messageOrg.append(" : "); messageOrg.append(pr.response.responseTime); messageOrg.append("\n"); } info.setMessageOrg(messageOrg.toString()); info.setNodeDate(m_nodeDate); info.setValue((double) responseTime); info.setProcessType(true); info.setNotifyGroupId(m_httpScenarioCheckInfo.getMonitorInfo().getNotifyGroupId()); resultInfos.add(info); // ??? if (!m_isMonitorJob && m_httpScenarioCheckInfo.getMonitoringPerPageFlg() && m_httpScenarioCheckInfo.getMonitorInfo().getCollectorFlg()) { Map<String, Integer> map = new HashMap<String, Integer>(); for (PageResponse pr : responses) { Integer count = map.get(pr.page.getUrl()); if (count == null) { count = 1; map.put(pr.page.getUrl(), count); } else { map.put(pr.page.getUrl(), ++count); } MonitorRunResultInfo pagetResultInfo = new MonitorRunResultInfo(); pagetResultInfo.setFacilityId(facilityId); pagetResultInfo.setMonitorFlg(false); pagetResultInfo.setCollectorFlg(true); pagetResultInfo.setCollectorResult(true); pagetResultInfo.setItemCode(Integer.toString(pr.page.getId().getPageOrderNo() + 1)); pagetResultInfo.setDisplayName(pr.page.getUrl() + " (" + count + ")"); pagetResultInfo.setPriority(pr.page.getPriority()); pagetResultInfo.setNodeDate(m_nodeDate); pagetResultInfo.setValue((double) pr.response.responseTime); pagetResultInfo.setNotifyGroupId(m_httpScenarioCheckInfo.getMonitorInfo().getNotifyGroupId()); resultInfos.add(pagetResultInfo); } } } else { resultInfos.add(errorResultInfo); } return resultInfos; }
From source file:com.naryx.tagfusion.cfm.document.cfDOCUMENT.java
private String retrieveHttp(cfSession _Session, String _src, DocumentSection _section, DocumentSettings _defaultSettings) throws dataNotSupportedException, cfmRunTimeException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet method = new HttpGet(); try {//from www . ja v a2s . c om method.setURI(new URI(_src)); if (_section.getUserAgent() != null) { method.setHeader("User-Agent", _section.getUserAgent()); } else { method.setHeader("User-Agent", _defaultSettings.getUserAgent()); } // HTTP basic authentication if (_section.getAuthPassword() != null) { httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(_section.getAuthUser(), _section.getAuthPassword())); } // proxy support if (_defaultSettings.getProxyHost() != null) { HttpHost proxy = new HttpHost(_defaultSettings.getProxyHost(), _defaultSettings.getProxyPort()); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (_defaultSettings.getProxyUser() != null) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(_defaultSettings.getProxyHost(), _defaultSettings.getProxyPort()), new UsernamePasswordCredentials(_defaultSettings.getProxyUser(), _defaultSettings.getProxyPassword())); } } HttpResponse response; response = httpClient.execute(method); if (response.getStatusLine().getStatusCode() == 200) { String charset = null; Header contentType = response.getFirstHeader("Content-type"); if (contentType != null) { String value = contentType.getValue(); int indx = value.indexOf("charset="); if (indx > 0) { charset = value.substring(indx + 8).trim(); } } return handleDocument(_Session, response.getEntity().getContent(), charset); } else { throw newRunTimeException("Failed to retrieve document from source. HTTP status code " + response.getStatusLine().getStatusCode() + " was returned"); } // throw newRunTimeException( "Failed to retrieve document from " + _src + " due to HttpException: " + e.getMessage() ); } catch (URISyntaxException e) { throw newRunTimeException("Error retrieving document via http: " + e.getMessage()); } catch (IOException e) { throw newRunTimeException("Error retrieving document via http: " + e.getMessage()); } }
From source file:org.ttrssreader.net.deprecated.ApacheJSONConnector.java
protected InputStream doRequest(Map<String, String> params) { HttpPost post = new HttpPost(); try {//from ww w . j a v a 2s . c o m if (sessionId != null) params.put(SID, sessionId); // Set Address post.setURI(Controller.getInstance().uri()); post.addHeader("Accept-Encoding", "gzip"); // Add POST data JSONObject json = new JSONObject(params); StringEntity jsonData = new StringEntity(json.toString(), "UTF-8"); jsonData.setContentType("application/json"); post.setEntity(jsonData); // Add timeouts for the connection { HttpParams httpParams = post.getParams(); // Set the timeout until a connection is established. int timeoutConnection = (int) (8 * Utils.SECOND); HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) which is the timeout for waiting for data. // use longer timeout when lazyServer-Feature is used int timeoutSocket = (int) ((Controller.getInstance().lazyServer()) ? 15 * Utils.MINUTE : 10 * Utils.SECOND); HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket); post.setParams(httpParams); } logRequest(json); if (client == null) client = HttpClientFactory.getInstance().getHttpClient(post.getParams()); else client.setParams(post.getParams()); // Add SSL-Stuff if (credProvider != null) client.setCredentialsProvider(credProvider); } catch (URISyntaxException e) { hasLastError = true; lastError = "Invalid URI."; return null; } catch (Exception e) { hasLastError = true; lastError = "Error creating HTTP-Connection in (old) doRequest(): " + formatException(e); e.printStackTrace(); return null; } HttpResponse response; try { response = client.execute(post); // Execute the request } catch (ClientProtocolException e) { hasLastError = true; lastError = "ClientProtocolException in (old) doRequest(): " + formatException(e); return null; } catch (SSLPeerUnverifiedException e) { // Probably related: http://stackoverflow.com/questions/6035171/no-peer-cert-not-sure-which-route-to-take // Not doing anything here since this error should happen only when no certificate is received from the // server. Log.w(TAG, "SSLPeerUnverifiedException in (old) doRequest(): " + formatException(e)); return null; } catch (SSLException e) { if ("No peer certificate".equals(e.getMessage())) { // Handle this by ignoring it, this occurrs very often when the connection is instable. Log.w(TAG, "SSLException in (old) doRequest(): " + formatException(e)); } else { hasLastError = true; lastError = "SSLException in (old) doRequest(): " + formatException(e); } return null; } catch (InterruptedIOException e) { Log.w(TAG, "InterruptedIOException in (old) doRequest(): " + formatException(e)); return null; } catch (SocketException e) { // http://stackoverflow.com/questions/693997/how-to-set-httpresponse-timeout-for-android-in-java/1565243#1565243 Log.w(TAG, "SocketException in (old) doRequest(): " + formatException(e)); return null; } catch (Exception e) { hasLastError = true; lastError = "Exception in (old) doRequest(): " + formatException(e); return null; } // Try to check for HTTP Status codes int code = response.getStatusLine().getStatusCode(); if (code >= 400 && code < 600) { hasLastError = true; lastError = "Server returned status: " + code; return null; } InputStream instream = null; try { HttpEntity entity = response.getEntity(); if (entity != null) instream = entity.getContent(); // Try to decode gzipped instream, if it is not gzip we stay to normal reading Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) instream = new GZIPInputStream(instream); // Header size = response.getFirstHeader("Api-Content-Length"); // Log.d(TAG, "SIZE: " + size.getValue()); if (instream == null) { hasLastError = true; lastError = "Couldn't get InputStream in (old) Method doRequest(String url) [instream was null]"; return null; } } catch (Exception e) { if (instream != null) try { instream.close(); } catch (IOException e1) { // Empty! } hasLastError = true; lastError = "Exception in (old) doRequest(): " + formatException(e); return null; } return instream; }
From source file:com.amossys.hooker.reporting.NetworkEventSenderThread.java
public boolean send(InterceptEvent event) { try {//ww w .ja va 2 s . co m this.targetURI = new URI("http://" + host + ":" + port + "/" + this.esIndex.toLowerCase() + "/" + this.esDoctype.toLowerCase() + "?parent=" + event.getIDXP() + "&op_type=create"); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } SubstrateMain.log("Sending Event to " + this.targetURI); boolean result = false; StringEntity se; try { se = new StringEntity(event.toJson()); HttpPost httpPost = new HttpPost(this.targetURI); httpPost.setEntity(se); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); // Executes POST request to the given URL HttpResponse httpResponse = this.httpClient.execute(httpPost); // Receives response as inputStream InputStream inputStream = httpResponse.getEntity().getContent(); // Converts inputStream to string // TODO: we should parse the elasticsearch result result = inputStream != null; SubstrateMain.log("Event succesfully sent !"); if (inputStream != null) { inputStream.close(); } } catch (UnsupportedEncodingException e) { SubstrateMain.log( "Impossible to send data to remote database due to encoding issues (" + e.getMessage() + ")", e); } catch (IOException e) { SubstrateMain.log( "Impossible to connect to the remote database, check the connectivity (" + e.getMessage() + ")", e); } return result; }