List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:com.twinsoft.convertigo.engine.util.RemoteAdmin.java
public void deployArchive(File archiveFile, boolean bAssembleXsl) throws RemoteAdminException { String deployServiceURL = (bHttps ? "https" : "http") + "://" + serverBaseUrl + "/admin/services/projects.Deploy?bAssembleXsl=" + bAssembleXsl; PostMethod deployMethod = null; Protocol myhttps = null;// w w w . ja v a2 s.c o m try { if (bHttps && bTrustAllCertificates) { ProtocolSocketFactory socketFactory = MySSLSocketFactory.getSSLSocketFactory(null, null, null, null, true); myhttps = new Protocol("https", socketFactory, serverPort); Protocol.registerProtocol("https", myhttps); hostConfiguration = httpClient.getHostConfiguration(); hostConfiguration.setHost(host, serverPort, myhttps); httpClient.setHostConfiguration(hostConfiguration); } deployMethod = new PostMethod(deployServiceURL); Part[] parts = { new FilePart(archiveFile.getName(), archiveFile) }; deployMethod.setRequestEntity(new MultipartRequestEntity(parts, deployMethod.getParams())); int returnCode = httpClient.executeMethod(deployMethod); String httpResponse = deployMethod.getResponseBodyAsString(); if (returnCode == HttpStatus.SC_OK) { Document domResponse; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); domResponse = parser.parse(new InputSource(new StringReader(httpResponse))); domResponse.normalize(); NodeList nodeList = domResponse.getElementsByTagName("error"); if (nodeList.getLength() != 0) { Element errorNode = (Element) nodeList.item(0); Element errorMessage = (Element) errorNode.getElementsByTagName("message").item(0); Element exceptionName = (Element) errorNode.getElementsByTagName("exception").item(0); Element stackTrace = (Element) errorNode.getElementsByTagName("stacktrace").item(0); if (errorMessage != null) { throw new RemoteAdminException(errorMessage.getTextContent(), exceptionName.getTextContent(), stackTrace.getTextContent()); } else { throw new RemoteAdminException( "An unexpected error has occured during the Convertigo project deployment: \n" + "Body content: \n\n" + XMLUtils.prettyPrintDOMWithEncoding(domResponse, "UTF-8")); } } } catch (ParserConfigurationException e) { throw new RemoteAdminException("Unable to parse the Convertigo server response: \n" + e.getMessage() + ".\n" + "Received response: " + httpResponse); } catch (IOException e) { throw new RemoteAdminException( "An unexpected error has occured during the Convertigo project deployment.\n" + "(IOException) " + e.getMessage() + "\n" + "Received response: " + httpResponse, e); } catch (SAXException e) { throw new RemoteAdminException("Unable to parse the Convertigo server response: " + e.getMessage() + ".\n" + "Received response: " + httpResponse); } } else { decodeResponseError(httpResponse); } } catch (HttpException e) { throw new RemoteAdminException( "An unexpected error has occured during the Convertigo project deployment.\n" + "Cause: " + e.getMessage(), e); } catch (IOException e) { throw new RemoteAdminException( "Unable to reach the Convertigo server: \n" + "(IOException) " + e.getMessage(), e); } catch (Exception e) { throw new RemoteAdminException( "Unable to reach the Convertigo server: \n" + "(Exception) " + e.getMessage(), e); } finally { Protocol.unregisterProtocol("https"); if (deployMethod != null) deployMethod.releaseConnection(); } }
From source file:com.apatar.ui.JFeatureRequestHelpDialog.java
private void addListeners() { sendButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { PostMethod filePost = new PostMethod(getUrl()); // filePost.getParameters().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); try { if (!CoreUtils.validEmail(emailField.getText())) { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "E-mail address is invalid! Please, write a valid e-mail."); return; }//from w ww . ja v a2 s. c o m Part[] parts; parts = new Part[4]; parts[0] = new StringPart("FeatureRequest", text.getText()); parts[1] = new StringPart("FirstName", firstNameField.getText()); parts[2] = new StringPart("LastName", lastNameField.getText()); parts[3] = new StringPart("Email", emailField.getText()); filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status != HttpStatus.SC_OK) JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Upload failed, response=" + HttpStatus.getStatusText(status)); else { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Your message has been sent. Thank you!"); dispose(); } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } } }); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); }
From source file:com.kylinolap.jdbc.stub.KylinClient.java
/** * @param sql/*ww w . j a va2 s. c o m*/ * @return * @throws IOException */ private SQLResponseStub runKylinQuery(String sql, List<StateParam> params) throws SQLException { String url = conn.getQueryUrl(); String project = conn.getProject(); QueryRequest request = null; if (null != params) { request = new PreQueryRequest(); ((PreQueryRequest) request).setParams(params); url += "/prestate"; } else { request = new QueryRequest(); } request.setSql(sql); request.setProject(project); PostMethod post = new PostMethod(url); addPostHeaders(post); HttpClient httpClient = new HttpClient(); if (conn.getQueryUrl().toLowerCase().startsWith("https://")) { registerSsl(); } String postBody = null; ObjectMapper mapper = new ObjectMapper(); try { postBody = mapper.writeValueAsString(request); logger.debug("Post body:\n " + postBody); } catch (JsonProcessingException e) { logger.error(e.getLocalizedMessage(), e); } String response = null; SQLResponseStub queryRes = null; try { StringRequestEntity requestEntity = new StringRequestEntity(postBody, "application/json", "UTF-8"); post.setRequestEntity(requestEntity); httpClient.executeMethod(post); response = post.getResponseBodyAsString(); if (post.getStatusCode() != 200 && post.getStatusCode() != 201) { logger.error("Failed to query", response); throw new SQLException(response); } queryRes = new ObjectMapper().readValue(response, SQLResponseStub.class); } catch (HttpException e) { logger.error(e.getLocalizedMessage(), e); throw new SQLException(e.getLocalizedMessage()); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); throw new SQLException(e.getLocalizedMessage()); } return queryRes; }
From source file:com.evolveum.midpoint.model.impl.bulkmodify.PostXML.java
/** * This method takes emailAddress as a search value and returns user's oid with the given emailAddress * * @param emailAddress// w w w . j a v a 2s. co m * @return user object's oid if the given username exists. Empty String if the emailAddress does not exist. * @throws Exception * * This method */ public String searchByEmailPostMethod(String emailAddress) throws Exception { String returnOid = ""; // Get target URL String strURL = "http://localhost:8080/midpoint/ws/rest/users/search"; // Prepare HTTP post PostMethod post = new PostMethod(strURL); //AUTHENTICATION String userPass = this.getUsername() + ":" + this.getPassword(); String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8")); post.addRequestHeader("Authorization", basicAuth); //construct searching string. place "name" attribute into <values> tags. String sendingXml = XML_TEMPLATE_SEARCH_BYEMAIL; sendingXml = sendingXml.replace("<value></value>", "<value>" + emailAddress + "</value>"); RequestEntity userSearchEntity = new StringRequestEntity(sendingXml, "application/xml", "UTF-8"); post.setRequestEntity(userSearchEntity); // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try { int result = httpclient.executeMethod(post); // Display status code //System.out.println("Response status code: " + result); // Display response //System.out.println("Response body: "); // System.out.println(post.getResponseBodyAsString()); String sbf = new String(post.getResponseBodyAsString()); //System.out.println(sbf); //find oid if (sbf.contains("oid")) { int begin = sbf.indexOf("oid"); returnOid = (sbf.substring(begin + 5, begin + 41)); } } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } return returnOid; }
From source file:com.evolveum.midpoint.model.impl.bulkmodify.PostXML.java
/** * This method takes// ww w. j a v a2 s . com * * @param idmUserName * @return user object's oid if the given username exists. Empty String if the user does not exist. * @throws Exception * * This method */ public String searchByNamePostMethod(String idmUserName) throws Exception { String returnOid = ""; // Get target URL String strURL = "http://localhost:8080/midpoint/ws/rest/users/search"; // Prepare HTTP post PostMethod post = new PostMethod(strURL); //AUTHENTICATION String userPass = this.getUsername() + ":" + this.getPassword(); String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8")); post.addRequestHeader("Authorization", basicAuth); //construct searching string. place "name" attribute into <values> tags. String sendingXml = XML_TEMPLATE_SEARCH_IGNORECASE; sendingXml = sendingXml.replace("<value></value>", "<value>" + idmUserName + "</value>"); RequestEntity userSearchEntity = new StringRequestEntity(sendingXml, "application/xml", "UTF-8"); post.setRequestEntity(userSearchEntity); // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try { int result = httpclient.executeMethod(post); // Display status code //System.out.println("Response status code: " + result); // Display response //System.out.println("Response body: "); // System.out.println(post.getResponseBodyAsString()); String sbf = new String(post.getResponseBodyAsString()); //System.out.println(sbf); //find oid if (sbf.contains("oid")) { int begin = sbf.indexOf("oid"); returnOid = (sbf.substring(begin + 5, begin + 41)); } } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } return returnOid; }
From source file:edu.unc.lib.dl.admin.controller.IngestController.java
@RequestMapping(value = "ingest/{pid}", method = RequestMethod.POST) public @ResponseBody Map<String, ? extends Object> ingestPackageController(@PathVariable("pid") String pid, @RequestParam("type") String type, @RequestParam(value = "name", required = false) String name, @RequestParam("file") MultipartFile ingestFile, HttpServletRequest request, HttpServletResponse response) {/*from w w w . j a v a 2 s .c o m*/ String destinationUrl = swordUrl + "collection/" + pid; HttpClient client = HttpClientUtil.getAuthenticatedClient(destinationUrl, swordUsername, swordPassword); client.getParams().setAuthenticationPreemptive(true); PostMethod method = new PostMethod(destinationUrl); // Set SWORD related headers for performing ingest method.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString()); method.addRequestHeader("Packaging", type); method.addRequestHeader("On-Behalf-Of", GroupsThreadStore.getUsername()); method.addRequestHeader("Content-Type", ingestFile.getContentType()); method.addRequestHeader("Content-Length", Long.toString(ingestFile.getSize())); method.addRequestHeader("mail", request.getHeader("mail")); method.addRequestHeader("Content-Disposition", "attachment; filename=" + ingestFile.getOriginalFilename()); if (name != null && name.trim().length() > 0) method.addRequestHeader("Slug", name); // Setup the json response Map<String, Object> result = new HashMap<String, Object>(); result.put("action", "ingest"); result.put("destination", pid); try { method.setRequestEntity( new InputStreamRequestEntity(ingestFile.getInputStream(), ingestFile.getSize())); client.executeMethod(method); response.setStatus(method.getStatusCode()); // Object successfully "create", or at least queued if (method.getStatusCode() == 201) { Header location = method.getResponseHeader("Location"); String newPid = location.getValue(); newPid = newPid.substring(newPid.lastIndexOf('/')); result.put("pid", newPid); } else if (method.getStatusCode() == 401) { // Unauthorized result.put("error", "Not authorized to ingest to container " + pid); } else if (method.getStatusCode() == 400 || method.getStatusCode() >= 500) { // Server error, report it to the client result.put("error", "A server error occurred while attempting to ingest \"" + ingestFile.getName() + "\" to " + pid); // Inspect the SWORD response, extracting the stacktrace InputStream entryPart = method.getResponseBodyAsStream(); Abdera abdera = new Abdera(); Parser parser = abdera.getParser(); Document<Entry> entryDoc = parser.parse(entryPart); Object rootEntry = entryDoc.getRoot(); String stackTrace; if (rootEntry instanceof FOMExtensibleElement) { stackTrace = ((org.apache.abdera.parser.stax.FOMExtensibleElement) entryDoc.getRoot()) .getExtension(SWORD_VERBOSE_DESCRIPTION).getText(); result.put("errorStack", stackTrace); } else { stackTrace = ((Entry) rootEntry).getExtension(SWORD_VERBOSE_DESCRIPTION).getText(); result.put("errorStack", stackTrace); } log.warn("Failed to upload ingest package file " + ingestFile.getName() + " from user " + GroupsThreadStore.getUsername(), stackTrace); } return result; } catch (Exception e) { log.warn("Encountered an unexpected error while ingesting package " + ingestFile.getName() + " from user " + GroupsThreadStore.getUsername(), e); result.put("error", "A server error occurred while attempting to ingest \"" + ingestFile.getName() + "\" to " + pid); return result; } finally { method.releaseConnection(); try { ingestFile.getInputStream().close(); } catch (IOException e) { log.warn("Failed to close ingest package file", e); } } }
From source file:cuanto.api.CuantoConnector.java
/** * Adds result files to a TestRun on the Cuanto server. This adds test result files to the specified TestRun. A * test result file is not an arbitrary file, but rather it needs to be a file that is in the correct result file * format for the Cuanto project type. For instance, if the Cuanto project is a JUnit project, then it needs to be * a JUnit result file./* w w w . j a v a 2 s . co m*/ * @param files Test Result files to add. * @param testRun The TestRun for adding results. * @throws FileNotFoundException If any of the files are not found. */ public void importTestFiles(List<File> files, TestRun testRun) throws FileNotFoundException { String fullUri = cuantoUrl + "/testRun/submitFile"; PostMethod post = (PostMethod) getHttpMethod(HTTP_POST, fullUri); if (testRun.id == null) { addTestRun(testRun); } post.addRequestHeader("Cuanto-TestRun-Id", testRun.id.toString()); List<FilePart> parts = new ArrayList<FilePart>(); for (File file : files) { parts.add(new FilePart(file.getName(), file)); } Part[] fileParts = parts.toArray(new Part[] {}); post.setRequestEntity(new MultipartRequestEntity(fileParts, post.getParams())); int responseCode; String responseText; try { HttpClient hclient = getHttpClient(); responseCode = hclient.executeMethod(post); responseText = getResponseBodyAsString(post); } catch (IOException e) { throw new RuntimeException(e); } finally { post.releaseConnection(); } if (responseCode != HttpStatus.SC_OK) { throw new RuntimeException("HTTP Response code " + responseCode + ": " + responseText); } }
From source file:eu.learnpad.core.impl.cw.XwikiCoreFacadeRestResource.java
@Override public Entities analyseText(String modelSetId, String contextArtifactId, String userId, String title, String text) throws LpRestException { HttpClient httpClient = this.getClient(); String uri = String.format("%s/learnpad/cw/corefacade/semantic/%s/analysetext", DefaultRestResource.REST_URI, modelSetId); PostMethod postMethod = new PostMethod(uri); postMethod.addRequestHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML); NameValuePair[] queryString = new NameValuePair[4]; queryString[0] = new NameValuePair("modelsetid", modelSetId); queryString[1] = new NameValuePair("contextArtifactId", contextArtifactId); queryString[2] = new NameValuePair("userid", userId); queryString[3] = new NameValuePair("title", title); postMethod.setQueryString(queryString); RequestEntity requestEntity;//from w w w . j a v a 2 s. c o m InputStream entitiesAsStream = null; try { requestEntity = new StringRequestEntity(text, MediaType.APPLICATION_XML, "UTF-8"); postMethod.setRequestEntity(requestEntity); httpClient.executeMethod(postMethod); entitiesAsStream = postMethod.getResponseBodyAsStream(); } catch (IOException e) { throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause()); } Entities entities = null; try { JAXBContext jc = JAXBContext.newInstance(Entities.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); entities = (Entities) unmarshaller.unmarshal(entitiesAsStream); } catch (JAXBException e) { throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause()); } return entities; }
From source file:com.cloud.baremetal.networkservice.SecurityGroupHttpClient.java
public SecurityGroupRuleAnswer call(String agentIp, SecurityGroupRulesCmd cmd) { PostMethod post = new PostMethod(String.format("http://%s:%s", agentIp, getPort())); try {//from w ww .j a v a 2s . c om SecurityGroupVmRuleSet rset = new SecurityGroupVmRuleSet(); rset.getEgressRules().addAll(generateRules(cmd.getEgressRuleSet())); rset.getIngressRules().addAll(generateRules(cmd.getIngressRuleSet())); rset.setVmName(cmd.getVmName()); rset.setVmIp(cmd.getGuestIp()); rset.setVmMac(cmd.getGuestMac()); rset.setVmId(cmd.getVmId()); rset.setSignature(cmd.getSignature()); rset.setSequenceNumber(cmd.getSeqNum()); Marshaller marshaller = context.createMarshaller(); StringWriter writer = new StringWriter(); marshaller.marshal(rset, writer); String xmlContents = writer.toString(); logger.debug(xmlContents); post.addRequestHeader("command", "set_rules"); StringRequestEntity entity = new StringRequestEntity(xmlContents); post.setRequestEntity(entity); if (httpClient.executeMethod(post) != 200) { return new SecurityGroupRuleAnswer(cmd, false, post.getResponseBodyAsString()); } else { return new SecurityGroupRuleAnswer(cmd); } } catch (Exception e) { return new SecurityGroupRuleAnswer(cmd, false, e.getMessage()); } finally { if (post != null) { post.releaseConnection(); } } }
From source file:com.github.maven.plugin.client.impl.GithubClientImpl.java
public void upload(String artifactName, File file, String description, String repositoryUrl) { assertNotNull(artifactName, "artifactName"); assertNotNull(file, "file"); assertNotNull(repositoryUrl, "repositoryUrl"); assertStartsWith(repositoryUrl, GITHUB_REPOSITORY_URL_PREFIX, "repositoryUrl"); PostMethod githubPost = new PostMethod(toRepositoryDownloadUrl(repositoryUrl)); githubPost.setRequestBody(new NameValuePair[] { new NameValuePair("login", login), new NameValuePair("token", token), new NameValuePair("file_name", artifactName), new NameValuePair("file_size", String.valueOf(file.length())), new NameValuePair("description", description == null ? "" : description) }); try {//from w w w . j a v a2 s . com int response = httpClient.executeMethod(githubPost); if (response == HttpStatus.SC_OK) { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readValue(githubPost.getResponseBodyAsString(), JsonNode.class); PostMethod s3Post = new PostMethod(GITHUB_S3_URL); Part[] parts = { new StringPart("Filename", artifactName), new StringPart("policy", node.path("policy").getTextValue()), new StringPart("success_action_status", "201"), new StringPart("key", node.path("path").getTextValue()), new StringPart("AWSAccessKeyId", node.path("accesskeyid").getTextValue()), new StringPart("Content-Type", node.path("mime_type").getTextValue()), new StringPart("signature", node.path("signature").getTextValue()), new StringPart("acl", node.path("acl").getTextValue()), new FilePart("file", file) }; MultipartRequestEntity partEntity = new MultipartRequestEntity(parts, s3Post.getParams()); s3Post.setRequestEntity(partEntity); int s3Response = httpClient.executeMethod(s3Post); if (s3Response != HttpStatus.SC_CREATED) { throw new GithubException( "Cannot upload " + file.getName() + " to repository " + repositoryUrl); } s3Post.releaseConnection(); } else if (response == HttpStatus.SC_NOT_FOUND) { throw new GithubRepositoryNotFoundException("Cannot found repository " + repositoryUrl); } else if (response == HttpStatus.SC_UNPROCESSABLE_ENTITY) { throw new GithubArtifactAlreadyExistException( "File " + artifactName + " already exist in " + repositoryUrl + " repository"); } else { throw new GithubException("Error " + HttpStatus.getStatusText(response)); } } catch (IOException e) { throw new GithubException(e); } githubPost.releaseConnection(); }