/** * Removes all parameters with the given paramName. If there is more than * one parameter with the given paramName, all of them are removed. If * there is just one, it is removed. If there are none, then the request * is ignored. * * @param paramName The parameter name to remove. * * @return true if at least one parameter was removed * * @throws IllegalArgumentException When the parameter name passed is null * * @since 2.0 */ public boolean removeParameter(String paramName) throws IllegalArgumentException { LOG.trace("enter PostMethod.removeParameter(String)"); if (paramName == null) { throw new IllegalArgumentException( "Argument passed to removeParameter(String) cannot be null"); } boolean removed = false; Iterator iter = this.params.iterator(); while (iter.hasNext()) { NameValuePair pair = (NameValuePair) iter.next(); if (paramName.equals(pair.getName())) { iter.remove(); removed = true; } } return removed; }
/** * 将NameValuePairs数组转变为字符串 * * @param nameValues * @return */ protected String toString(NameValuePair[] nameValues) { if (nameValues == null || nameValues.length == 0) { return "null"; } StringBuffer buffer = new StringBuffer(); for (int i = 0; i < nameValues.length; i++) { NameValuePair nameValue = nameValues[i]; if (i == 0) { buffer.append(nameValue.getName() + "=" + nameValue.getValue()); } else { buffer.append("&" + nameValue.getName() + "=" + nameValue.getValue()); } } return buffer.toString(); }
/** * Test for SLING-1677 */ @Test public void testUpdateUserResponseAsJSON() throws IOException, JsonException { testUserId = H.createTestUser(); String postUrl = HttpTest.HTTP_BASE_URL + "/system/userManager/user/" + testUserId + ".update.json"; List<NameValuePair> postParams = new ArrayList<NameValuePair>(); postParams.add(new NameValuePair("displayName", "My Updated Test User")); postParams.add(new NameValuePair("url", "http://www.apache.org/updated")); Credentials creds = new UsernamePasswordCredentials(testUserId, "testPwd"); String json = H.getAuthenticatedPostContent(creds, postUrl, HttpTest.CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK); //make sure the json response can be parsed as a JSON object JsonObject jsonObj = JsonUtil.parseObject(json); assertNotNull(jsonObj); }
/** * Return a string suitable for sending in a <tt>"Cookie"</tt> header as * defined in RFC 2965 * @param cookie a {@link org.apache.commons.httpclient.Cookie} to be formatted as string * @return a string suitable for sending in a <tt>"Cookie"</tt> header. */ public String formatCookie(final Cookie cookie) { LOG.trace("enter RFC2965Spec.formatCookie(Cookie)"); if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (cookie instanceof Cookie2) { Cookie2 cookie2 = (Cookie2) cookie; int version = cookie2.getVersion(); final StringBuffer buffer = new StringBuffer(); this.formatter.format(buffer, new NameValuePair("$Version", Integer.toString(version))); buffer.append("; "); doFormatCookie2(cookie2, buffer); return buffer.toString(); } else { // old-style cookies are formatted according to the old rules return this.rfc2109.formatCookie(cookie); } }
/** * Initializes the parameters required for the POST call to the PSP for * re-registration.. * * @param paymentInfo * The current payment information object. * @param paymentType * The payment type the iframe should be pre-configured for. * @param supplierId * Supplier context * @return The properties required for the connection to the PSP in order to * register the credit card or direct debit. */ private List<NameValuePair> initPostParametersForReRegistration( RequestData data) { List<NameValuePair> regParams = new ArrayList<NameValuePair>(); setBasicPostParameters(regParams, data); // operation code for re-registration, we use credit card as default. regParams.add(new NameValuePair(HeidelpayPostParameter.PAYMENT_CODE, getHeidelPayPaymentType(data.getPaymentTypeId()) + ".RR")); // also set the already stored reference id regParams.add(new NameValuePair( HeidelpayPostParameter.IDENTIFICATION_REFERENCEID, data .getExternalIdentifier())); initGeneralRegistrationPostData(regParams, data); return regParams; }
/** * Sets the parameters required to enable the WPF * * @param regParams * The list of name value pairs the WPF control parameters will * be added to. */ private void setWPFControlParameters(RequestData data, List<NameValuePair> regParams) { regParams.add(new NameValuePair( HeidelpayPostParameter.FRONTEND_ENABLED, "true")); regParams.add(new NameValuePair(HeidelpayPostParameter.FRONTEND_POPUP, "false")); regParams.add(new NameValuePair(HeidelpayPostParameter.FRONTEND_MODE, "DEFAULT")); regParams.add(new NameValuePair( HeidelpayPostParameter.FRONTEND_LANGUAGE, data .getCurrentUserLocale())); regParams.add(new NameValuePair( HeidelpayPostParameter.FRONTEND_ONEPAGE, "true")); regParams.add(new NameValuePair( HeidelpayPostParameter.FRONTEND_NEXT_TARGET, "self.location.href")); }
public void testRemoveAce() throws IOException, JsonException { String folderUrl = createFolderWithAces(false); //remove the ace for the testUser principal String postUrl = folderUrl + ".deleteAce.html"; List<NameValuePair> postParams = new ArrayList<NameValuePair>(); postParams.add(new NameValuePair(":applyTo", testUserId)); Credentials creds = new UsernamePasswordCredentials("admin", "admin"); assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, null); //fetch the JSON for the acl to verify the settings. String getUrl = folderUrl + ".acl.json"; String json = getAuthenticatedContent(creds, getUrl, CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK); assertNotNull(json); JsonObject jsonObject = JsonUtil.parseObject(json); assertNotNull(jsonObject); assertEquals(0, jsonObject.size()); }
@Override public RegistrationLink determineReregistrationLink(RequestData data) throws PSPCommunicationException { if (data == null) { throw new IllegalArgumentException("requestData must not be null!"); } setProxyForHTTPClient(data); List<NameValuePair> registrationParameters = initPostParametersForReRegistration(data); String regLinkDetails = retrieveRegistrationLinkDetails( registrationParameters, data); String result = validateLinkDetails(regLinkDetails); RegistrationLink link = new RegistrationLink(result, ""); return link; }
public void testRemoveAuthorizables() throws IOException { String userId = createTestUser(); String groupId = createTestGroup(); Credentials creds = new UsernamePasswordCredentials("admin", "admin"); String getUrl = HTTP_BASE_URL + "/system/userManager/user/" + userId + ".json"; assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_OK, null); //make sure the profile request returns some data getUrl = HTTP_BASE_URL + "/system/userManager/group/" + groupId + ".json"; assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_OK, null); //make sure the profile request returns some data String postUrl = HTTP_BASE_URL + "/system/userManager.delete.html"; List<NameValuePair> postParams = new ArrayList<NameValuePair>(); postParams.add(new NameValuePair(":applyTo", "group/" + groupId)); postParams.add(new NameValuePair(":applyTo", "user/" + userId)); assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, null); getUrl = HTTP_BASE_URL + "/system/userManager/user/" + userId + ".json"; assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_NOT_FOUND, null); //make sure the profile request returns some data getUrl = HTTP_BASE_URL + "/system/userManager/group/" + groupId + ".json"; assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_NOT_FOUND, null); //make sure the profile request returns some data }
/** * Gets the parameter of the specified name. If there exists more than one * parameter with the name paramName, then only the first one is returned. * * @param paramName name of the parameter * * @return If a parameter exists with the name argument, the coresponding * NameValuePair is returned. Otherwise null. * * @since 2.0 * */ public NameValuePair getParameter(String paramName) { LOG.trace("enter PostMethod.getParameter(String)"); if (paramName == null) { return null; } Iterator iter = this.params.iterator(); while (iter.hasNext()) { NameValuePair parameter = (NameValuePair) iter.next(); if (paramName.equals(parameter.getName())) { return parameter; } } return null; }
/** * Extracts a map of challenge parameters from an authentication challenge. * Keys in the map are lower-cased * * @param challengeStr the authentication challenge string * @return a map of authentication challenge parameters * @throws MalformedChallengeException when the authentication challenge string * is malformed * * @since 2.0beta1 */ public static Map extractParams(final String challengeStr) throws MalformedChallengeException { if (challengeStr == null) { throw new IllegalArgumentException("Challenge may not be null"); } int idx = challengeStr.indexOf(' '); if (idx == -1) { throw new MalformedChallengeException("Invalid challenge: " + challengeStr); } Map map = new HashMap(); ParameterParser parser = new ParameterParser(); List params = parser.parse( challengeStr.substring(idx + 1, challengeStr.length()), ','); for (int i = 0; i < params.size(); i++) { NameValuePair param = (NameValuePair) params.get(i); map.put(param.getName().toLowerCase(), param.getValue()); } return map; }
@Test public void deregisterPaymentInformation_CreditCard() throws PaymentDeregistrationException, XPathExpressionException, ParserConfigurationException, SAXException, IOException { // setup RequestData requestData = createRequestData(CREDIT_CARD); PostMethodStub.setStubReturnValue(sampleResponse); PaymentInfo pi = createPaymentInfo( PaymentCollectionType.PAYMENT_SERVICE_PROVIDER, PaymentInfoType.CREDIT_CARD.name()); pi.setKey(2L); // execute psp.deregisterPaymentInformation(requestData); // assert NameValuePair[] requestBodyDetails = PostMethodStub .getRequestBodyDetails(); Assert.assertNotNull("A request must have been generated", requestBodyDetails); Assert.assertEquals("Wrong number of parameters for the request", 1, requestBodyDetails.length); validateDeregistrationXMLResponse(pi, requestBodyDetails, "CC"); }
@Test public void deregisterPaymentInformation_DirectDebit() throws PaymentDeregistrationException, XPathExpressionException, ParserConfigurationException, SAXException, IOException { // setup RequestData requestData = createRequestData(DIRECT_DEBIT); PostMethodStub.setStubReturnValue(sampleResponse); PaymentInfo pi = createPaymentInfo( PaymentCollectionType.PAYMENT_SERVICE_PROVIDER, PaymentInfoType.CREDIT_CARD.name()); pi.setKey(2L); // execute psp.deregisterPaymentInformation(requestData); // assert NameValuePair[] requestBodyDetails = PostMethodStub .getRequestBodyDetails(); Assert.assertNotNull("A request must have been generated", requestBodyDetails); Assert.assertEquals("Wrong number of parameters for the request", 1, requestBodyDetails.length); validateDeregistrationXMLResponse(pi, requestBodyDetails, "DD"); }
@Test public void testValidatingCorrectFormCredentials() throws Exception { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("j_username", "admin")); params.add(new NameValuePair("j_password", "admin")); params.add(new NameValuePair("j_validate", "true")); HttpMethod post = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_OK, params, null); assertTrue(post.getResponseBodyAsString().length() == 0); List<NameValuePair> params2 = new ArrayList<NameValuePair>(); params2.add(new NameValuePair("j_validate", "true")); HttpMethod post2 = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_OK, params2, null); assertTrue(post2.getResponseBodyAsString().length() == 0); }
private HttpMethod createPostMethod(HttpServletRequest req, String redirectUrl) throws ServletException, NotLoggedInException { PostMethod post = new PostMethod(redirectUrl); addUserNameToHeader(post, req); addAcceptEncodingHeader(post, req); post.getParams().setContentCharset("UTF-8"); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); @SuppressWarnings("unchecked") Enumeration e = req.getParameterNames(); while (e.hasMoreElements()) { String paramName = (String) e.nextElement(); String[] values = req.getParameterValues(paramName); for (String value : values) { NameValuePair pair = new NameValuePair(paramName, value); pairs.add(pair); } } post.addParameters(pairs.toArray(new NameValuePair[0])); return post; }
public static final String httpClientPost(String url, ArrayList<NameValuePair> list) { String result = ""; HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(url); try { NameValuePair[] params = new NameValuePair[list.size()]; for (int i = 0; i < list.size(); i++) { params[i] = list.get(i); } postMethod.addParameters(params); client.executeMethod(postMethod); result = postMethod.getResponseBodyAsString(); } catch (Exception e) { logger.error(e); } finally { postMethod.releaseConnection(); } return result; }
/** * Test SLING-2165. Login Error should redirect back to the referrer * login page. * * @throws Exception */ public void testRedirectToLoginFormAfterLoginError() throws Exception { //login failure List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("j_username", "___bogus___")); params.add(new NameValuePair("j_password", "not_a_real_user")); final String loginPageUrl = String.format("%s/system/sling/form/login", HTTP_BASE_URL); PostMethod post = (PostMethod)assertPostStatus(HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_MOVED_TEMPORARILY, params, null, loginPageUrl); final Header locationHeader = post.getResponseHeader("Location"); String location = locationHeader.getValue(); int queryStrStart = location.indexOf('?'); if (queryStrStart != -1) { location = location.substring(0, queryStrStart); } assertEquals("Expected to remain on the form/login page", loginPageUrl, location); }
/** * Test for SLING-1677 */ @Test public void testCreateUserResponseAsJSON() throws IOException, JsonException { String postUrl = HttpTest.HTTP_BASE_URL + "/system/userManager/user.create.json"; testUserId = "testUser" + random.nextInt(); List<NameValuePair> postParams = new ArrayList<NameValuePair>(); postParams.add(new NameValuePair(":name", testUserId)); postParams.add(new NameValuePair("marker", testUserId)); postParams.add(new NameValuePair("pwd", "testPwd")); postParams.add(new NameValuePair("pwdConfirm", "testPwd")); Credentials creds = new UsernamePasswordCredentials("admin", "admin"); String json = H.getAuthenticatedPostContent(creds, postUrl, HttpTest.CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK); //make sure the json response can be parsed as a JSON object JsonObject jsonObj = JsonUtil.parseObject(json); assertNotNull(jsonObj); }
/** * Test the problem reported as SLING-1237 */ public void testRemoveGroupWithMembers() throws IOException { String groupId = createTestGroup(); String userId = createTestUser(); Credentials creds = new UsernamePasswordCredentials("admin", "admin"); String addMemberPostUrl = HTTP_BASE_URL + "/system/userManager/group/" + groupId + ".update.html"; List<NameValuePair> addMemberPostParams = new ArrayList<NameValuePair>(); addMemberPostParams.add(new NameValuePair(":member", userId)); assertAuthenticatedPostStatus(creds, addMemberPostUrl, HttpServletResponse.SC_OK, addMemberPostParams, null); String getUrl = HTTP_BASE_URL + "/system/userManager/group/" + groupId + ".json"; assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_OK, null); //make sure the profile request returns some data String postUrl = HTTP_BASE_URL + "/system/userManager/group/" + groupId + ".delete.html"; List<NameValuePair> postParams = new ArrayList<NameValuePair>(); assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, null); getUrl = HTTP_BASE_URL + "/system/userManager/group/" + groupId + ".json"; assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_NOT_FOUND, null); //make sure the profile request returns some data }
public void testDeleteOnly() throws Exception { final Map<String, String> props = new HashMap<String, String>(); props.put(PROP_NAME, PROP_VALUE); final String contentURL = testClient.createNode(postUrl + SlingPostConstants.DEFAULT_CREATE_SUFFIX, props); try { // assert property is set correctly final String propURL = contentURL + "/" + PROP_NAME; final String data = getContent(propURL + ".json", CONTENT_TYPE_JSON); final JsonObject json = JsonUtil.parseObject(data); assertEquals(PROP_VALUE, json.getString(PROP_NAME)); final List <NameValuePair> params = new LinkedList<NameValuePair> (); params.add(new NameValuePair(PROP_NAME + SlingPostConstants.SUFFIX_DELETE, "don't care")); assertPostStatus(contentURL, HttpServletResponse.SC_OK, params, PROP_NAME + " must be deleted"); assertHttpStatus(propURL, HttpServletResponse.SC_NOT_FOUND, PROP_NAME + " must be deleted"); } finally { deleteNode(contentURL); } }
/** * SLING-1091: test error reporting when attempting to create a node with an * invalid exact node name. */ public void testImportNodeWithInvalidExactName() throws IOException { final String testPath = TEST_BASE_PATH; Map<String, String> props = new HashMap<String, String>(); String testNode = testClient.createNode(HTTP_BASE_URL + testPath, props); urlsToDelete.add(testNode); List<NameValuePair> postParams = new ArrayList<NameValuePair>(); postParams.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_IMPORT)); postParams.add(new NameValuePair(SlingPostConstants.RP_NODE_NAME, "exactNodeName*")); String jsonContent = getStreamAsString(getClass().getResourceAsStream("/integration-test/servlets/post/testimport.json")); postParams.add(new NameValuePair(SlingPostConstants.RP_CONTENT, jsonContent)); postParams.add(new NameValuePair(SlingPostConstants.RP_CONTENT_TYPE, "json")); postParams.add(new NameValuePair(SlingPostConstants.RP_REDIRECT_TO, SERVLET_CONTEXT + testPath + "/*")); //expect a 500 status since the name is invalid String location = HTTP_BASE_URL + testPath; assertPostStatus(location, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, postParams, null); }
public void testCopyAncestor() throws IOException { final String testPath = TEST_BASE_PATH + "/AT_tcanc/" + System.currentTimeMillis(); final List<NameValuePair> opt = new ArrayList<NameValuePair>(); opt.add(new NameValuePair(testPath + "./@CopyFrom", "../")); final int expectedStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; assertPostStatus(HTTP_BASE_URL + testPath, expectedStatus, opt, "Expecting status " + expectedStatus); }
/** * Test for SLING-2415 Ability to delete child nodes of a subnode, without deleting the parent node * Using :applyTo value of "subnode_path/*" */ public void testDeleteAllChildrenOfSubNode() throws IOException { final String urlA = testClient.createNode(postUrl + SlingPostConstants.DEFAULT_CREATE_SUFFIX, null); final String urlB = testClient.createNode(postUrl + SlingPostConstants.DEFAULT_CREATE_SUFFIX, null); final String urlC = testClient.createNode(postUrl + SlingPostConstants.DEFAULT_CREATE_SUFFIX, null); final String urlD = testClient.createNode(postUrl + "/specific-location/for-delete", null); // initially all nodes must be found assertHttpStatus(urlA + DEFAULT_EXT, HttpServletResponse.SC_OK, "A must initially exist"); assertHttpStatus(urlB + DEFAULT_EXT, HttpServletResponse.SC_OK, "B must initially exist"); assertHttpStatus(urlC + DEFAULT_EXT, HttpServletResponse.SC_OK, "C must initially exist"); assertHttpStatus(urlD + DEFAULT_EXT, HttpServletResponse.SC_OK, "D must initially exist"); String testBaseUrl = HTTP_BASE_URL + TEST_BASE_PATH; String subPath = postUrl.substring(testBaseUrl.length() + 1); // delete and check final List <NameValuePair> params = new LinkedList<NameValuePair> (); params.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_DELETE)); params.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, String.format("%s/*", subPath))); assertPostStatus(testBaseUrl,HttpServletResponse.SC_OK,params,"Delete must return expected status"); assertHttpStatus(urlA + DEFAULT_EXT, HttpServletResponse.SC_NOT_FOUND, "A must be deleted"); assertHttpStatus(urlB + DEFAULT_EXT, HttpServletResponse.SC_NOT_FOUND, "B must be deleted"); assertHttpStatus(urlC + DEFAULT_EXT, HttpServletResponse.SC_NOT_FOUND, "C must be deleted"); assertHttpStatus(urlD + DEFAULT_EXT, HttpServletResponse.SC_NOT_FOUND, "D must be deleted"); }
@Test public void testValidatingIncorrectHttpBasicCredentials() throws Exception { // assume http and webdav are on the same host + port URL url = new URL(HttpTest.HTTP_BASE_URL); Credentials defaultcreds = new UsernamePasswordCredentials("garbage", "garbage"); H.getHttpClient().getState() .setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("j_validate", "true")); HttpMethod post = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_FORBIDDEN, params, null); assertXReason(post); HttpMethod get = H.assertHttpStatus(HttpTest.HTTP_BASE_URL + "/?j_validate=true", HttpServletResponse.SC_FORBIDDEN); assertXReason(get); }
public String getCharset() { String charset = null; Header contenttype = this.headers.getFirstHeader("Content-Type"); if (contenttype != null) { HeaderElement values[] = contenttype.getElements(); if (values.length == 1) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } if (charset != null) { return charset; } else { return DEFAULT_CONTENT_CHARSET; } }
private void assertWithRetries(String url, int expectedStatus, String expectedContent, String httpMethod, List<NameValuePair> params) throws Throwable { final long endTime = System.currentTimeMillis() + RETRY_MAX_TIME_SEC * 1000L; Throwable caught = null; while(System.currentTimeMillis() < endTime) { try { caught = null; assertContains(getContent(url, CONTENT_TYPE_HTML,params,expectedStatus, httpMethod), expectedContent); break; } catch(Throwable t) { caught = t; try { Thread.sleep(RETRY_INTERVAL_MSEC); } catch(InterruptedException ignored) { } } } if(caught != null) { throw caught; } }
/** * Return a string suitable for sending in a <tt>"Cookie"</tt> header * as defined in RFC 2109 for backward compatibility with cookie version 0 * @param buffer The string buffer to use for output * @param cookie The {@link Cookie} to be formatted as string * @param version The version to use. */ private void formatCookieAsVer(final StringBuffer buffer, final Cookie cookie, int version) { String value = cookie.getValue(); if (value == null) { value = ""; } formatParam(buffer, new NameValuePair(cookie.getName(), value), version); if ((cookie.getPath() != null) && cookie.isPathAttributeSpecified()) { buffer.append("; "); formatParam(buffer, new NameValuePair("$Path", cookie.getPath()), version); } if ((cookie.getDomain() != null) && cookie.isDomainAttributeSpecified()) { buffer.append("; "); formatParam(buffer, new NameValuePair("$Domain", cookie.getDomain()), version); } }
/** * Create a RFC 2109 compliant <tt>"Cookie"</tt> header value containing all * {@link Cookie}s in <i>cookies</i> suitable for sending in a <tt>"Cookie" * </tt> header * @param cookies an array of {@link Cookie}s to be formatted * @return a string suitable for sending in a Cookie header. */ public String formatCookies(Cookie[] cookies) { LOG.trace("enter RFC2109Spec.formatCookieHeader(Cookie[])"); int version = Integer.MAX_VALUE; // Pick the lowerest common denominator for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookie.getVersion() < version) { version = cookie.getVersion(); } } final StringBuffer buffer = new StringBuffer(); formatParam(buffer, new NameValuePair("$Version", Integer.toString(version)), version); for (int i = 0; i < cookies.length; i++) { buffer.append("; "); formatCookieAsVer(buffer, cookies[i], version); } return buffer.toString(); }
/** * Removes all parameter with the given paramName and paramValue. If there * is more than one parameter with the given paramName, only one is * removed. If there are none, then the request is ignored. * * @param paramName The parameter name to remove. * @param paramValue The parameter value to remove. * * @return true if a parameter was removed. * * @throws IllegalArgumentException when param name or value are null * * @since 2.0 */ public boolean removeParameter(String paramName, String paramValue) throws IllegalArgumentException { LOG.trace("enter PostMethod.removeParameter(String, String)"); if (paramName == null) { throw new IllegalArgumentException("Parameter name may not be null"); } if (paramValue == null) { throw new IllegalArgumentException("Parameter value may not be null"); } Iterator iter = this.params.iterator(); while (iter.hasNext()) { NameValuePair pair = (NameValuePair) iter.next(); if (paramName.equals(pair.getName()) && paramValue.equals(pair.getValue())) { iter.remove(); return true; } } return false; }
/** * Helper to assist adding a user to a group * @param testUserId the user * @param testGroupId the group */ public void addUserToGroup(String testUserId, String testGroupId) throws IOException { String postUrl = HTTP_BASE_URL + "/system/userManager/group/" + testGroupId + ".update.html"; List<NameValuePair> postParams = new ArrayList<NameValuePair>(); postParams.add(new NameValuePair(":member", testUserId)); Credentials creds = new UsernamePasswordCredentials("admin", "admin"); final String info = "Adding user " + testUserId + " to group via " + postUrl; assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, info); }
@Override public void tearDown() throws Exception { if (testGroupId != null) { //remove the test group if it exists. String postUrl = HTTP_BASE_URL + "/system/userManager/group/" + testGroupId + ".delete.html"; List<NameValuePair> postParams = new ArrayList<NameValuePair>(); assertAuthenticatedAdminPostStatus(postUrl, HttpServletResponse.SC_OK, postParams, null); } super.tearDown(); }
public String getAccessTokenUserPass() { if (!StringUtils.isEmpty(this.oAuth2AccessToken)) { return this.oAuth2AccessToken; } if (StringUtils.isEmpty(this.username) || StringUtils.isEmpty(this.password) && StringUtils.isEmpty(this.oAuth2AuthorizationServer) || StringUtils.isEmpty(this.oAuth2ClientId) || StringUtils.isEmpty(this.oAuth2ClientSecret)) { return ""; } try { HttpClient client = new HttpClient(); client.getParams().setAuthenticationPreemptive(true); // post development PostMethod method = new PostMethod(this.getOAuthAuthorizationServer()); method.setRequestHeader(new Header("Content-type", "application/x-www-form-urlencoded")); method.addRequestHeader("Authorization", "Basic " + Base64.encodeBase64String((username + ":" + password).getBytes())); NameValuePair[] body = new NameValuePair[] { new NameValuePair("username", username), new NameValuePair("password", password), new NameValuePair("client_id", oAuth2ClientId), new NameValuePair("client_secret", oAuth2ClientSecret), new NameValuePair("grant_type", oAuth2GrantType) }; method.setRequestBody(body); int responseCode = client.executeMethod(method); String responseBody = method.getResponseBodyAsString(); if (responseCode != 200) { throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer() + ", got response code " + responseCode); } JSONObject accessResponse = new JSONObject(responseBody); accessResponse.getString("access_token"); return (this.oAuth2AccessToken = accessResponse.getString("access_token")); } catch (Exception e) { throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e); } }
@SuppressWarnings("unchecked") public void test2(){ logger.info("我是不带参数的test2方法,正在被执行"); NameValuePair[] data = { new NameValuePair("account", "cf_xihuanqian"), new NameValuePair("password", "single1899"), new NameValuePair("mobile", "15504400427"), new NameValuePair("content", "尊敬的会员,您好,夏季新品已上市,请关注。退订回TD【互亿无线】"), new NameValuePair("format", "json") }; String url = "http://api.yx.ihuyi.com/webservice/sms.php?method=Submit"; System.out.println((Map<String,String>)JSON.parse(Sendsms.send(data,url))); }
/** * Checks all present name value pairs for the existence of an entry with * name FRONTEND.REDIRECT_URL. The found entry will be returned, null if * there is none. * * @param result * The list of name value pairs to search in. * @return The redirect URL, null if it is not set. */ private String getRedirectURL(List<NameValuePair> result) { String redirectURL = null; for (NameValuePair nvp : result) { if (HeidelpayPostParameter.FRONTEND_REDIRECT_URL.equals(nvp .getName())) { redirectURL = nvp.getValue(); break; } } return redirectURL; }
/** * Initializes the parameters required for the POST call to the PSP for * initial registration.. * * @param paymentInfo * The payment type of payment info the iframe should be * pre-configured for. * @return The properties required for the connection to the PSP in order to * register the credit card or direct debit. */ private List<NameValuePair> initPostParametersForRegistration( RequestData data) { List<NameValuePair> regParams = new ArrayList<NameValuePair>(); setBasicPostParameters(regParams, data); // operation code for registration, we use credit card as default. regParams.add(new NameValuePair(HeidelpayPostParameter.PAYMENT_CODE, getHeidelPayPaymentType(data.getPaymentTypeId()) + ".RG")); initGeneralRegistrationPostData(regParams, data); return regParams; }
/** * Sets the parameters required for a later callback to our system. * * @param regParams * The list of name value pairs the callback parameters will be * added to. */ private void setCallbackPostParameters(List<NameValuePair> regParams, RequestData data) { regParams.add(new NameValuePair( HeidelpayPostParameter.FRONTEND_REDIRECT_TIME, "0")); // use the base-url to determine the response address String servletBaseURL = data .getProperty(HeidelpayConfigurationKey.PSP_RESPONSE_SERVLET_URL .name()); regParams.add(new NameValuePair( HeidelpayPostParameter.FRONTEND_RESPONSE_URL, servletBaseURL)); }
/** * Sets the parameters to restrict the payment method choices a user can * make in the WPF. * * @param regParams * The list of name value pairs the restriction parameters will * be added to. * @param paymentInfo * The payment type from payment info the iframe should be * pre-configured for. */ private void setChoiceRestrictionPostParameters( List<NameValuePair> regParams, RequestData data) { regParams .add(new NameValuePair( HeidelpayPostParameter.FRONTEND_PM_DEFAULT_DISABLE_ALL, "true")); String restrictionValue = null; if ("DIRECT_DEBIT".equals(data.getPaymentTypeId())) { restrictionValue = data .getProperty(HeidelpayConfigurationKey.PSP_SUPPORTED_DD_COUNTRIES .name()); } if ("CREDIT_CARD".equals(data.getPaymentTypeId())) { restrictionValue = data .getProperty(HeidelpayConfigurationKey.PSP_SUPPORTED_CC_BRANDS .name()); } if (restrictionValue != null) { addPostParamsToRestrictPaymentOptions( getHeidelPayPaymentType(data.getPaymentTypeId()), restrictionValue, regParams); } }