List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody
public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException
From source file:orca.handlers.nlr.SherpaSession.java
void handleLogin(GetMethod cmdHttpGet) throws IOException { // need to request again to get to the login form // get whatever it is (not really interested) // this time follow the redirect // enableRedirects(); cmdHttpGet.setFollowRedirects(true); // get the login form dhc.executeMethod(cmdHttpGet);/*www . j a va 2s . com*/ // New location (login form post) // ideally the form port URL should come from the form // right now we make it a constant PostMethod httpform = new PostMethod(postURL); // add username/password and other form values NameValuePair login = new NameValuePair("login", sherpaLogin); NameValuePair password = new NameValuePair("password", sherpaPassword); NameValuePair reqd = new NameValuePair("required", ""); NameValuePair ref = new NameValuePair("ref", cmdHttpGet.getURI().toString()); NameValuePair service = new NameValuePair("service", sherpaService); NameValuePair realm = new NameValuePair("realm", sherpaRealm); httpform.setRequestBody(new NameValuePair[] { login, password, reqd, ref, service, realm }); // disableRedirects(); httpform.setFollowRedirects(false); // post the form dhc.executeMethod(httpform); }
From source file:org.alfresco.dataprep.UserService.java
/** * Login in alfresco share/*from ww w. j a va 2 s .com*/ * * @param userName login user name * @param userPass login user password * @return true for successful user login */ public HttpState login(final String userName, final String userPass) { if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(userPass)) { throw new IllegalArgumentException("Parameter missing"); } AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject(); HttpState state = null; org.apache.commons.httpclient.HttpClient theClient = new org.apache.commons.httpclient.HttpClient(); String reqURL = client.getShareUrl() + "share/page/dologin"; org.apache.commons.httpclient.methods.PostMethod post = new org.apache.commons.httpclient.methods.PostMethod( reqURL); NameValuePair[] formParams; CookieStore cookieStore = new BasicCookieStore(); HttpClientContext localContext = HttpClientContext.create(); localContext.setCookieStore(cookieStore); formParams = (new NameValuePair[] { new NameValuePair("username", userName), new NameValuePair("password", userPass), new NameValuePair("success", "/share/page/user/" + userName + "/dashboard"), new NameValuePair("failure", "/share/page/type/login?error=true") }); post.setRequestBody(formParams); try { int postStatus = theClient.executeMethod(post); if (302 == postStatus) { state = theClient.getState(); post.releaseConnection(); org.apache.commons.httpclient.methods.GetMethod get = new org.apache.commons.httpclient.methods.GetMethod( client.getShareUrl() + "share/page/user/" + userName + "/dashboard"); theClient.setState(state); theClient.executeMethod(get); get.releaseConnection(); } } catch (IOException e) { throw new RuntimeException("Failed to execute the request"); } return state; }
From source file:org.alfresco.jive.impl.JiveOpenClientImpl.java
/** * @see org.alfresco.jive.JiveOpenClient#createDocument(java.lang.String, long, java.lang.String, java.lang.String, long, java.lang.String) *//*from w w w .j a v a 2s . co m*/ @Override public void createDocument(final String userId, final long spaceId, final String cmisId, final String fileName, final long fileSize, final String mimeType) throws AuthenticationException, CallFailedException, SpaceNotFoundException, ServiceUnavailableException, DocumentSizeException { final String resolvedUrl = OPENCLIENT_API_CREATE_DOCUMENT.replace("{0}", String.valueOf(spaceId)); final PostMethod post = new PostMethod(buildUrl(resolvedUrl)); final NameValuePair[] body = constructNameValuePairs(cmisId, fileName, fileSize, mimeType); int status = -1; setCommonHeaders(userId, post); post.setRequestHeader("Content-Type", MIME_TYPE_FORM_URLENCODED); post.setRequestBody(body); try { status = callJive(post); if (status >= 400) { if (status == 401 || status == 403) { throw new AuthenticationException(); } else if (status == 404) { throw new SpaceNotFoundException(spaceId); } else if (status == 409) { throw new DocumentSizeException(fileName, fileSize); } else if (status == 503) { throw new ServiceUnavailableException(); } else { throw new CallFailedException(status); } } else if (status >= 300) { log.warn("Status code: " + status + ". cmisObjectID: " + cmisId); } } catch (final HttpException he) { throw new CallFailedException(he); } catch (final IOException ioe) { throw new CallFailedException(ioe); } finally { post.releaseConnection(); } }
From source file:org.alfresco.jive.impl.JiveOpenClientImpl.java
/** * @see org.alfresco.jive.JiveOpenClient#updateDocument(java.lang.String, java.lang.String, java.lang.String, long, java.lang.String) *///ww w . j a va 2 s .c om @Override public void updateDocument(final String userId, final String cmisId, final String fileName, final long fileSize, final String mimeType) throws AuthenticationException, CallFailedException, DocumentNotFoundException, ServiceUnavailableException, DocumentSizeException { final PutMethod put = new PutMethod(buildUrl(OPENCLIENT_API_UPDATE_DOCUMENT)); final PostMethod temp = new PostMethod(); int status = -1; setCommonHeaders(userId, put); put.setRequestHeader("Content-Type", MIME_TYPE_FORM_URLENCODED); // These shenanigans are required because PutMethod doesn't directly support content as NameValuePairs. temp.setRequestBody(constructNameValuePairs(cmisId, fileName, fileSize, mimeType)); put.setRequestEntity(temp.getRequestEntity()); try { status = callJive(put); if (status >= 400) { if (status == 401 || status == 403) { throw new AuthenticationException(); } else if (status == 404) { throw new DocumentNotFoundException(cmisId); } else if (status == 409) { throw new DocumentSizeException(fileName, fileSize); } else if (status == 503) { throw new ServiceUnavailableException(); } else { throw new CallFailedException(status); } } else if (status >= 300) { log.warn("Status code: " + status + ". cmisObjectID: " + cmisId); } } catch (final HttpException he) { throw new CallFailedException(he); } catch (final IOException ioe) { throw new CallFailedException(ioe); } finally { put.releaseConnection(); } }
From source file:org.alfresco.po.share.ShareUtil.java
public HtmlPage loginWithPost(WebDriver driver, String shareUrl, String userName, String password) { HttpClient client = new HttpClient(); //login/*www. j ava 2 s . c o m*/ PostMethod post = new PostMethod((new StringBuilder()).append(shareUrl).append("/page/dologin").toString()); NameValuePair[] formParams = (new NameValuePair[] { new org.apache.commons.httpclient.NameValuePair("username", userName), new org.apache.commons.httpclient.NameValuePair("password", password), new org.apache.commons.httpclient.NameValuePair("success", "/share/page/site-index"), new org.apache.commons.httpclient.NameValuePair("failure", "/share/page/type/login?error=true") }); post.setRequestBody(formParams); post.addRequestHeader("Accept-Language", "en-us,en;q=0.5"); try { client.executeMethod(post); HttpState state = client.getState(); //Navigate to login page to obtain a session cookie. driver.navigate().to(shareUrl); //add authenticated token to cookie and navigate to user dashboard String url = shareUrl + "/page/user/" + userName + "/dashboard"; driver.manage() .addCookie(new Cookie(state.getCookies()[0].getName(), state.getCookies()[0].getValue())); driver.navigate().to(url); } catch (IOException e) { e.printStackTrace(); logger.error("Login error ", e); } finally { post.releaseConnection(); } return factoryPage.getPage(driver); }
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
public Transfer begin(TransferTarget target, String fromRepositoryId, TransferVersion fromVersion) throws TransferException { PostMethod beginRequest = getPostMethod(); try {/*from w w w. ja va 2 s .c o m*/ HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); beginRequest.setPath(target.getEndpointPath() + "/begin"); try { NameValuePair[] nameValuePair = new NameValuePair[] { new NameValuePair(TransferCommons.PARAM_FROM_REPOSITORYID, fromRepositoryId), new NameValuePair(TransferCommons.PARAM_ALLOW_TRANSFER_TO_SELF, "false"), new NameValuePair(TransferCommons.PARAM_VERSION_EDITION, fromVersion.getEdition()), new NameValuePair(TransferCommons.PARAM_VERSION_MAJOR, fromVersion.getVersionMajor()), new NameValuePair(TransferCommons.PARAM_VERSION_MINOR, fromVersion.getVersionMinor()), new NameValuePair(TransferCommons.PARAM_VERSION_REVISION, fromVersion.getVersionRevision()) }; //add the parameter defining the root of the transfer on the file system if exist NodeRef transferRootNode = this.getFileTransferRootNodeRef(target.getNodeRef()); if (transferRootNode != null) { //add the parameter ArrayList<NameValuePair> nameValuePairArrayList = new ArrayList<NameValuePair>( nameValuePair.length + 1); Collections.addAll(nameValuePairArrayList, nameValuePair); nameValuePairArrayList.add(new NameValuePair(TransferCommons.PARAM_ROOT_FILE_TRANSFER, transferRootNode.toString())); nameValuePair = nameValuePairArrayList.toArray(new NameValuePair[0]); } beginRequest.setRequestBody(nameValuePair); int responseStatus = httpClient.executeMethod(hostConfig, beginRequest, httpState); checkResponseStatus("begin", responseStatus, beginRequest); //If we get here then we've received a 200 response //We're expecting the transfer id encoded in a JSON object... JSONObject response = new JSONObject(beginRequest.getResponseBodyAsString()); Transfer transfer = new Transfer(); transfer.setTransferTarget(target); String transferId = response.getString(TransferCommons.PARAM_TRANSFER_ID); transfer.setTransferId(transferId); if (response.has(TransferCommons.PARAM_VERSION_MAJOR)) { String versionMajor = response.getString(TransferCommons.PARAM_VERSION_MAJOR); String versionMinor = response.getString(TransferCommons.PARAM_VERSION_MINOR); String versionRevision = response.getString(TransferCommons.PARAM_VERSION_REVISION); String edition = response.getString(TransferCommons.PARAM_VERSION_EDITION); TransferVersion version = new TransferVersionImpl(versionMajor, versionMinor, versionRevision, edition); transfer.setToVersion(version); } else { TransferVersion version = new TransferVersionImpl("0", "0", "0", "Unknown"); transfer.setToVersion(version); } if (log.isDebugEnabled()) { log.debug("begin transfer transferId:" + transferId + ", target:" + target); } return transfer; } catch (RuntimeException e) { log.debug("unexpected exception", e); throw e; } catch (Exception e) { String error = "Failed to execute HTTP request to target"; log.debug(error, e); throw new TransferException(MSG_HTTP_REQUEST_FAILED, new Object[] { "begin", target.toString(), e.toString() }, e); } } finally { log.debug("releasing connection"); beginRequest.releaseConnection(); } }
From source file:org.alfresco.test.util.UserService.java
/** * Login in alfresco share//from w ww .j a v a 2s.c o m * * @param userName login user name * @param userPass login user password * @return true for successful user login * @throws Exception if error */ public boolean login(final String userName, final String userPass) throws Exception { if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(userPass)) { throw new IllegalArgumentException("Parameter missing"); } AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject(); HttpState state; org.apache.commons.httpclient.HttpClient theClient = new org.apache.commons.httpclient.HttpClient(); String reqURL = client.getAlfrescoUrl() + "share/page/dologin"; org.apache.commons.httpclient.methods.PostMethod post = new org.apache.commons.httpclient.methods.PostMethod( reqURL); NameValuePair[] formParams; CookieStore cookieStore = new BasicCookieStore(); HttpClientContext localContext = HttpClientContext.create(); localContext.setCookieStore(cookieStore); formParams = (new NameValuePair[] { new NameValuePair("username", userName), new NameValuePair("password", userPass), new NameValuePair("success", "/share/page/user/" + userName + "/dashboard"), new NameValuePair("failure", "/share/page/type/login?error=true") }); post.setRequestBody(formParams); int postStatus = theClient.executeMethod(post); if (302 == postStatus) { state = theClient.getState(); post.releaseConnection(); org.apache.commons.httpclient.methods.GetMethod get = new org.apache.commons.httpclient.methods.GetMethod( client.getAlfrescoUrl() + "share/page/user/" + userName + "/dashboard"); theClient.setState(state); int getStatus = theClient.executeMethod(get); get.releaseConnection(); if (200 == getStatus) { return true; } else { return false; } } else { return false; } }
From source file:org.andrewberman.sync.InheritMe.java
String post(String urlString, HashMap vars) throws Exception { PostMethod post = new PostMethod(urlString); try {//from ww w . jav a2 s . com NameValuePair[] params = hashToValuePairs(vars); post.setRequestBody(params); httpclient.executeMethod(post); String s = post.getResponseBodyAsString(); return s; } finally { post.releaseConnection(); } }
From source file:org.apache.ambari.funtest.server.AmbariHttpWebRequest.java
/** * Constructs a PostMethod and sets the request data on it. * * @return - PostMethod.//from w ww.j a v a2 s.com */ @SuppressWarnings("deprecation") private PostMethod getPostMethod() { PostMethod postMethod = new PostMethod(getUrl()); /* RequestEntity requestEntity = new StringRequestEntity( request.getContent(), request.getContentType(), request.getContentEncoding()); postMethod.setRequestEntity(requestEntity); */ postMethod.setRequestBody(getContent()); return postMethod; }
From source file:org.apache.axis2.maven2.aar.DeployAarMojo.java
/** * Deploys the AAR./*from ww w. j ava 2 s.c o m*/ * * @param aarFile the target AAR file * @throws MojoExecutionException * @throws HttpException * @throws IOException */ private void deploy(File aarFile) throws MojoExecutionException, IOException, HttpException { if (axis2AdminConsoleURL == null) { throw new MojoExecutionException("No Axis2 administrative console URL provided."); } // TODO get name of web service mount point HttpClient client = new HttpClient(); client.getParams().setParameter(HttpClientParams.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); // log into Axis2 administration console URL axis2AdminConsoleLoginURL = new URL(axis2AdminConsoleURL.toString() + "/login"); getLog().debug("Logging into Axis2 Admin Web Console " + axis2AdminConsoleLoginURL + " using user ID " + axis2AdminUser); PostMethod post = new PostMethod(axis2AdminConsoleLoginURL.toString()); NameValuePair[] nvps = new NameValuePair[] { new NameValuePair("userName", axis2AdminUser), new NameValuePair("password", axis2AdminPassword) }; post.setRequestBody(nvps); int status = client.executeMethod(post); if (status != 200) { throw new MojoExecutionException("Failed to log in"); } if (post.getResponseBodyAsString().indexOf(LOGIN_FAILED_ERROR_MESSAGE) != -1) { throw new MojoExecutionException( "Failed to log into Axis2 administration web console using credentials"); } // deploy AAR web service URL axis2AdminConsoleUploadURL = new URL(axis2AdminConsoleURL.toString() + "/upload"); getLog().debug("Uploading AAR to Axis2 Admin Web Console " + axis2AdminConsoleUploadURL); post = new PostMethod(axis2AdminConsoleUploadURL.toString()); Part[] parts = { new FilePart(project.getArtifact().getFile().getName(), project.getArtifact().getFile()) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); status = client.executeMethod(post); if (status != 200) { throw new MojoExecutionException("Failed to log in"); } // log out of web console URL axis2AdminConsoleLogoutURL = new URL(axis2AdminConsoleURL.toString() + "/logout"); getLog().debug("Logging out of Axis2 Admin Web Console " + axis2AdminConsoleLogoutURL); GetMethod get = new GetMethod(axis2AdminConsoleLogoutURL.toString()); status = client.executeMethod(get); if (status != 200) { throw new MojoExecutionException("Failed to log out"); } }