List of usage examples for org.apache.commons.httpclient URI URI
public URI(URI base, URI relative) throws URIException
From source file:davmail.http.DavGatewayHttpClientFacade.java
/** * Set http client current host configuration. * * @param httpClient current Http client * @param url target url/*from w w w . j a v a 2 s. c o m*/ * @throws DavMailException on error */ public static void setClientHost(HttpClient httpClient, String url) throws DavMailException { try { HostConfiguration hostConfig = httpClient.getHostConfiguration(); URI httpURI = new URI(url, true); hostConfig.setHost(httpURI); } catch (URIException e) { throw new DavMailException("LOG_INVALID_URL", url); } }
From source file:gov.nih.nci.cabio.RESTAPITest.java
/** * Queries the REST API with the given query string and parses the resulting * XML into a DOM document./*from w ww . jav a 2s .co m*/ */ private Document getXML(String query) throws Exception { URI uri = new URI(GET_XML_URL + "?" + query, false); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(); method.setURI(uri); client.executeMethod(method); InputSource inputSource = new InputSource(method.getResponseBodyAsStream()); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); return builder.parse(inputSource); }
From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.TunnelServlet.java
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { monitor.fireOnRequest(request, response); if (response.isCommitted()) return;/*from w ww. j av a 2 s .c om*/ ExtendedHttpMethod postMethod; // for this create ui server and port, properties. InetSocketAddress inetAddress = new InetSocketAddress(sslEndPoint, sslPort); HttpServletRequest httpRequest = (HttpServletRequest) request; if (httpRequest.getMethod().equals("GET")) postMethod = new ExtendedGetMethod(); else postMethod = new ExtendedPostMethod(); JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project); capturedData.setRequestHost(httpRequest.getRemoteHost()); capturedData.setRequestHeader(httpRequest); capturedData.setTargetURL(this.prot + inetAddress.getHostName()); CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream()); // copy headers Enumeration<?> headerNames = httpRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String hdr = (String) headerNames.nextElement(); String lhdr = hdr.toLowerCase(); if ("host".equals(lhdr)) { Enumeration<?> vals = httpRequest.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val.startsWith("127.0.0.1")) { postMethod.addRequestHeader(hdr, sslEndPoint); } } continue; } Enumeration<?> vals = httpRequest.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { postMethod.addRequestHeader(hdr, val); } } } if (postMethod instanceof ExtendedPostMethod) ((ExtendedPostMethod) postMethod) .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType())); HostConfiguration hostConfiguration = new HostConfiguration(); httpRequest.getProtocol(); hostConfiguration.getParams().setParameter(SoapUIHostConfiguration.SOAPUI_SSL_CONFIG, settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPATH, "") + " " + settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPASSWORD, "")); hostConfiguration.setHost(new URI(this.prot + sslEndPoint, true)); hostConfiguration = ProxyUtils.initProxySettings(settings, httpState, hostConfiguration, prot + sslEndPoint, new DefaultPropertyExpansionContext(project)); if (sslEndPoint.indexOf("/") < 0) postMethod.setPath("/"); else postMethod.setPath(sslEndPoint.substring(sslEndPoint.indexOf("/"), sslEndPoint.length())); monitor.fireBeforeProxy(request, response, postMethod, hostConfiguration); if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) { if (httpState == null) httpState = new HttpState(); HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod, httpState); } else { HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod); } capturedData.stopCapture(); capturedData.setRequest(capture.getCapturedData()); capturedData.setRawResponseBody(postMethod.getResponseBody()); capturedData.setResponseHeader(postMethod); capturedData.setRawRequestData(getRequestToBytes(request.toString(), postMethod, capture)); capturedData.setRawResponseData( getResponseToBytes(response.toString(), postMethod, capturedData.getRawResponseBody())); monitor.fireAfterProxy(request, response, postMethod, capturedData); StringToStringsMap responseHeaders = capturedData.getResponseHeaders(); // copy headers to response HttpServletResponse httpResponse = (HttpServletResponse) response; for (String name : responseHeaders.keySet()) { for (String header : responseHeaders.get(name)) httpResponse.addHeader(name, header); } IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream()); postMethod.releaseConnection(); synchronized (this) { monitor.addMessageExchange(capturedData); } capturedData = null; }
From source file:com.comcast.cats.jenkins.service.AbstractService.java
/** * Perform build Operations Via GET//from w w w .j a v a 2 s .c o m * * @param requestUrl * Relative request URL * @param mapperClass * Class to which the response should cast to. * @return JAXB deserialized response */ protected Object performBuildOperationsViaGet(final String requestUrl, Class<?> mapperClass) { Object domainObject = null; HttpClient client = new HttpClient(); try { GetMethod request = new GetMethod(); request.setURI(new URI(getAbsoluteUrl(requestUrl), false)); request.addRequestHeader(CONTENT_TYPE, APPLICATION_XML); String apiToken = jenkinsClientProperties.getJenkinsApiToken(); if (!apiToken.isEmpty()) { request.setDoAuthentication(true); } domainObject = sendRequestToJenkins(mapperClass, domainObject, client, request, apiToken); } catch (Exception e) { LOGGER.error(e.getMessage()); } return domainObject; }
From source file:com.wandisco.s3hdfs.rewrite.redirect.VersionRedirect.java
/** * Places a new .d file in the default version directory. * * @param userName//ww w.j a va2s .c o m * @throws IOException */ public void createDeleteMarker(String userName) throws IOException { String versionpath = replaceUri(path.getFullHdfsObjPath(), OBJECT_FILE_NAME, DELETE_MARKER_FILE_NAME); PutMethod httpPut = (PutMethod) getHttpMethod(request.getScheme(), request.getServerName(), request.getServerPort(), "CREATE&overwrite=true", userName, versionpath, PUT); httpPut.setRequestHeader(S3_HEADER_NAME, S3_HEADER_VALUE); httpClient.executeMethod(httpPut); Header locationHeader = httpPut.getResponseHeader("Location"); LOG.debug("1st response: " + httpPut.getStatusLine().toString()); boolean containsRedirect = (locationHeader != null); httpPut.releaseConnection(); if (!containsRedirect) { LOG.debug("1st response did not contain redirect. " + "No version will be created."); return; } // Handle redirect header transition assert httpPut.getStatusCode() == 307; // Consume response and re-allocate connection for redirect httpPut.setURI(new URI(locationHeader.getValue(), true)); httpClient.executeMethod(httpPut); LOG.debug("2nd response: " + httpPut.getStatusLine().toString()); if (httpPut.getStatusCode() != 200) { LOG.debug("Response not 200: " + httpPut.getResponseBodyAsString()); return; } assert httpPut.getStatusCode() == 200; httpPut.releaseConnection(); response.setHeader("x-amz-delete-marker", "true"); }
From source file:com.sforce.cd.apexUnit.client.codeCoverage.WebServiceInvoker.java
public static JSONObject doGet(String relativeServiceURL, String accessToken) { LOG.debug("relativeServiceURL in doGet method:" + relativeServiceURL); HttpClient httpclient = new HttpClient(); GetMethod get = null;// w w w . j a v a 2 s .co m String authorizationServerURL = CommandLineArguments.getOrgUrl() + relativeServiceURL; get = new GetMethod(authorizationServerURL); get.addRequestHeader("Content-Type", "application/json"); get.setRequestHeader("Authorization", "Bearer " + accessToken); LOG.debug("Start GET operation for the url..." + authorizationServerURL); InputStream instream = null; try { instream = executeHTTPMethod(httpclient, get, authorizationServerURL); LOG.debug("done with get operation"); JSONObject json = (JSONObject) JSONValue.parse(new InputStreamReader(instream)); LOG.debug("is json null? :" + json == null ? "true" : "false"); if (json != null) { if (LOG.isDebugEnabled()) { LOG.debug("ToolingApi.get response: " + json.toString()); Set<String> keys = castSet(String.class, json.keySet()); Iterator<String> jsonKeyIter = keys.iterator(); LOG.debug("Response for the GET method: "); while (jsonKeyIter.hasNext()) { String key = jsonKeyIter.next(); LOG.debug("key : " + key + ". Value : " + json.get(key) + "\n"); // TODO if query results are too large, only 1st batch // of results // are returned. Need to use the identifier in an // additional query // to retrieve rest of the next batch of results if (key.equals("nextRecordsUrl")) { // fire query to the value for this key // doGet((String) json.get(key), accessToken); try { authorizationServerURL = CommandLineArguments.getOrgUrl() + (String) json.get(key); get.setURI(new URI(authorizationServerURL, false)); instream = executeHTTPMethod(httpclient, get, authorizationServerURL); JSONObject newJson = (JSONObject) JSONValue.parse(new InputStreamReader(instream)); if (newJson != null) { Set<String> newKeys = castSet(String.class, json.keySet()); Iterator<String> newJsonKeyIter = newKeys.iterator(); while (newJsonKeyIter.hasNext()) { String newKey = newJsonKeyIter.next(); json.put(newKey, newJson.get(newKey)); LOG.debug("newkey : " + newKey + ". NewValue : " + newJson.get(newKey) + "\n"); } } } catch (URIException e) { ApexUnitUtils.shutDownWithDebugLog(e, "URI exception while fetching subsequent batch of result"); } } } } } return json; } finally { get.releaseConnection(); try { if (instream != null) { instream.close(); } } catch (IOException e) { ApexUnitUtils.shutDownWithDebugLog(e, "Encountered IO exception when closing the stream after reading response from the get method. The error says: " + e.getMessage()); } } }
From source file:com.sa.npopa.samples.hbase.rest.client.Client.java
/** * Execute a transaction method given only the path. Will select at random * one of the members of the supplied cluster definition and iterate through * the list until a transaction can be successfully completed. The * definition of success here is a complete HTTP transaction, irrespective * of result code. /*from w w w. j ava2s . c om*/ * @param cluster the cluster definition * @param method the transaction method * @param headers HTTP header values to send * @param path the properly urlencoded path * @return the HTTP response code * @throws IOException */ public int executePathOnly(Cluster cluster, HttpMethod method, Header[] headers, String path) throws IOException { IOException lastException; if (cluster.nodes.size() < 1) { throw new IOException("Cluster is empty"); } int start = (int) Math.round((cluster.nodes.size() - 1) * Math.random()); int i = start; do { cluster.lastHost = cluster.nodes.get(i); try { StringBuilder sb = new StringBuilder(); if (sslEnabled) { sb.append("https://"); } else { sb.append("http://"); } sb.append(cluster.lastHost); sb.append(path); URI uri = new URI(sb.toString(), true); return executeURI(method, headers, uri.toString()); } catch (IOException e) { lastException = e; } } while (++i != start && i < cluster.nodes.size()); throw lastException; }
From source file:com.denimgroup.threadfix.plugin.zap.action.AttackThread.java
private SiteNode accessNode(URL url) { logger.info("Trying to find a node for " + url); SiteNode startNode = null;// www.j av a 2 s.c o m // Request the URL try { HttpMessage msg = new HttpMessage(new URI(url.toString(), true)); getHttpSender().sendAndReceive(msg, true); if (msg.getResponseHeader().getStatusCode() != HttpStatusCode.OK) { extension.notifyProgress(Progress.FAILED); logger.info("response header was " + msg.getResponseHeader().getStatusCode()); return null; } if (msg.getResponseHeader().isEmpty()) { logger.info("Response header was empty."); return null; } ExtensionHistory extHistory = (ExtensionHistory) Control.getSingleton().getExtensionLoader() .getExtension(ExtensionHistory.NAME); extHistory.addHistory(msg, HistoryReference.TYPE_MANUAL); Model.getSingleton().getSession().getSiteTree().addPath(msg.getHistoryRef()); for (int i = 0; i < 10; i++) { startNode = Model.getSingleton().getSession().getSiteTree() .findNode(new URI(url.toString(), false)); if (startNode != null) { break; } try { sleep(200); } catch (InterruptedException e) { // Ignore } } } catch (Exception e1) { logger.info(e1.getMessage(), e1); return null; } logger.warn("returning " + startNode); return startNode; }
From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.ProxyServlet.java
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { monitor.fireOnRequest(request, response); if (response.isCommitted()) return;/* www. j a v a 2 s .com*/ ExtendedHttpMethod method; HttpServletRequest httpRequest = (HttpServletRequest) request; if (httpRequest.getMethod().equals("GET")) method = new ExtendedGetMethod(); else method = new ExtendedPostMethod(); method.setDecompress(false); // for this create ui server and port, properties. JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project); capturedData.setRequestHost(httpRequest.getServerName()); capturedData.setRequestMethod(httpRequest.getMethod()); capturedData.setRequestHeader(httpRequest); capturedData.setHttpRequestParameters(httpRequest); capturedData.setTargetURL(httpRequest.getRequestURL().toString()); CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream()); // check connection header String connectionHeader = httpRequest.getHeader("Connection"); if (connectionHeader != null) { connectionHeader = connectionHeader.toLowerCase(); if (connectionHeader.indexOf("keep-alive") < 0 && connectionHeader.indexOf("close") < 0) connectionHeader = null; } // copy headers boolean xForwardedFor = false; @SuppressWarnings("unused") long contentLength = -1; Enumeration<?> headerNames = httpRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String hdr = (String) headerNames.nextElement(); String lhdr = hdr.toLowerCase(); if (dontProxyHeaders.contains(lhdr)) continue; if (connectionHeader != null && connectionHeader.indexOf(lhdr) >= 0) continue; if ("content-length".equals(lhdr)) contentLength = request.getContentLength(); Enumeration<?> vals = httpRequest.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { method.setRequestHeader(lhdr, val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } // Proxy headers method.setRequestHeader("Via", "SoapUI Monitor"); if (!xForwardedFor) method.addRequestHeader("X-Forwarded-For", request.getRemoteAddr()); if (method instanceof ExtendedPostMethod) ((ExtendedPostMethod) method) .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType())); HostConfiguration hostConfiguration = new HostConfiguration(); StringBuffer url = new StringBuffer("http://"); url.append(httpRequest.getServerName()); if (httpRequest.getServerPort() != 80) url.append(":" + httpRequest.getServerPort()); if (httpRequest.getServletPath() != null) { url.append(httpRequest.getServletPath()); method.setPath(httpRequest.getServletPath()); if (httpRequest.getQueryString() != null) { url.append("?" + httpRequest.getQueryString()); method.setPath(httpRequest.getServletPath() + "?" + httpRequest.getQueryString()); } } hostConfiguration.setHost(new URI(url.toString(), true)); // SoapUI.log("PROXY to:" + url); monitor.fireBeforeProxy(request, response, method, hostConfiguration); if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) { if (httpState == null) httpState = new HttpState(); HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method, httpState); } else { HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method); } // wait for transaction to end and store it. capturedData.stopCapture(); capturedData.setRequest(capture.getCapturedData()); capturedData.setRawResponseBody(method.getResponseBody()); capturedData.setResponseHeader(method); capturedData.setRawRequestData(getRequestToBytes(request.toString(), method, capture)); capturedData.setRawResponseData( getResponseToBytes(response.toString(), method, capturedData.getRawResponseBody())); capturedData.setResponseContent(new String(method.getDecompressedResponseBody())); monitor.fireAfterProxy(request, response, method, capturedData); if (!response.isCommitted()) { StringToStringsMap responseHeaders = capturedData.getResponseHeaders(); // capturedData = null; // copy headers to response HttpServletResponse httpResponse = (HttpServletResponse) response; for (String name : responseHeaders.keySet()) { for (String header : responseHeaders.get(name)) httpResponse.addHeader(name, header); } IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream()); } synchronized (this) { if (checkContentType(method)) { monitor.addMessageExchange(capturedData); } } }
From source file:com.sa.npopa.samples.hbase.rest.client.Client.java
/** * Execute a transaction method given a complete URI. * @param method the transaction method//from w ww. jav a2 s . c om * @param headers HTTP header values to send * @param uri a properly urlencoded URI * @return the HTTP response code * @throws IOException */ public int executeURI(HttpMethod method, Header[] headers, String uri) throws IOException { method.setURI(new URI(uri, true)); for (Map.Entry<String, String> e : extraHeaders.entrySet()) { method.addRequestHeader(e.getKey(), e.getValue()); } if (headers != null) { for (Header header : headers) { method.addRequestHeader(header); } } long startTime = System.currentTimeMillis(); int code = httpClient.executeMethod(method); long endTime = System.currentTimeMillis(); if (LOG.isDebugEnabled()) { LOG.debug(method.getName() + " " + uri + " " + code + " " + method.getStatusText() + " in " + (endTime - startTime) + " ms"); } return code; }