List of usage examples for org.apache.commons.httpclient HttpMethod setFollowRedirects
public abstract void setFollowRedirects(boolean paramBoolean);
From source file:org.parosproxy.paros.network.HttpMethodHelper.java
public HttpMethod createRequestMethodNew(HttpRequestHeader header, HttpBody body) throws URIException { HttpMethod httpMethod = null; String method = header.getMethod(); URI uri = header.getURI();/* w w w . jav a2 s .c o m*/ String version = header.getVersion(); httpMethod = new GenericMethod(method); httpMethod.setURI(uri); HttpMethodParams httpParams = httpMethod.getParams(); // default to use HTTP 1.0 httpParams.setVersion(HttpVersion.HTTP_1_0); if (version.equalsIgnoreCase(HttpHeader.HTTP11)) { httpParams.setVersion(HttpVersion.HTTP_1_1); } // set various headers int pos = 0; // ZAP: FindBugs fix - always initialise pattern Pattern pattern = patternCRLF; String delimiter = CRLF; String msg = header.getHeadersAsString(); if ((pos = msg.indexOf(CRLF)) < 0) { if ((pos = msg.indexOf(LF)) < 0) { delimiter = LF; pattern = patternLF; } } else { delimiter = CRLF; pattern = patternCRLF; } String[] split = pattern.split(msg); String token = null; String name = null; String value = null; //String host = null; for (int i = 0; i < split.length; i++) { token = split[i]; if (token.equals("")) { continue; } if ((pos = token.indexOf(":")) < 0) { return null; } name = token.substring(0, pos).trim(); value = token.substring(pos + 1).trim(); httpMethod.addRequestHeader(name, value); } // set body if post method or put method if (body != null && body.length() > 0) { EntityEnclosingMethod generic = (EntityEnclosingMethod) httpMethod; // generic.setRequestEntity(new StringRequestEntity(body.toString())); generic.setRequestEntity(new ByteArrayRequestEntity(body.getBytes())); } httpMethod.setFollowRedirects(false); return httpMethod; }
From source file:org.parosproxy.paros.network.HttpMethodHelper.java
public HttpMethod createRequestMethod(HttpRequestHeader header, HttpBody body) throws URIException { HttpMethod httpMethod = null; String method = header.getMethod(); URI uri = header.getURI();/*ww w. jav a2s . c o m*/ String version = header.getVersion(); if (method == null || method.trim().length() < 3) { throw new URIException("Invalid HTTP method: " + method); } if (method.equalsIgnoreCase(GET)) { //httpMethod = new GetMethod(); // ZAP: avoid discarding HTTP status code 101 that is used for WebSocket upgrade httpMethod = new ZapGetMethod(); } else if (method.equalsIgnoreCase(POST)) { httpMethod = new ZapPostMethod(); } else if (method.equalsIgnoreCase(DELETE)) { httpMethod = new ZapDeleteMethod(); } else if (method.equalsIgnoreCase(PUT)) { httpMethod = new ZapPutMethod(); } else if (method.equalsIgnoreCase(HEAD)) { httpMethod = new ZapHeadMethod(); } else if (method.equalsIgnoreCase(OPTIONS)) { httpMethod = new ZapOptionsMethod(); } else if (method.equalsIgnoreCase(TRACE)) { httpMethod = new ZapTraceMethod(uri.toString()); } else { httpMethod = new GenericMethod(method); } try { httpMethod.setURI(uri); } catch (Exception e1) { logger.error(e1.getMessage(), e1); } HttpMethodParams httpParams = httpMethod.getParams(); // default to use HTTP 1.0 httpParams.setVersion(HttpVersion.HTTP_1_0); if (version.equalsIgnoreCase(HttpHeader.HTTP11)) { httpParams.setVersion(HttpVersion.HTTP_1_1); } // set various headers int pos = 0; // ZAP: changed to always use CRLF, like the HttpHeader Pattern pattern = patternCRLF; String delimiter = header.getLineDelimiter(); // ZAP: Shouldn't happen as the HttpHeader always uses CRLF if (delimiter.equals(LF)) { delimiter = LF; pattern = patternLF; } String msg = header.getHeadersAsString(); String[] split = pattern.split(msg); String token = null; String name = null; String value = null; for (int i = 0; i < split.length; i++) { token = split[i]; if (token.equals("")) { continue; } if ((pos = token.indexOf(":")) < 0) { return null; } name = token.substring(0, pos).trim(); value = token.substring(pos + 1).trim(); httpMethod.addRequestHeader(name, value); } // set body if post method or put method if (body != null && body.length() > 0 && (httpMethod instanceof EntityEnclosingMethod)) { EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod; // post.setRequestEntity(new StringRequestEntity(body.toString())); post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes())); } httpMethod.setFollowRedirects(false); return httpMethod; }
From source file:org.parosproxy.paros.network.HttpSender.java
private HttpMethod runMethod(HttpMessage msg, boolean isFollowRedirect) throws IOException { HttpMethod method = null; // no more retry modifyUserAgent(msg);//from w w w. j av a 2 s . c o m method = helper.createRequestMethod(msg.getRequestHeader(), msg.getRequestBody()); if (!(method instanceof EntityEnclosingMethod)) { // cant do this for EntityEnclosingMethod methods - it will fail method.setFollowRedirects(isFollowRedirect); } // ZAP: Use custom HttpState if needed User forceUser = this.getUser(msg); if (forceUser != null) { this.executeMethod(method, forceUser.getCorrespondingHttpState()); } else { this.executeMethod(method, null); } HttpMethodHelper.updateHttpRequestHeaderSent(msg.getRequestHeader(), method); return method; }
From source file:org.proteomecommons.io.gpmdb.GPMDBPeptideReader.java
/** * A helper to parse one page of the gpmdb and update the internal peptides and possible links lists. * @param url the location to parse/*from ww w .j ava 2 s.co m*/ */ private void parse(String url) { //create a singular HttpClient object HttpClient client = new HttpClient(); client.getHostConfiguration().setHost("gpmdb-us.thegpm.org"); //establish a connection within 25 seconds client.getHttpConnectionManager().getParams().setConnectionTimeout(25000); //create a method object HttpMethod method = new GetMethod(url); method.setFollowRedirects(true); //System.out.println("Getting " + url); //execute the method try { client.executeMethod(method); InputStream responseBody = method.getResponseBodyAsStream(); if (responseBody != null) { //if(!url.endsWith("xml")){ //kludge through the html //go through the html and look for various elements like peptide sequences, or links to more about this hit BufferedReader html = new BufferedReader(new InputStreamReader(responseBody)); String line = html.readLine(); //some parsing state String proteinModel = ""; boolean inModel = false; String proteinID = null; int tableStringCount = 0; //generic loop to process any html that we might see on the gpmdb.. from any of the page generating scripts. while (line != null) { //check the line for links to "GPM - protein model:" pages... but don't look for more links if we're already at a protein.pl //for example, if they clicked on an accession link if (line.indexOf("protein.pl") != -1 && url.indexOf("protein.pl") == -1) { //System.out.println("Contains a link to a protein xml doc: " + line); //split on links String[] splitLinks = line.split("href=\"*\""); //look over all of the split results to find good links for (int index = 0; index < splitLinks.length; index++) { //System.out.println("possible " + index + " " + splitLinks[index]); if (splitLinks[index].indexOf("archive") != -1 && splitLinks[index].indexOf("protein.pl") != -1) { splitLinks[index] = splitLinks[index].substring(0, splitLinks[index].indexOf("\">")); if (DEBUG) System.out.println("Found more peptide model pages.. Adding " + index + " " + splitLinks[index]); possibleLinks.add(splitLinks[index]); } } } //check for links to "Search Results for:" if we've done a keyword search if (url.indexOf("dblist_keyword.pl") != -1 && line.indexOf("dblist_label.pl") != -1) { // System.out.println("Expandling links by accessions"); String[] splitLinks = line.split("href=\"*\""); //look over all of the split results to find good links for (int index = 0; index < splitLinks.length; index++) { //System.out.println("possible " + index + " " + splitLinks[index]); if (splitLinks[index].indexOf("dblist_label.pl") != -1) { splitLinks[index] = splitLinks[index].substring(0, splitLinks[index].indexOf("\">")); // System.out.println("Found more protein search result pages.. Adding " + index + " " + splitLinks[index]); possibleLinks.add(splitLinks[index]); } } } //look for the actual pepetides and model sequence if we're on a protein model page if (url.indexOf("protein.pl") != -1) { // System.out.println("Handling Ling: "+line); // pull out protein id if appropriate if (line.indexOf("<BR>protein model: ") != -1) { String[] parts = line.split("<BR>protein model: |<BR><BR>"); System.out.println("Setting ID: " + parts[1]); proteinID = parts[1]; } // fix me! if (line.indexOf("<table") != -1) { tableStringCount++; } //look for the protein model... and parse it if (tableStringCount == 5 && line.indexOf("</table>") == -1) { inModel = true; //grab all of the AminoAcid chars on these lines String chars = removeAllTags(line); // System.out.println("Adding: "+filterAminoAcidChars(chars)); proteinModel = proteinModel + filterAminoAcidChars(chars); } if ((tableStringCount > 4 && line.indexOf("</table>") != -1)) { // System.out.println("Flagging out of model."); inModel = false; tableStringCount++; possibleProteins.add(proteinModel); // System.out.println("Added protein model " + proteinModel); proteinModel = ""; } // //look for the protein model... and parse it // if(line.indexOf("<pre>") != -1 || tableStringCount == 5){ // inModel = true; // } else if(line.indexOf("</pre>") != -1 || (tableStringCount==5 && line.indexOf("</table>")!=-1)){ // inModel = false; // tableStringCount++; // possibleProteins.add(proteinModel); // if(DEBUG) System.out.println("Added protein model " + proteinModel); // proteinModel = ""; // } else if (inModel){ // //grab all of the AminoAcid chars on these lines // String chars = removeAllTags(line); // // proteinModel = proteinModel + filterAminoAcidChars(chars); // // } else if (line.indexOf("spectrum") != -1 && line.indexOf("sequence") != -1) { //found the table with peptide sequences... parse the peptides out of it String[] rows = line.split("<tr>"); //process rows and columns in the table. There are peptide sequences in there. for (int row = 0; row < rows.length; row++) { String[] columns = rows[row].split("</td>"); for (int column = 0; column < columns.length; column++) { String possiblePep = removeAllTags(columns[column]); possiblePep = filterAminoAcidChars(possiblePep); //System.out.println(possiblePep); //give all detagged and filtered strings that are above a specified size a chance at becoming a peptide. if (possiblePep.length() > 4 && columns[column].indexOf("nbsp") == -1) { try { //convert the possible pep into a real live peptide sequence String pepSeq = validatePeptideSequence(possiblePep); peptides.add(new GPMDBPeptide(pepSeq, proteinID)); } catch (Exception e) { System.err.println( "Tried to make a peptide from " + possiblePep + " but failed"); System.err.println("The possible string was " + columns[column]); } } } } } } //and look for more line = html.readLine(); } // } else { /* //setup an xml reader to parse the document try { XMLInputFactory factory = XMLInputFactory.newInstance(); parser = factory.createXMLStreamReader(responseBody); //state for parsing the document boolean inPeptide = false; //in a 'peptide' tag? //walk through the document, and buffer some peptides for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()){ if(event == XMLStreamConstants.START_ELEMENT && parser.getLocalName().equals("domain")){ String pepSeq = parser.getAttributeValue(null, "seq"); //TODO do mods too try{ peptides.add(new Peptide(pepSeq)); } catch (Exception e){ System.out.println("couldn't get a pepseq from the xml..."); } } else if (event == XMLStreamConstants.CHARACTERS && inPeptide){ //System.out.println("Found characters in the doc in peptide tag"); char[] chars = parser.getTextCharacters(); String fixed = ""; for(int character = 0; character < chars.length; character++){ if(chars[character] == 'A' || chars[character] == 'R' || chars[character] == 'N' || chars[character] == 'D' || chars[character] == 'C' || chars[character] == 'E' || chars[character] == 'Q' || chars[character] == 'G' || chars[character] == 'H' || chars[character] == 'I' || chars[character] == 'L' || chars[character] == 'K' || chars[character] == 'M' || chars[character] == 'F' || chars[character] == 'P' || chars[character] == 'S' || chars[character] == 'T' || chars[character] == 'W' || chars[character] == 'Y' || chars[character] == 'V'){ fixed = fixed + chars[character]; } } if(!possibleProteins.contains(fixed)){ possibleProteins.add(fixed); } //System.out.println(fixed); } else if (event == XMLStreamConstants.START_ELEMENT && parser.getLocalName().equals("peptide")){ inPeptide = true; } else if(event == XMLStreamConstants.END_ELEMENT && parser.getLocalName().equals("peptide")){ inPeptide = false; } } } catch (XMLStreamException ex) { System.out.println(ex); } */ // } } } catch (HttpException he) { System.err.println("Could not connect to '" + url + "'"); } catch (IOException ioe) { System.err.println("Unable to connect to the GPMDB."); } //clean up the connection resources method.releaseConnection(); }
From source file:org.red5.server.service.Installer.java
/** * Returns a Map containing all of the application wars in the snapshot repository. * //ww w . j a v a 2 s .c om * @return async message */ public AsyncMessage getApplicationList() { AcknowledgeMessage result = new AcknowledgeMessage(); // create a singular HttpClient object HttpClient client = new HttpClient(); // set the proxy (WT) // test if we received variables on the commandline if ((System.getProperty("http.proxyHost") != null) && (System.getProperty("http.proxyPort") != null)) { HostConfiguration config = client.getHostConfiguration(); config.setProxy(System.getProperty("http.proxyHost").toString(), Integer.parseInt(System.getProperty("http.proxyPort"))); } // establish a connection within 5 seconds client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); //get the params for the client HttpClientParams params = client.getParams(); params.setParameter(HttpMethodParams.USER_AGENT, userAgent); //get registry file HttpMethod method = new GetMethod(applicationRepositoryUrl + "registry-0.9.xml"); //follow any 302's although there shouldnt be any method.setFollowRedirects(true); // execute the method try { IConnection conn = Red5.getConnectionLocal(); int code = client.executeMethod(method); log.debug("HTTP response code: {}", code); String xml = method.getResponseBodyAsString(); log.trace("Response: {}", xml); //prepare response for flex result.body = xml; result.clientId = conn.getClient().getId(); result.messageId = UUID.randomUUID().toString(); result.timestamp = System.currentTimeMillis(); //send the servers java version so the correct apps are installed String javaVersion = System.getProperty("java.version"); if (!ServiceUtils.invokeOnConnection(conn, "onJavaVersion", new Object[] { javaVersion })) { log.warn("Client call to onJavaVersion failed"); } } catch (HttpException he) { log.error("Http error connecting to {}", applicationRepositoryUrl, he); } catch (IOException ioe) { log.error("Unable to connect to {}", applicationRepositoryUrl, ioe); } finally { if (method != null) { method.releaseConnection(); } } return result; }
From source file:org.red5.server.service.Installer.java
/** * Installs a given application./*from w w w. jav a2 s. c o m*/ * * @param applicationWarName app war name * @return true if installed; false otherwise */ public boolean install(String applicationWarName) { IConnection conn = Red5.getConnectionLocal(); boolean result = false; //strip everything except the applications name String application = applicationWarName.substring(0, applicationWarName.indexOf('-')); log.debug("Application name: {}", application); //get webapp location String webappsDir = System.getProperty("red5.webapp.root"); log.debug("Webapp folder: {}", webappsDir); //setup context String contextPath = '/' + application; String contextDir = webappsDir + contextPath; //verify this is a unique app File appDir = new File(webappsDir, application); if (appDir.exists()) { if (appDir.isDirectory()) { log.debug("Application directory exists"); } else { log.warn("Application destination is not a directory"); } ServiceUtils.invokeOnConnection(conn, "onAlert", new Object[] { String.format( "Application %s already installed, please un-install before attempting another install", application) }); } else { //use the system temp directory for moving files around String srcDir = System.getProperty("java.io.tmpdir"); log.debug("Source directory: {}", srcDir); //look for archive containing application (war, zip, etc..) File dir = new File(srcDir); if (!dir.exists()) { log.warn("Source directory not found"); //use another directory dir = new File(System.getProperty("red5.root"), "/webapps/installer/WEB-INF/cache"); if (!dir.exists()) { if (dir.mkdirs()) { log.info("Installer cache directory created"); } } } else { if (!dir.isDirectory()) { log.warn("Source directory is not a directory"); } } //get a list of temp files File[] files = dir.listFiles(); for (File f : files) { String fileName = f.getName(); if (fileName.equals(applicationWarName)) { log.debug("File found matching application name"); result = true; break; } } dir = null; //if the file was not found then download it if (!result) { // create a singular HttpClient object HttpClient client = new HttpClient(); // set the proxy (WT) if ((System.getProperty("http.proxyHost") != null) && (System.getProperty("http.proxyPort") != null)) { HostConfiguration config = client.getHostConfiguration(); config.setProxy(System.getProperty("http.proxyHost").toString(), Integer.parseInt(System.getProperty("http.proxyPort"))); } // establish a connection within 5 seconds client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); //get the params for the client HttpClientParams params = client.getParams(); params.setParameter(HttpMethodParams.USER_AGENT, userAgent); params.setParameter(HttpMethodParams.STRICT_TRANSFER_ENCODING, Boolean.TRUE); //try the wav version first HttpMethod method = new GetMethod(applicationRepositoryUrl + applicationWarName); //we dont want any transformation - RFC2616 method.addRequestHeader("Accept-Encoding", "identity"); //follow any 302's although there shouldnt be any method.setFollowRedirects(true); FileOutputStream fos = null; // execute the method try { int code = client.executeMethod(method); log.debug("HTTP response code: {}", code); //create output file fos = new FileOutputStream(srcDir + '/' + applicationWarName); log.debug("Writing response to {}/{}", srcDir, applicationWarName); // have to receive the response as a byte array. This has the advantage of writing to the filesystem // faster and it also works on macs ;) byte[] buf = method.getResponseBody(); fos.write(buf); fos.flush(); result = true; } catch (HttpException he) { log.error("Http error connecting to {}", applicationRepositoryUrl, he); } catch (IOException ioe) { log.error("Unable to connect to {}", applicationRepositoryUrl, ioe); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { } } if (method != null) { method.releaseConnection(); } } } //if we've found or downloaded the war if (result) { //get the webapp loader LoaderMBean loader = getLoader(); if (loader != null) { //un-archive it to app dir FileUtil.unzip(srcDir + '/' + applicationWarName, contextDir); //load and start the context loader.startWebApplication(application); } else { //just copy the war to the webapps dir try { FileUtil.moveFile(srcDir + '/' + applicationWarName, webappsDir + '/' + application + ".war"); ServiceUtils.invokeOnConnection(conn, "onAlert", new Object[] { String.format( "Application %s will not be available until container is restarted", application) }); } catch (IOException e) { } } } ServiceUtils.invokeOnConnection(conn, "onAlert", new Object[] { String.format("Application %s was %s", application, (result ? "installed" : "not installed")) }); } appDir = null; return result; }
From source file:org.sakaiproject.kernel.proxy.ProxyClientServiceImpl.java
/** * Executes a HTTP call using a path in the JCR to point to a template and a map of * properties to populate that template with. An example might be a SOAP call. * //from w w w. j a v a2 s .c om * <pre> * {http://www.w3.org/2001/12/soap-envelope}Envelope:{ * {http://www.w3.org/2001/12/soap-envelope}Body:{ * {http://www.example.org/stock}GetStockPriceResponse:{ * >body:[ ] * {http://www.example.org/stock}Price:{ * >body:[34.5] * } * } * >body:[ ] * } * >body:[ ] * {http://www.w3.org/2001/12/soap-envelope}encodingStyle:[http://www.w3.org/2001/12/soap-encoding] * } * * </pre> * * @param resource * the resource containing the proxy end point specification. * @param headers * a map of headers to set int the request. * @param input * a map of parameters for all templates (both url and body) * @param requestInputStream * containing the request body (can be null if the call requires no body or the * template will be used to generate the body) * @param requestContentLength * if the requestImputStream is specified, the length specifies the lenght of * the body. * @param requerstContentType * the content type of the request, if null the node property * sakai:proxy-request-content-type will be used. * @throws ProxyClientException */ public ProxyResponse executeCall(Node node, Map<String, String> headers, Map<String, String> input, InputStream requestInputStream, long requestContentLength, String requestContentType) throws ProxyClientException { try { bindNode(node); if (node != null && node.hasProperty(SAKAI_REQUEST_PROXY_ENDPOINT)) { VelocityContext context = new VelocityContext(input); // setup the post request String endpointURL = JcrUtils.getMultiValueString(node.getProperty(SAKAI_REQUEST_PROXY_ENDPOINT)); Reader urlTemplateReader = new StringReader(endpointURL); StringWriter urlWriter = new StringWriter(); velocityEngine.evaluate(context, urlWriter, "urlprocessing", urlTemplateReader); endpointURL = urlWriter.toString(); ProxyMethod proxyMethod = ProxyMethod.GET; if (node.hasProperty(SAKAI_REQUEST_PROXY_METHOD)) { try { proxyMethod = ProxyMethod.valueOf(node.getProperty(SAKAI_REQUEST_PROXY_METHOD).getString()); } catch (Exception e) { } } HttpMethod method = null; switch (proxyMethod) { case GET: method = new GetMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); break; case HEAD: method = new HeadMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); break; case OPTIONS: method = new OptionsMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); break; case POST: method = new PostMethod(endpointURL); break; case PUT: method = new PutMethod(endpointURL); break; default: method = new GetMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); } // follow redirects, but dont auto process 401's and the like. // credentials should be provided method.setDoAuthentication(false); for (Entry<String, String> header : headers.entrySet()) { method.addRequestHeader(header.getKey(), header.getValue()); } Value[] additionalHeaders = JcrUtils.getValues(node, SAKAI_PROXY_HEADER); for (Value v : additionalHeaders) { String header = v.getString(); String[] keyVal = StringUtils.split(header, ':', 2); method.addRequestHeader(keyVal[0].trim(), keyVal[1].trim()); } if (method instanceof EntityEnclosingMethod) { String contentType = requestContentType; if (contentType == null && node.hasProperty(SAKAI_REQUEST_CONTENT_TYPE)) { contentType = node.getProperty(SAKAI_REQUEST_CONTENT_TYPE).getString(); } if (contentType == null) { contentType = APPLICATION_OCTET_STREAM; } EntityEnclosingMethod eemethod = (EntityEnclosingMethod) method; if (requestInputStream != null) { eemethod.setRequestEntity(new InputStreamRequestEntity(requestInputStream, requestContentLength, contentType)); } else { // build the request Template template = velocityEngine.getTemplate(node.getPath()); StringWriter body = new StringWriter(); template.merge(context, body); byte[] soapBodyContent = body.toString().getBytes("UTF-8"); eemethod.setRequestEntity(new ByteArrayRequestEntity(soapBodyContent, contentType)); } } int result = httpClient.executeMethod(method); if (result == 302 && method instanceof EntityEnclosingMethod) { // handle redirects on post and put String url = method.getResponseHeader("Location").getValue(); method = new GetMethod(url); method.setFollowRedirects(true); method.setDoAuthentication(false); result = httpClient.executeMethod(method); } return new ProxyResponseImpl(result, method); } } catch (Exception e) { throw new ProxyClientException("The Proxy request specified by " + node + " failed, cause follows:", e); } finally { unbindNode(); } throw new ProxyClientException( "The Proxy request specified by " + node + " does not contain a valid endpoint specification "); }
From source file:org.sakaiproject.nakamura.proxy.ProxyClientServiceImpl.java
/** * Executes a HTTP call using a path in the JCR to point to a template and a map of * properties to populate that template with. An example might be a SOAP call. * * <pre>/*from www. j ava 2 s.co m*/ * {http://www.w3.org/2001/12/soap-envelope}Envelope:{ * {http://www.w3.org/2001/12/soap-envelope}Body:{ * {http://www.example.org/stock}GetStockPriceResponse:{ * >body:[ ] * {http://www.example.org/stock}Price:{ * >body:[34.5] * } * } * >body:[ ] * } * >body:[ ] * {http://www.w3.org/2001/12/soap-envelope}encodingStyle:[http://www.w3.org/2001/12/soap-encoding] * } * * </pre> * * @param resource * the resource containing the proxy end point specification. * @param headers * a map of headers to set int the request. * @param input * a map of parameters for all templates (both url and body) * @param requestInputStream * containing the request body (can be null if the call requires no body or the * template will be used to generate the body) * @param requestContentLength * if the requestImputStream is specified, the length specifies the lenght of * the body. * @param requerstContentType * the content type of the request, if null the node property * sakai:proxy-request-content-type will be used. * @throws ProxyClientException */ public ProxyResponse executeCall(Node node, Map<String, String> headers, Map<String, Object> input, InputStream requestInputStream, long requestContentLength, String requestContentType) throws ProxyClientException { try { bindNode(node); if (node != null && node.hasProperty(SAKAI_REQUEST_PROXY_ENDPOINT)) { // setup the post request String endpointURL = JcrUtils.getMultiValueString(node.getProperty(SAKAI_REQUEST_PROXY_ENDPOINT)); if (isUnsafeProxyDefinition(node)) { try { URL u = new URL(endpointURL); String host = u.getHost(); if (host.indexOf('$') >= 0) { throw new ProxyClientException( "Invalid Endpoint template, relies on request to resolve valid URL " + u); } } catch (MalformedURLException e) { throw new ProxyClientException( "Invalid Endpoint template, relies on request to resolve valid URL", e); } } // Find all velocity replacement variable(s) in the endpointURL, // copy any equivalent keys from the input Map, to a new Map that // can be process by Velocity. In the new Map, the Map value field // has been changed from RequestParameter[] to String. Map<String, String> inputContext = new HashMap<String, String>(); int startPosition = endpointURL.indexOf("${"); while (startPosition > -1) { int endPosition = endpointURL.indexOf("}", startPosition); if (endPosition > -1) { String key = endpointURL.substring(startPosition + 2, endPosition); Object value = input.get(key); if (value instanceof RequestParameter[]) { // now change input value object from RequestParameter[] to String // and add to inputContext Map. RequestParameter[] requestParameters = (RequestParameter[]) value; inputContext.put(key, requestParameters[0].getString()); } else { // KERN-1346 regression; see KERN-1409 inputContext.put(key, String.valueOf(value)); } // look for the next velocity replacement variable startPosition = endpointURL.indexOf("${", endPosition); } else { break; } } VelocityContext context = new VelocityContext(inputContext); // add in the config properties from the bundle overwriting everythign else. context.put("config", configProperties); endpointURL = processUrlTemplate(endpointURL, context); ProxyMethod proxyMethod = ProxyMethod.GET; if (node.hasProperty(SAKAI_REQUEST_PROXY_METHOD)) { try { proxyMethod = ProxyMethod.valueOf(node.getProperty(SAKAI_REQUEST_PROXY_METHOD).getString()); } catch (Exception e) { logger.debug("The Proxy request specified by " + node + " failed, cause follows:", e); } } HttpMethod method = null; switch (proxyMethod) { case GET: if (node.hasProperty(SAKAI_LIMIT_GET_SIZE)) { long maxSize = node.getProperty(SAKAI_LIMIT_GET_SIZE).getLong(); method = new HeadMethod(endpointURL); HttpMethodParams params = new HttpMethodParams(method.getParams()); // make certain we reject the body of a head params.setBooleanParameter("http.protocol.reject-head-body", true); method.setParams(params); method.setFollowRedirects(true); populateMethod(method, node, headers); int result = httpClient.executeMethod(method); if (externalAuthenticatingProxy && result == 407) { method.releaseConnection(); method.setDoAuthentication(true); result = httpClient.executeMethod(method); } if (result == 200) { // Check if the content-length is smaller than the maximum (if any). Header contentLengthHeader = method.getResponseHeader("Content-Length"); if (contentLengthHeader != null) { long length = Long.parseLong(contentLengthHeader.getValue()); if (length > maxSize) { return new ProxyResponseImpl(HttpServletResponse.SC_PRECONDITION_FAILED, "Response too large", method); } } } else { return new ProxyResponseImpl(result, method); } } method = new GetMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); break; case HEAD: method = new HeadMethod(endpointURL); HttpMethodParams params = new HttpMethodParams(method.getParams()); // make certain we reject the body of a head params.setBooleanParameter("http.protocol.reject-head-body", true); method.setParams(params); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); break; case OPTIONS: method = new OptionsMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); break; case POST: method = new PostMethod(endpointURL); break; case PUT: method = new PutMethod(endpointURL); break; default: method = new GetMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); } populateMethod(method, node, headers); if (requestInputStream == null && !node.hasProperty(SAKAI_PROXY_REQUEST_TEMPLATE)) { if (method instanceof PostMethod) { PostMethod postMethod = (PostMethod) method; ArrayList<Part> parts = new ArrayList<Part>(); for (Entry<String, Object> param : input.entrySet()) { String key = param.getKey(); Object value = param.getValue(); if (value instanceof RequestParameter[]) { for (RequestParameter val : (RequestParameter[]) param.getValue()) { Part part = null; if (val.isFormField()) { part = new StringPart(param.getKey(), val.getString()); } else { ByteArrayPartSource source = new ByteArrayPartSource(key, val.get()); part = new FilePart(key, source); } parts.add(part); } } else { parts.add(new StringPart(key, value.toString())); } Part[] partsArray = parts.toArray(new Part[parts.size()]); postMethod.setRequestEntity(new MultipartRequestEntity(partsArray, method.getParams())); } } } else { if (method instanceof EntityEnclosingMethod) { String contentType = requestContentType; if (contentType == null && node.hasProperty(SAKAI_REQUEST_CONTENT_TYPE)) { contentType = node.getProperty(SAKAI_REQUEST_CONTENT_TYPE).getString(); } if (contentType == null) { contentType = APPLICATION_OCTET_STREAM; } EntityEnclosingMethod eemethod = (EntityEnclosingMethod) method; if (requestInputStream != null) { eemethod.setRequestEntity(new InputStreamRequestEntity(requestInputStream, requestContentLength, contentType)); } else { // build the request Template template = velocityEngine.getTemplate(node.getPath()); StringWriter body = new StringWriter(); template.merge(context, body); byte[] soapBodyContent = body.toString().getBytes("UTF-8"); eemethod.setRequestEntity(new ByteArrayRequestEntity(soapBodyContent, contentType)); } } } int result = httpClient.executeMethod(method); if (externalAuthenticatingProxy && result == 407) { method.releaseConnection(); method.setDoAuthentication(true); result = httpClient.executeMethod(method); } if (result == 302 && method instanceof EntityEnclosingMethod) { // handle redirects on post and put String url = method.getResponseHeader("Location").getValue(); method = new GetMethod(url); method.setFollowRedirects(true); method.setDoAuthentication(false); result = httpClient.executeMethod(method); if (externalAuthenticatingProxy && result == 407) { method.releaseConnection(); method.setDoAuthentication(true); result = httpClient.executeMethod(method); } } return new ProxyResponseImpl(result, method); } } catch (ProxyClientException e) { throw e; } catch (Exception e) { throw new ProxyClientException("The Proxy request specified by " + node + " failed, cause follows:", e); } finally { unbindNode(); } throw new ProxyClientException( "The Proxy request specified by " + node + " does not contain a valid endpoint specification "); }
From source file:org.semispace.google.space.address.FetchAddress.java
public GoogleAddress resolveAddress(String address, GoogleKey key) { GoogleAddress result = new GoogleAddress(); String url = encodeAddressAsHttpParameter(address, key); log.debug("Query url: " + url); HttpMethod method = new GetMethod(url); try {/* ww w .j ava 2s . co m*/ result.setAddress(address); HttpClient client = new HttpClient(); method.setFollowRedirects(false); method.setDoAuthentication(false); client.executeMethod(method); byte[] buffer = method.getResponseBody(); fillResponseInAddress(result, new String(buffer)); } catch (IOException e) { result.setStatusCode("-1"); log.error("Got exception", e); } finally { method.releaseConnection(); } return result; }
From source file:org.soaplab.clients.spinet.ServiceController.java
/************************************************************************* * *************************************************************************/ protected boolean urlExists(String url) { HttpMethod method = null; try {/*from ww w .j a va 2 s . com*/ // instantiating an HttpClient and its HEAD method HttpClient httpClient = new HttpClient(); URI uri = new URI(url, false); method = new HeadMethod(uri.toString()); method.setFollowRedirects(true); // execute the method int statusCode = httpClient.executeMethod(method); return (statusCode == HttpStatus.SC_OK); } catch (Throwable e) { SoaplabException.formatAndLog(e, log); return false; } finally { // release the connection if (method != null) method.releaseConnection(); } }