List of usage examples for org.apache.commons.httpclient HttpMethod getParams
public abstract HttpMethodParams getParams();
From source file:org.parosproxy.paros.network.HttpSender.java
public int executeMethod(HttpMethod method, HttpState state) throws IOException { int responseCode = -1; String hostName;/*from ww w .jav a 2 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:org.paxle.crawler.http.impl.HttpCrawler.java
/** * Initializes the {@link HttpMethod} with common attributes for all requests this crawler * initiates./*from w w w.ja va 2 s .c om*/ * <p> * Currently the following attributes (represented as HTTP header values in the final request) * are set: * <ul> * <li>the cookie policy to use ({@link #PROP_COOKIE_POLICY})</li> * <li> * if enabled, content-transformation using <code>compress</code>, <code>gzip</code> and * <code>deflate</code> is supported</li> * </li> * </ul> * * @param method the method to set the standard attributes on */ private void initRequestMethod(final HttpMethod method) throws URIException { method.getParams().setCookiePolicy( this.cookiePolicy == null ? CookiePolicy.BROWSER_COMPATIBILITY : this.cookiePolicy); if (acceptEncoding && !isHostSettingSet(method.getURI().getHost(), PREF_NO_ENCODING)) method.setRequestHeader(HTTPHEADER_ACCEPT_ENCODING, "compress, gzip, identity, deflate"); // see RFC 2616, section 14.3 // set some additional http headers if (this.userAgent != null) { method.setRequestHeader("User-Agent", this.userAgent); } }
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>/* ww w . ja v a 2 s. com*/ * {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.siberia.image.searcher.impl.GoogleImageSearcher.java
/** search */ public void search() { // http://images.google.fr/images?imgsz=xxlarge&gbv=2&hl=fr&q=b+e&btnG=Recherche+d%27images // http://images.google.fr/images?imgsz=xxlarge&hl=fr&q=b+e Runnable run = new Runnable() { public void run() { fireSearchHasBegan(new ImageSearcherEvent(GoogleImageSearcher.this)); StringBuffer buffer = new StringBuffer(50); if (getCriterions() != null) { boolean oneTokenAlreadyApplied = false; for (int i = 0; i < getCriterions().length; i++) { String current = getCriterions()[i]; if (current != null) { if (oneTokenAlreadyApplied) { buffer.append("+"); }/*ww w . j ava 2s. c o m*/ buffer.append(current); oneTokenAlreadyApplied = true; } } } Locale locale = getLocale(); if (locale == null) { locale = Locale.getDefault(); } if (logger.isDebugEnabled()) { logger.debug("uri : " + buffer.toString()); } HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(GOOGLE_URL); NameValuePair[] pairs = new NameValuePair[3]; pairs[0] = new NameValuePair("imgsz", convertImageSizeCriterion(getImageSize())); pairs[1] = new NameValuePair("hl", locale.getCountry().toLowerCase()); pairs[2] = new NameValuePair("q", buffer.toString()); method.setQueryString(pairs); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); InputStream stream = null; try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { /** on recherche partir des motifs suivants * la premire occurrence de http:// partir de l, on prend jusqu'au prochaine espace ou '>' : * * exemple : * <img src=http://tbn0.google.com/images?q=tbn:GIJo-j_dSy4FiM:http://www.discogs.com/image/R-378796-1136999170.jpeg width=135 height=135> * * on trouve le motif, puis, on prend partir de http://www.discogs jusqu'au prochain espace... * * --> http://www.discogs.com/image/R-378796-1136999170.jpeg */ String searchMotif = "<img src=http://tbn0.google.com/images?q"; String urlMotif = "http://"; int indexInSearchMotif = -1; int indexInUrlMotif = -1; boolean motifFound = false; boolean foundUrl = false; StringBuffer urlBuffer = new StringBuffer(50); // Read the response body. byte[] bytes = new byte[1024 * 8]; stream = method.getResponseBodyAsStream(); if (stream != null) { int read = -1; int linksRetrieved = 0; while ((read = stream.read(bytes)) != -1) { for (int i = 0; i < read; i++) { byte currentByte = bytes[i]; if (motifFound) { if (foundUrl) { if (currentByte == ' ' || currentByte == '>') { /* add current url to list of result */ try { URL url = new URL(urlBuffer.toString()); fireImageFound(new ImageFoundEvent(GoogleImageSearcher.this, url, linksRetrieved)); linksRetrieved++; if (linksRetrieved >= getMaximumLinksRetrieved()) { break; } } catch (Exception e) { e.printStackTrace(); } finally { urlBuffer.delete(0, urlBuffer.length()); foundUrl = false; motifFound = false; } } else { /* add current byte to url buffer */ urlBuffer.append((char) currentByte); } } else { if (indexInUrlMotif == urlMotif.length() - 1) { urlBuffer.append(urlMotif); urlBuffer.append((char) currentByte); foundUrl = true; indexInUrlMotif = -1; } /* if the current byte is the same as that attempted on the url motif let's continue */ if (((char) currentByte) == urlMotif.charAt(indexInUrlMotif + 1)) { indexInUrlMotif++; } else { indexInUrlMotif = -1; } } } else { if (indexInSearchMotif == searchMotif.length() - 1) { motifFound = true; indexInSearchMotif = -1; } if (((char) currentByte) == searchMotif.charAt(indexInSearchMotif + 1)) { indexInSearchMotif++; } else { indexInSearchMotif = -1; } } } if (linksRetrieved >= getMaximumLinksRetrieved()) { break; } } } } else { System.err.println("Method failed: " + method.getStatusLine()); } } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { if (stream != null) { try { stream.close(); } catch (IOException ex) { System.err.println("Fatal transport error: " + ex.getMessage()); } } System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); fireSearchFinished(new ImageSearcherEvent(GoogleImageSearcher.this)); } } }; this.service.submit(run); }
From source file:org.sonatype.nexus.bundle.launcher.support.RequestUtils.java
public static boolean isNexusRESTStarted(final String nexusBaseURI) throws IOException, HttpException { Preconditions.checkNotNull(nexusBaseURI); final String serviceStatusURI = nexusBaseURI.endsWith("/") ? nexusBaseURI + "service/local/status" : nexusBaseURI + "/service/local/status"; org.apache.commons.httpclient.HttpMethod method = null; try {//from w w w . j a v a 2s . c o m method = new GetMethod(serviceStatusURI); // only try once makes sense by default DefaultHttpMethodRetryHandler oneRetry = new DefaultHttpMethodRetryHandler(1, true); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, oneRetry); method = executeHTTPClientMethodAsAdmin(method); final int statusCode = method.getStatusCode(); if (statusCode != 200) { LOG.debug("Status check returned status " + statusCode); return false; } final String entityText = method.getResponseBodyAsString(); if (entityText == null || !entityText.contains("<state>STARTED</state>")) { LOG.debug("Status check returned invalid system state. Status: " + entityText); return false; } return true; } finally { if (method != null) { method.releaseConnection(); // request facade does this but just making sure } } }
From source file:org.tgta.tagger.AnnotationClient.java
public String request(HttpMethod method) throws AnnotationException { String response = null;//from ww w . j a va 2 s. com // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { LOG.error("Method failed: " + method.getStatusLine()); } // Read the response body. //byte[] responseBody; InputStream in = method.getResponseBodyAsStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); } //System.out.println(out.toString()); //Prints the string content read from input stream reader.close(); response = out.toString(); //TODO Going to buffer response body of large or unknown size. //Using getResponseBodyAsStream instead is recommended. // Deal with the response. // Use caution: ensure correct character encoding and is not binary data //response = new String(responseBody); } catch (HttpException e) { LOG.error("Fatal protocol violation: " + e.getMessage()); throw new AnnotationException("Protocol error executing HTTP request.", e); } catch (IOException e) { LOG.error("Fatal transport error: " + e.getMessage()); LOG.error(method.getQueryString()); throw new AnnotationException("Transport error executing HTTP request.", e); } finally { // Release the connection. method.releaseConnection(); } return response; }
From source file:org.wso2.carbon.mashup.javascript.hostobjects.pooledhttpclient.PooledHttpClientHostObject.java
/** * Used by jsFunction_executeMethod()./*from w w w . j a v a2 s.c o m*/ * * @param httpClient * @param contentType * @param charset * @param methodName * @param content * @param params */ private static void setParams(PooledHttpClientHostObject httpClient, HttpMethod method, String contentType, String charset, String methodName, Object content, NativeObject params) { // other parameters have been set, they are properly set to the // corresponding context if (ScriptableObject.getProperty(params, "cookiePolicy") instanceof String) { method.getParams().setCookiePolicy((String) ScriptableObject.getProperty(params, "cookiePolicy")); } else if (!ScriptableObject.getProperty(params, "cookiePolicy").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (ScriptableObject.getProperty(params, "contentType") instanceof String) { contentType = (String) ScriptableObject.getProperty(params, "contentType"); } else if (!ScriptableObject.getProperty(params, "contentType").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (ScriptableObject.getProperty(params, "charset") instanceof String) { charset = (String) ScriptableObject.getProperty(params, "charset"); } else if (!ScriptableObject.getProperty(params, "charset").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (ScriptableObject.getProperty(params, "timeout") instanceof Integer) { method.getParams().setSoTimeout((Integer) ScriptableObject.getProperty(params, "timeout")); } else if (!ScriptableObject.getProperty(params, "timeout").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (ScriptableObject.getProperty(params, "doAuthentication") instanceof Boolean) { method.setDoAuthentication((Boolean) ScriptableObject.getProperty(params, "doAuthentication")); } else if (!ScriptableObject.getProperty(params, "doAuthentication").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (ScriptableObject.getProperty(params, "followRedirect") instanceof Boolean) { method.setFollowRedirects((Boolean) ScriptableObject.getProperty(params, "followRedirect")); } else if (!ScriptableObject.getProperty(params, "followRedirect").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (methodName.equals("POST")) { // several parameters are specific to POST method if (ScriptableObject.getProperty(params, "contentChunked") instanceof Boolean) { boolean chuncked = (Boolean) ScriptableObject.getProperty(params, "contentChunked"); ((PostMethod) method).setContentChunked(chuncked); if (chuncked && content != null) { // if contentChucked is set true, then // InputStreamRequestEntity or // MultipartRequestEntity is used if (content instanceof String) { // InputStreamRequestEntity for string content ((PostMethod) method).setRequestEntity(new InputStreamRequestEntity( new ByteArrayInputStream(((String) content).getBytes()))); } else { // MultipartRequestEntity for Name-Value pair // content NativeObject element; List<StringPart> parts = new ArrayList<StringPart>(); String eName; String eValue; // create pairs using name-value pairs for (int i = 0; i < ((NativeArray) content).getLength(); i++) { if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) { element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content); if (ScriptableObject.getProperty(element, "name") instanceof String && ScriptableObject.getProperty(element, "value") instanceof String) { eName = (String) ScriptableObject.getProperty(element, "name"); eValue = (String) ScriptableObject.getProperty(element, "value"); parts.add(new StringPart(eName, eValue)); } else { throw new RuntimeException("Invalid content definition, objects of the content" + " array should consists with strings for both key/value"); } } else { throw new RuntimeException( "Invalid content definition, content array should contain " + "Javascript Objects"); } } ((PostMethod) method).setRequestEntity(new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), method.getParams())); } } } else if (ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND) && content != null) { // contentChunking has not used if (content instanceof String) { try { ((PostMethod) method) .setRequestEntity(new StringRequestEntity((String) content, contentType, charset)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unsupported Charset"); } } else { NativeObject element; List<NameValuePair> pairs = new ArrayList<NameValuePair>(); String eName; String eValue; // create pairs using name-value pairs for (int i = 0; i < ((NativeArray) content).getLength(); i++) { if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) { element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content); if (ScriptableObject.getProperty(element, "name") instanceof String && ScriptableObject.getProperty(element, "value") instanceof String) { eName = (String) ScriptableObject.getProperty(element, "name"); eValue = (String) ScriptableObject.getProperty(element, "value"); pairs.add(new NameValuePair(eName, eValue)); } else { throw new RuntimeException( "Invalid content definition, objects of the content array " + "should consists with strings for both key/value"); } } else { throw new RuntimeException("Invalid content definition, content array should contain " + "Javascript Objects"); } } ((PostMethod) method).setRequestBody(pairs.toArray(new NameValuePair[pairs.size()])); } } else if (!ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } } else if (methodName.equals("GET")) { // here, the method now is GET if (content != null) { if (content instanceof String) { method.setQueryString((String) content); } else { NativeObject element; List<NameValuePair> pairs = new ArrayList<NameValuePair>(); String eName; String eValue; // create pairs using name-value pairs for (int i = 0; i < ((NativeArray) content).getLength(); i++) { if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) { element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content); if (ScriptableObject.getProperty(element, "name") instanceof String && ScriptableObject.getProperty(element, "value") instanceof String) { eName = (String) ScriptableObject.getProperty(element, "name"); eValue = (String) ScriptableObject.getProperty(element, "value"); pairs.add(new NameValuePair(eName, eValue)); } else { throw new RuntimeException( "Invalid content definition, objects of the content array " + "should consists with strings for both key/value"); } } else { throw new RuntimeException("Invalid content definition, content array should contain " + "Javascript Objects"); } } method.setQueryString(pairs.toArray(new NameValuePair[pairs.size()])); } } } else if (methodName.equals("PUT")) { // several parameters are specific to PUT method if (ScriptableObject.getProperty(params, "contentChunked") instanceof Boolean) { boolean chuncked = (Boolean) ScriptableObject.getProperty(params, "contentChunked"); ((PutMethod) method).setContentChunked(chuncked); if (chuncked && content != null) { // if contentChucked is set true, then // InputStreamRequestEntity or // MultipartRequestEntity is used if (content instanceof String) { // InputStreamRequestEntity for string content ((PostMethod) method).setRequestEntity(new InputStreamRequestEntity( new ByteArrayInputStream(((String) content).getBytes()))); } else { throw new RuntimeException( "Invalid content definition, content should be a string when PUT " + "method is used"); } } } else if (ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND) && content != null) { // contentChunking has not used if (content instanceof String) { try { ((PostMethod) method) .setRequestEntity(new StringRequestEntity((String) content, contentType, charset)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unsupported Charset"); } } else { throw new RuntimeException( "Invalid content definition, content should be a string when PUT " + "method is used"); } } else if (!ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } } // check whether preemptive authentication is used if (ScriptableObject.getProperty(params, "preemptiveAuth") instanceof Boolean) { httpClient.httpClient.getParams() .setAuthenticationPreemptive((Boolean) ScriptableObject.getProperty(params, "preemptiveAuth")); } else if (!ScriptableObject.getProperty(params, "preemptiveAuth").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } }
From source file:org.wso2.carbon.mediator.ntlm.CustomNTLMAuthScheme.java
/** * Produces NTLM authorization string for the given set of * {@link Credentials}.//w w w .j av a2 s.c o m * * @param credentials * The set of credentials to be used for athentication * @param method * The method being authenticated * * @throws InvalidCredentialsException * if authentication credentials are not valid or not applicable * for this authentication scheme * @throws AuthenticationException * if authorization string cannot be generated due to an * authentication failure * * @return an NTLM authorization string * * @since 3.0 */ public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException { LOG.trace("enter NTLMScheme.authenticate (Credentials, HttpMethod)"); if (this.state == UNINITIATED) { throw new IllegalStateException("NTLM authentication process has not been initiated"); } NTCredentials ntcredentials = null; try { ntcredentials = (NTCredentials) credentials; } catch (ClassCastException e) { throw new InvalidCredentialsException( "Credentials cannot be used for NTLM authentication: " + credentials.getClass().getName()); } byte[] msgBytes = null; String response = null; if (this.state == INITIATED) { Type1Message msg = new Type1Message(); // @see http://davenport.sourceforge.net/ntlm.html#theType1Message // dont' support Unicode // negotiate OEM // request authentication realm in Type2 response // not signed // not encrypted // not authenticated // no lan manager key // negotiate NTLM msg.setFlags(0x5206); msg.setSuppliedWorkstation(ntcredentials.getHost()); msg.setSuppliedDomain(ntcredentials.getDomain()); msgBytes = msg.toByteArray(); this.state = TYPE1_MSG_GENERATED; } else if (this.state == TYPE2_MSG_RECEIVED) { byte[] msg2Bytes = Base64.decodeBase64( EncodingUtil.getBytes(this.ntlmChallenge, method.getParams().getCredentialCharset())); try { Type2Message msg2 = new Type2Message(msg2Bytes); int flags = Type3Message.NTLMSSP_NEGOTIATE_OEM | Type3Message.NTLMSSP_NEGOTIATE_LM_KEY; Type3Message msg3 = new Type3Message(msg2, ntcredentials.getPassword(), ntcredentials.getDomain(), ntcredentials.getUserName(), ntcredentials.getHost(), flags); msgBytes = msg3.toByteArray(); } catch (IOException ex) { throw new AuthenticationException("unable to parse Type2Message", ex); } this.state = TYPE3_MSG_GENERATED; } else { throw new RuntimeException("failed to authenticate"); } response = EncodingUtil.getAsciiString(Base64.encodeBase64(msgBytes)); return "NTLM " + response; }