List of usage examples for org.apache.commons.httpclient.methods PostMethod addParameter
public void addParameter(String paramString1, String paramString2) throws IllegalArgumentException
From source file:org.jahia.bin.RenderTest.java
@Test public void testRestAPI() throws RepositoryException, IOException, JSONException { JCRPublicationService jcrService = ServicesRegistry.getInstance().getJCRPublicationService(); Locale englishLocale = LanguageCodeConverters.languageCodeToLocale("en"); JCRSessionWrapper editSession = jcrService.getSessionFactory() .getCurrentUserSession(Constants.EDIT_WORKSPACE, englishLocale); jcrService.getSessionFactory().getCurrentUserSession(Constants.LIVE_WORKSPACE, englishLocale); JCRNodeWrapper stageRootNode = editSession.getNode(SITECONTENT_ROOT_NODE); JCRNodeWrapper stageNode = stageRootNode.getNode("home"); JCRNodeWrapper stagedPageContent = stageNode.getNode("listA"); JCRNodeWrapper mainContent = stagedPageContent.addNode("mainContent", "jnt:mainContent"); mainContent.setProperty("jcr:title", MAIN_CONTENT_TITLE + "0"); mainContent.setProperty("body", MAIN_CONTENT_BODY + "0"); editSession.save();//from ww w .j a v a 2 s .c om PostMethod createPost = new PostMethod("http://localhost:8080" + Jahia.getContextPath() + "/cms/render/default/en" + SITECONTENT_ROOT_NODE + "/home/listA/*"); createPost.addRequestHeader("x-requested-with", "XMLHttpRequest"); createPost.addRequestHeader("accept", "application/json"); // here we voluntarily don't set the node name to test automatic name creation. createPost.addParameter("jcrNodeType", "jnt:mainContent"); createPost.addParameter("jcr:title", MAIN_CONTENT_TITLE + "1"); createPost.addParameter("body", MAIN_CONTENT_BODY + "1"); int responseCode = client.executeMethod(createPost); assertEquals("Error in response, code=" + responseCode, 201, responseCode); String responseBody = createPost.getResponseBodyAsString(); JSONObject jsonResults = new JSONObject(responseBody); assertNotNull("A proper JSONObject instance was expected, got null instead", jsonResults); assertTrue("body property should be " + MAIN_CONTENT_BODY + "1", jsonResults.get("body").equals(MAIN_CONTENT_BODY + "1")); }
From source file:org.jahia.modules.filter.WebClippingFilter.java
private String getURLContentWithPostMethod(String urlToClip, RenderContext renderContext, Resource resource, RenderChain chain, Map map) { String path = urlToClip;//from w w w . jav a 2 s . c om Map parameters = (Map) map.get("URL_PARAMS"); // Get the httpClient HttpClient httpClient = new HttpClient(); Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443)); httpClient.getParams().setContentCharset("UTF-8"); // Create a post method for accessing the url. PostMethod postMethod = new PostMethod(path); // Set a default retry handler (see httpclient doc). postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); if (parameters != null) { Iterator iterator = parameters.entrySet().iterator(); StringBuffer buffer = new StringBuffer(4096); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); if (!entry.getKey().toString().equals("original_method") && !entry.getKey().toString().equals("jahia_url_web_clipping")) { final Object value = entry.getValue(); if (value instanceof String[]) { buffer.setLength(0); String[] strings = (String[]) entry.getValue(); for (int i = 0; i < strings.length; i++) { String string = strings[i]; buffer.append((i != 0) ? "," : "").append(string); } postMethod.addParameter(entry.getKey().toString(), buffer.toString()); } else { postMethod.addParameter(entry.getKey().toString(), value.toString()); } } } } String contentCharset = httpClient.getParams().getContentCharset(); httpClient.getParams().setContentCharset(contentCharset); return getResponse(path, renderContext, resource, chain, postMethod, httpClient); }
From source file:org.jahia.services.notification.HttpClientService.java
/** * Executes a request with POST method to the specified URL and reads the response content as a string. * * @param url a URL to connect to/*w w w . jav a 2s . c om*/ * @param parameters the request parameter to submit; <code>null</code> if no parameters are passed * @param headers request headers to be set for connection; <code>null</code> if no additional headers needs to be set * @param state the HTTP state object if additional state options, e.g. credentials, needs to be specified; otherwise can be <code>null</code> * @return the string representation of the URL connection response * @throws {@link IllegalArgumentException} in case of a malformed URL */ public String executePost(String url, Map<String, String> parameters, Map<String, String> headers, HttpState state) throws IllegalArgumentException { if (StringUtils.isEmpty(url)) { throw new IllegalArgumentException("Provided URL is null"); } if (logger.isDebugEnabled()) { logger.debug("Asked to get content from the URL {} using POST method with parameters {}", url, parameters); } String content = null; PostMethod httpMethod = new PostMethod(url); if (parameters != null && !parameters.isEmpty()) { for (Map.Entry<String, String> param : parameters.entrySet()) { httpMethod.addParameter(param.getKey(), param.getValue()); } } if (headers != null && !headers.isEmpty()) { for (Map.Entry<String, String> header : headers.entrySet()) { httpMethod.addRequestHeader(header.getKey(), header.getValue()); } } try { getHttpClient(url).executeMethod(null, httpMethod, state); StatusLine statusLine = httpMethod.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() == SC_OK) { content = httpMethod.getResponseBodyAsString(); } else { logger.warn("Connection to URL: " + url + " failed with status " + statusLine); } } catch (HttpException e) { logger.error("Unable to get the content of the URL: " + url + ". Cause: " + e.getMessage(), e); } catch (IOException e) { logger.error("Unable to get the content of the URL: " + url + ". Cause: " + e.getMessage(), e); } finally { httpMethod.releaseConnection(); } if (logger.isDebugEnabled()) { logger.debug("Retrieved " + (content != null ? content.length() : 0) + " characters as a response"); if (logger.isTraceEnabled()) { logger.trace("Content:\n" + content); } } return content; }
From source file:org.jahia.services.translation.microsoft.MicrosoftTranslationProvider.java
private String authenticate(JCRSiteNode site, Locale uiLocale) throws TranslationException { String clientId = null;/*from w ww. j a v a2s.c om*/ String clientSecret = null; try { if (site.isNodeType("jmix:microsoftTranslatorSettings")) { clientId = site.getPropertyAsString("j:microsoftClientId"); clientSecret = site.getPropertyAsString("j:microsoftClientSecret"); } } catch (RepositoryException e) { throw new TranslationException( Messages.get(module, "siteSettings.translation.microsoft.failedToGetCredentials", uiLocale)); } String key = clientId + clientSecret; String accessToken; if (!accesses.containsKey(key) || accesses.get(key).getExpiration() < System.currentTimeMillis()) { PostMethod method = new PostMethod(accessTokenUrl); method.addParameter("grant_type", "client_credentials"); method.addParameter("client_id", clientId); method.addParameter("client_secret", clientSecret); method.addParameter("scope", "http://api.microsofttranslator.com"); int returnCode; String bodyAsString; long callTime = System.currentTimeMillis(); try { returnCode = httpClientService.getHttpClient().executeMethod(method); bodyAsString = method.getResponseBodyAsString(); if (returnCode != HttpStatus.SC_OK) { throw new TranslationException(Messages.getWithArgs(ResourceBundles.get(module, uiLocale), "siteSettings.translation.microsoft.errorWithCode", returnCode), bodyAsString); } } catch (IOException e) { throw new TranslationException( Messages.get(module, "siteSettings.translation.microsoft.failedToCallService", uiLocale)); } finally { method.releaseConnection(); } try { JSONObject jsonObject = new JSONObject(bodyAsString); accessToken = jsonObject.getString("access_token"); accesses.put(key, new MicrosoftTranslatorAccess(accessToken, callTime + (jsonObject.getLong("expires_in") - 1) * 1000)); // substract 1 second to expiration time for execution time } catch (JSONException e) { throw new TranslationException( Messages.get(module, "siteSettings.translation.microsoft.failedToParse", uiLocale)); } } else { accessToken = accesses.get(key).getToken(); } return accessToken; }
From source file:org.jahia.services.versioning.VersioningTest.java
@Before public void setUp() throws Exception { try {// w w w .j av a 2 s . c o m site = TestHelper.createSite(TESTSITE_NAME, "localhost" + System.currentTimeMillis(), TestHelper.INTRANET_TEMPLATES); assertNotNull(site); } catch (Exception ex) { logger.warn("Exception during test setUp", ex); } // Create an instance of HttpClient. client = new HttpClient(); // todo we should really insert content to test the find. PostMethod loginMethod = new PostMethod("http://localhost:8080" + Jahia.getContextPath() + "/cms/login"); loginMethod.addParameter("username", "root"); loginMethod.addParameter("password", "root1234"); loginMethod.addParameter("redirectActive", "false"); // the next parameter is required to properly activate the valve check. loginMethod.addParameter(LoginEngineAuthValveImpl.LOGIN_TAG_PARAMETER, "1"); int statusCode = client.executeMethod(loginMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + loginMethod.getStatusLine()); } yyyy_mm_dd_hh_mm_ss = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss"); languagesStringSet = new LinkedHashSet<String>(); languagesStringSet.add(Locale.ENGLISH.toString()); }
From source file:org.jahia.services.versioning.VersioningTest.java
@After public void tearDown() throws Exception { PostMethod logoutMethod = new PostMethod("http://localhost:8080" + Jahia.getContextPath() + "/cms/logout"); logoutMethod.addParameter("redirectActive", "false"); int statusCode = client.executeMethod(logoutMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + logoutMethod.getStatusLine()); }//from w w w . j a va 2 s. co m logoutMethod.releaseConnection(); try { TestHelper.deleteSite(TESTSITE_NAME); } catch (Exception ex) { logger.warn("Exception during test tearDown", ex); } JCRSessionFactory.getInstance().closeAllSessions(); }
From source file:org.jahia.test.bin.FindPrincipalTest.java
@Before public void setUp() throws Exception { // Create an instance of HttpClient. client = new HttpClient(); // todo we should really insert content to test the find. PostMethod loginMethod = new PostMethod(getLoginServletURL()); try {/*from w w w .j a v a 2 s . co m*/ loginMethod.addParameter("username", "root"); loginMethod.addParameter("password", "root1234"); loginMethod.addParameter("redirectActive", "false"); // the next parameter is required to properly activate the valve check. loginMethod.addParameter(LoginEngineAuthValveImpl.LOGIN_TAG_PARAMETER, "1"); // Provide custom retry handler is necessary loginMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); int statusCode = client.executeMethod(loginMethod); assertEquals("Method failed: " + loginMethod.getStatusLine(), HttpStatus.SC_OK, statusCode); } finally { loginMethod.releaseConnection(); } }
From source file:org.jahia.test.bin.FindPrincipalTest.java
@After public void tearDown() throws Exception { PostMethod logoutMethod = new PostMethod(getLogoutServletURL()); try {//from w ww .j av a 2 s . co m logoutMethod.addParameter("redirectActive", "false"); // Provide custom retry handler is necessary logoutMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); int statusCode = client.executeMethod(logoutMethod); assertEquals("Method failed: " + logoutMethod.getStatusLine(), HttpStatus.SC_OK, statusCode); } finally { logoutMethod.releaseConnection(); } }
From source file:org.jahia.test.bin.FindPrincipalTest.java
@Test public void testFindUsers() throws IOException, JSONException, JahiaException { PostMethod method = new PostMethod(getFindPrincipalServletURL()); try {// w ww . j a v a 2 s . c o m method.addParameter("principalType", "users"); method.addParameter("wildcardTerm", "*root*"); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Execute the method. int statusCode = client.executeMethod(method); assertEquals("Method failed: " + method.getStatusLine(), HttpStatus.SC_OK, statusCode); // Read the response body. StringBuilder responseBodyBuilder = new StringBuilder(); responseBodyBuilder.append("[").append(method.getResponseBodyAsString()).append("]"); String responseBody = responseBodyBuilder.toString(); JSONArray jsonResults = new JSONArray(responseBody); assertNotNull("A proper JSONObject instance was expected, got null instead", jsonResults); } finally { method.releaseConnection(); } // @todo we need to add more tests to validate results. }
From source file:org.jahia.test.bin.FindPrincipalTest.java
@Test public void testFindGroups() throws IOException, JSONException { PostMethod method = new PostMethod(getFindPrincipalServletURL()); try {// ww w . jav a 2 s. c o m method.addParameter("principalType", "groups"); method.addParameter("siteKey", TESTSITE_NAME); method.addParameter("wildcardTerm", "*administrators*"); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Execute the method. int statusCode = client.executeMethod(method); assertEquals("Method failed: " + method.getStatusLine(), HttpStatus.SC_OK, statusCode); // Read the response body. StringBuilder responseBodyBuilder = new StringBuilder(); responseBodyBuilder.append("[").append(method.getResponseBodyAsString()).append("]"); String responseBody = responseBodyBuilder.toString(); JSONArray jsonResults = new JSONArray(responseBody); assertNotNull("A proper JSONObject instance was expected, got null instead", jsonResults); } finally { method.releaseConnection(); } // @todo we need to add more tests to validate results. }