List of usage examples for org.apache.commons.httpclient NameValuePair NameValuePair
public NameValuePair(String name, String value)
From source file:org.apache.hcatalog.templeton.TestWebHCatE2e.java
/** * tries to drop table in a DB that doesn't exist *//*from www.j a v a 2s . c o m*/ @Ignore("not ready due to HIVE-4824") @Test public void dropTableNoSuchDbIfExists() throws IOException { MethodCallRetVal p = doHttpCall(templetonBaseUrl + "/ddl/database/no_such_db/table/t1", HTTP_METHOD_TYPE.DELETE, null, new NameValuePair[] { new NameValuePair("ifExists", "true") }); Assert.assertEquals(p.getAssertMsg(), HttpStatus.NOT_FOUND_404, p.httpStatusCode); Assert.assertEquals(p.getAssertMsg(), ErrorMsg.DATABASE_NOT_EXISTS.getErrorCode(), getErrorCode(p.responseBody)); }
From source file:org.apache.hcatalog.templeton.TestWebHCatE2e.java
/** * tries to drop table that doesn't exist (with ifExists=true) */// w w w.j av a 2 s . c o m @Ignore("not ready due to HIVE-4824") @Test public void dropTableIfExists() throws IOException { MethodCallRetVal p = doHttpCall(templetonBaseUrl + "/ddl/database/default/table/no_such_table", HTTP_METHOD_TYPE.DELETE, null, new NameValuePair[] { new NameValuePair("ifExists", "true") }); Assert.assertEquals(p.getAssertMsg(), HttpStatus.OK_200, p.httpStatusCode); }
From source file:org.apache.hcatalog.templeton.TestWebHCatE2e.java
/** * Does a basic HTTP GET and returns Http Status code + response body * Will add the dummy user query string//from ww w .ja va2s.co m */ private static MethodCallRetVal doHttpCall(String uri, HTTP_METHOD_TYPE type, Map<String, Object> data, NameValuePair[] params) throws IOException { HttpClient client = new HttpClient(); HttpMethod method; switch (type) { case GET: method = new GetMethod(uri); break; case DELETE: method = new DeleteMethod(uri); break; case PUT: method = new PutMethod(uri); if (data == null) { break; } String msgBody = JsonBuilder.mapToJson(data); LOG.info("Msg Body: " + msgBody); StringRequestEntity sre = new StringRequestEntity(msgBody, "application/json", charSet); ((PutMethod) method).setRequestEntity(sre); break; default: throw new IllegalArgumentException("Unsupported method type: " + type); } if (params == null) { method.setQueryString(new NameValuePair[] { new NameValuePair("user.name", username) }); } else { NameValuePair[] newParams = new NameValuePair[params.length + 1]; System.arraycopy(params, 0, newParams, 1, params.length); newParams[0] = new NameValuePair("user.name", username); method.setQueryString(newParams); } String actualUri = "no URI"; try { actualUri = method.getURI().toString();//should this be escaped string? LOG.debug(type + ": " + method.getURI().getEscapedURI()); int httpStatus = client.executeMethod(method); LOG.debug("Http Status Code=" + httpStatus); String resp = method.getResponseBodyAsString(); LOG.debug("response: " + resp); return new MethodCallRetVal(httpStatus, resp, actualUri, method.getName()); } catch (IOException ex) { LOG.error("doHttpCall() failed", ex); } finally { method.releaseConnection(); } return new MethodCallRetVal(-1, "Http " + type + " failed; see log file for details", actualUri, method.getName()); }
From source file:org.apache.jackrabbit.spi2davex.PostMethod.java
/** * Adds a new parameter to be used in the POST request body. * * @param paramName The parameter name to add. * @param paramValue The parameter value to add. * @throws IllegalArgumentException if either argument is null */// w w w . jav a 2s .c om public void addParameter(String paramName, String paramValue) throws IllegalArgumentException { log.debug("enter PostMethod.addParameter(String, String)"); if ((paramName == null) || (paramValue == null)) { throw new IllegalArgumentException("Arguments to addParameter(String, String) cannot be null"); } super.clearRequestBody(); params.add(new NameValuePair(paramName, paramValue)); }
From source file:org.apache.jetspeed.portlets.sso.SSOWebContentPortlet.java
protected byte[] doPreemptiveAuthentication(HttpClient client, HttpMethod method, RenderRequest request, RenderResponse response) {// ww w . j a va 2 s. c o m byte[] result = super.doPreemptiveAuthentication(client, method, request, response); if (result != null) { // already handled return result; } // System.out.println("SSOWebContentPortlet.doPreemptiveAuthentication..."); PortletPreferences prefs = request.getPreferences(); String type = getSingleSignOnAuthType(prefs); if (type.equalsIgnoreCase(SSO_TYPE_BASIC_PREEMPTIVE)) { // Preemptive, basic authentication String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; // System.out.println("...performing preemptive basic authentication with userName: "+userName+", and password: "+password); method.setDoAuthentication(true); method.getHostAuthState().setPreemptive(); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); // handled! return result; } else if (type.startsWith(SSO_TYPE_FORM)) { try { Boolean formAuth = (Boolean) PortletMessaging.receive(request, FORM_AUTH_STATE); if (formAuth != null) { // already been here, done that return (formAuth.booleanValue() ? result : null); } else { // stop recursion, but assume failure, ...for now PortletMessaging.publish(request, FORM_AUTH_STATE, Boolean.FALSE); } String formAction = prefs.getValue(SSO_TYPE_FORM_ACTION_URL, ""); if (formAction == null || formAction.length() == 0) { log.warn("sso.type specified as 'form', but no: " + SSO_TYPE_FORM_ACTION_URL + ", action was specified - unable to preemptively authenticate by form."); return null; } String userNameField = prefs.getValue(SSO_TYPE_FORM_USERNAME_FIELD, ""); if (userNameField == null || userNameField.length() == 0) { log.warn("sso.type specified as 'form', but no: " + SSO_TYPE_FORM_USERNAME_FIELD + ", username field was specified - unable to preemptively authenticate by form."); return null; } String passwordField = prefs.getValue(SSO_TYPE_FORM_PASSWORD_FIELD, "password"); if (passwordField == null || passwordField.length() == 0) { log.warn("sso.type specified as 'form', but no: " + SSO_TYPE_FORM_PASSWORD_FIELD + ", password field was specified - unable to preemptively authenticate by form."); return null; } String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; // get submit method int i = type.indexOf('.'); boolean isPost = i > 0 ? type.substring(i + 1).equalsIgnoreCase("post") : true; // default to post, since it is a form // get parameter map HashMap formParams = new HashMap(); formParams.put(userNameField, new String[] { userName }); formParams.put(passwordField, new String[] { password }); String formArgs = prefs.getValue(SSO_TYPE_FORM_ACTION_ARGS, ""); if (formArgs != null && formArgs.length() > 0) { StringTokenizer iter = new StringTokenizer(formArgs, ";"); while (iter.hasMoreTokens()) { String pair = iter.nextToken(); i = pair.indexOf('='); if (i > 0) formParams.put(pair.substring(0, i), new String[] { pair.substring(i + 1) }); } } // resuse client - in case new cookies get set - but create a new method (for the formAction) String formMethod = (isPost) ? FORM_POST_METHOD : FORM_GET_METHOD; method = getHttpMethod(client, getURLSource(formAction, formParams, request, response), formParams, formMethod, request); // System.out.println("...posting credentials"); result = doHttpWebContent(client, method, 0, request, response); // System.out.println("Result of attempted authorization: "+success); PortletMessaging.publish(request, FORM_AUTH_STATE, Boolean.valueOf(result != null)); return result; } catch (Exception ex) { // bad log.error("Form-based authentication failed", ex); } } else if (type.equalsIgnoreCase(SSO_TYPE_URL) || type.equalsIgnoreCase(SSO_TYPE_URL_BASE64)) { // set user name and password parameters in the HttpMethod String userNameParam = prefs.getValue(SSO_TYPE_URL_USERNAME_PARAM, ""); if (userNameParam == null || userNameParam.length() == 0) { log.warn("sso.type specified as 'url', but no: " + SSO_TYPE_URL_USERNAME_PARAM + ", username parameter was specified - unable to preemptively authenticate by URL."); return null; } String passwordParam = prefs.getValue(SSO_TYPE_URL_PASSWORD_PARAM, ""); if (passwordParam == null || passwordParam.length() == 0) { log.warn("sso.type specified as 'url', but no: " + SSO_TYPE_URL_PASSWORD_PARAM + ", password parameter was specified - unable to preemptively authenticate by URL."); return null; } String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; if (type.equalsIgnoreCase(SSO_TYPE_URL_BASE64)) { Base64 encoder = new Base64(); userName = new String(encoder.encode(userName.getBytes())); password = new String(encoder.encode(password.getBytes())); } // GET and POST accept args differently if (method instanceof PostMethod) { // add POST data PostMethod postMethod = (PostMethod) method; postMethod.addParameter(userNameParam, userName); postMethod.addParameter(passwordParam, password); } else { // augment GET query string NameValuePair[] authPairs = new NameValuePair[] { new NameValuePair(userNameParam, userName), new NameValuePair(passwordParam, password) }; String existingQuery = method.getQueryString(); method.setQueryString(authPairs); if (existingQuery != null && existingQuery.length() > 0) { // augment existing query with new auth query existingQuery = existingQuery + '&' + method.getQueryString(); method.setQueryString(existingQuery); } } return result; } // else System.out.println("...sso.type: "+type+", no pre-emptive authentication"); // not handled return null; }
From source file:org.apache.nutch.protocol.httpclient.HttpFormAuthentication.java
private List<NameValuePair> getLoginFormParams(String pageContent) throws UnsupportedEncodingException { List<NameValuePair> params = new ArrayList<NameValuePair>(); Document doc = Jsoup.parse(pageContent); Element loginform = doc.getElementById(authConfigurer.getLoginFormId()); if (loginform == null) { LOG.debug("No form element found with 'id' = {}, trying 'name'.", authConfigurer.getLoginFormId()); loginform = doc.select("form[name=" + authConfigurer.getLoginFormId() + "]").first(); if (loginform == null) { LOG.debug("No form element found with 'name' = {}", authConfigurer.getLoginFormId()); throw new IllegalArgumentException("No form exists: " + authConfigurer.getLoginFormId()); }/* w ww . ja va2 s . c o m*/ } Elements inputElements = loginform.getElementsByTag("input"); // skip fields in removedFormFields or loginPostData for (Element inputElement : inputElements) { String key = inputElement.attr("name"); String value = inputElement.attr("value"); if (authConfigurer.getLoginPostData().containsKey(key) || authConfigurer.getRemovedFormFields().contains(key)) { // value = loginPostData.get(key); continue; } params.add(new NameValuePair(key, value)); } // add key and value in loginPostData for (Entry<String, String> entry : authConfigurer.getLoginPostData().entrySet()) { params.add(new NameValuePair(entry.getKey(), entry.getValue())); } return params; }
From source file:org.apache.nutch.protocol.httpclient.proxy.HttpFormAuthentication.java
private List<NameValuePair> getLoginFormParams(String pageContent) throws UnsupportedEncodingException { List<NameValuePair> params = new ArrayList<NameValuePair>(); Document doc = Jsoup.parse(pageContent); Element loginform = doc.getElementById(authConfigurer.getLoginFormId()); if (loginform == null) { LOGGER.debug("No form element found with 'id' = {}, trying 'name'.", authConfigurer.getLoginFormId()); loginform = doc.select("form[name=" + authConfigurer.getLoginFormId() + "]").first(); if (loginform == null) { LOGGER.debug("No form element found with 'name' = {}", authConfigurer.getLoginFormId()); throw new IllegalArgumentException("No form exists: " + authConfigurer.getLoginFormId()); }/* w w w .j a v a2 s . c om*/ } Elements inputElements = loginform.getElementsByTag("input"); // skip fields in removedFormFields or loginPostData for (Element inputElement : inputElements) { String key = inputElement.attr("name"); String value = inputElement.attr("value"); if (authConfigurer.getLoginPostData().containsKey(key) || authConfigurer.getRemovedFormFields().contains(key)) { // value = loginPostData.get(key); continue; } params.add(new NameValuePair(key, value)); } // add key and value in loginPostData for (Entry<String, String> entry : authConfigurer.getLoginPostData().entrySet()) { params.add(new NameValuePair(entry.getKey(), entry.getValue())); } return params; }
From source file:org.apache.ode.axis2.util.URLEncodedTransformer.java
/** * @param values - a map<String, Element>, the key is a part name (without curly braces), the value the replacement value for the part name. If the value is not a simple type, it will be skipped. * @return the encoded params/*from www .java 2s.com*/ */ public String transform(Map<String, Element> values) { if (values.isEmpty()) return null; List<NameValuePair> l = new ArrayList<NameValuePair>(values.size()); for (Map.Entry<String, Element> e : values.entrySet()) { String partName = e.getKey(); Element value = e.getValue(); String textValue; if (DOMUtils.isEmptyElement(value)) { textValue = ""; } else { /* The expected part value could be a simple type or an element of a simple type. So if a element is there, take its text content else take the text content of the part element itself */ Element childElement = DOMUtils.getFirstChildElement(value); if (childElement != null) { textValue = DOMUtils.getTextContent(childElement); } else { textValue = DOMUtils.getTextContent(value); } } // if it is not a simple type, skip it if (textValue != null) { l.add(new NameValuePair(e.getKey(), textValue)); } } return EncodingUtil.formUrlEncode(l.toArray(new NameValuePair[0]), "UTF-8"); }
From source file:org.apache.oodt.cas.filemgr.catalog.solr.SolrClient.java
/** * Method to execute a GET request to the given URL with the given parameters. * @param url// w ww . ja v a2s. c o m * @param parameters * @return */ private String doGet(String url, Map<String, String[]> parameters, String mimeType) throws IOException, CatalogException { // build HTTP/GET request GetMethod method = new GetMethod(url); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); for (Map.Entry<String, String[]> key : parameters.entrySet()) { for (String value : key.getValue()) { nvps.add(new NameValuePair(key.getKey(), value)); } } // request results in JSON format if (mimeType.equals(Parameters.MIME_TYPE_JSON)) { nvps.add(new NameValuePair("wt", "json")); } method.setQueryString(nvps.toArray(new NameValuePair[nvps.size()])); LOG.info("GET url: " + url + " query string: " + method.getQueryString()); // send HTTP/GET request, return response return doHttp(method); }
From source file:org.apache.oodt.security.sso.opensso.SSOProxy.java
public String authenticate(String username, String password) { HttpClient httpClient = new HttpClient(); PostMethod post = new PostMethod(AUTH_ENDPOINT); String response;/* ww w . j a v a 2 s . c om*/ String ssoToken = null; NameValuePair[] data = { new NameValuePair("username", username), new NameValuePair("password", password), new NameValuePair("uri", "realm/lmmp") }; post.setRequestBody(data); try { httpClient.executeMethod(post); if (post.getStatusCode() != HttpStatus.SC_OK) { throw new HttpException(post.getStatusLine().toString()); } response = post.getResponseBodyAsString().trim(); ssoToken = response.substring(9); } catch (Exception e) { LOG.log(Level.SEVERE, e.getMessage()); } finally { post.releaseConnection(); } return ssoToken; }