List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:com.borhan.client.BorhanClientBase.java
private PostMethod addParams(PostMethod method, BorhanParams kparams) throws UnsupportedEncodingException { String content = kparams.toString(); String contentType = "application/json"; StringRequestEntity requestEntity = new StringRequestEntity(content, contentType, null); method.setRequestEntity(requestEntity); return method; }
From source file:edu.ku.brc.specify.plugins.ipadexporter.iPadRepositoryHelper.java
/** * @param targetFile/*w w w . j a va 2 s . c om*/ * @param fileName * @param dirName * @return */ public synchronized boolean sendFile(final File targetFile, final String fileName, final String dirName) { String targetURL = getWriteURL(); PostMethod filePost = new PostMethod(targetURL); try { sha1Hash = null; sha1Hash = calculateHash(targetFile); //System.out.println("Uploading " + targetFile.getName() + " to " + targetURL+ "Src Exists: "+targetFile.exists()); //System.out.println("Hash [" + sha1Hash + "]"); Part[] parts = { new FilePart(targetFile.getName(), targetFile), new StringPart("store", fileName), new StringPart("dir", dirName), new StringPart("hash", sha1Hash == null ? "" : sha1Hash), new StringPart("action", "upload"), }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(15000); int status = client.executeMethod(filePost); //System.out.println(filePost.getResponseBodyAsString()); if (status == HttpStatus.SC_OK) { System.err.println("HTTP Status: OK"); return true; } else { System.err.println("HTTP Status: " + status); System.err.println(filePost.getResponseBodyAsString()); } } catch (java.net.UnknownHostException uex) { networkConnError = true; } catch (Exception ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { filePost.releaseConnection(); } return false; }
From source file:it.openprj.jValidator.services.ServiceScheduledJob.java
@Override protected synchronized void executeInternal(JobExecutionContext arg0) throws JobExecutionException { long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId"); JobsEntity jobEntity = jobsDao.find(jobId); if (!jobEntity.isWorking()) { if (jobsDao.setWorkStatus(jobId, true)) { try { long eventTriggerId = arg0.getJobDetail().getJobDataMap().getString("eventTriggerId") == null ? -1l//from w w w . ja v a 2 s . com : Long.parseLong(arg0.getJobDetail().getJobDataMap().getString("eventTriggerId")); if (eventTriggerId > 0) { EventTriggerEntity entity = eventTriggerDao.findEventTriggerById(eventTriggerId); String className = entity.getName(); try { String sourceCode = entity.getCode(); EventTrigger eventTrigger; String response; eventTrigger = (EventTrigger) CommonUtils.getClassInstance(className, "it.openprj.jValidator.eventtrigger.EventTrigger", EventTrigger.class, sourceCode); assert eventTrigger != null; response = eventTrigger.trigger(); log.info("Response From EventTrigger(" + className + ") :" + response); } catch (Exception e) { e.printStackTrace(); log.error("EventTrigger(" + className + ") :" + e.getMessage(), e); logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + e.getMessage()); } catch (NoClassDefFoundError err) { log.error("EventTrigger(" + className + ") :" + err.getMessage(), err); logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + err.getMessage()); } return; } int day = arg0.getJobDetail().getJobDataMap().getString("day") == null ? -1 : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("day")); int month = arg0.getJobDetail().getJobDataMap().getString("month") == null ? -1 : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("month")); if ((day > 0 && day != Calendar.getInstance().get(Calendar.DAY_OF_MONTH)) || (month > 0 && month != (Calendar.getInstance().get(Calendar.MONTH) + 1))) { return; } StandardFileSystemManager fsManager = new StandardFileSystemManager(); boolean isDataStream = true; try { fsManager.init(); long schemaId = arg0.getJobDetail().getJobDataMap().getLong("schemaId"); long schedulerId = arg0.getJobDetail().getJobDataMap().getLong("schedulerId"); //long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId"); long connectionId = arg0.getJobDetail().getJobDataMap().getLong("connectionId"); String datastream = ""; int idSchemaType = schemasDao.find(schemaId).getIdSchemaType(); TasksEntity taskEntity = tasksDao.find(schedulerId); //JobsEntity jobEntity = jobsDao.find(jobId); if (taskEntity.getIsOneShoot()) { jobEntity.setIsActive(0); jobsDao.update(jobEntity); } if (idSchemaType == SchemaType.GENERATION) { StreamGenerationUtils sgu = new StreamGenerationUtils(); datastream = sgu.getStream(schemaId); log.debug("Content stream: " + schemaId); if (datastream.trim().length() > 0) { log.debug("Datastream to validate: " + datastream); DatastreamsInput datastreamsInput = new DatastreamsInput(); String result = datastreamsInput.datastreamsInput(datastream, schemaId, null); log.debug("Validation result: " + result); } else { isDataStream = false; log.debug("No datastream create"); } } if (connectionId != 0) { int serviceId = Integer .parseInt(arg0.getJobDetail().getJobDataMap().getString("serviceId")); String hostName = arg0.getJobDetail().getJobDataMap().getString("ftpServerIp"); String port = arg0.getJobDetail().getJobDataMap().getString("port"); String userName = arg0.getJobDetail().getJobDataMap().getString("userName"); String password = arg0.getJobDetail().getJobDataMap().getString("password"); String inputDirectory = arg0.getJobDetail().getJobDataMap().getString("inputDirectory"); String fileName = arg0.getJobDetail().getJobDataMap().getString("fileName"); ConnectionsEntity conn; conn = connectionsDao.find(connectionId); if (inputDirectory == null || inputDirectory.trim().length() == 0) { inputDirectory = fileName; } else if (!(conn.getIdConnType() == GenericType.uploadTypeConn && serviceId == Servers.HTTP.getDbCode())) { inputDirectory = inputDirectory + "/" + fileName; } log.info("(jobId:" + jobEntity.getName() + ") - Trying to Server polling at server [" + hostName + ":" + port + "] with user[" + userName + "]."); String url = ""; if (serviceId == Servers.SAMBA.getDbCode()) { if (!fsManager.hasProvider("smb")) { fsManager.addProvider("smb", new SmbFileProvider()); } url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory; } else if (serviceId == Servers.HTTP.getDbCode()) { if (!fsManager.hasProvider("http")) { fsManager.addProvider("http", new HttpFileProvider()); } url = "http://" + hostName + ":" + port + "/" + inputDirectory; } else if (serviceId == Servers.FTP.getDbCode()) { if (!fsManager.hasProvider("ftp")) { fsManager.addProvider("ftp", new FtpFileProvider()); } url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory; } log.info("url:" + url); final FileObject fileObject = fsManager.resolveFile(url); if (conn.getIdConnType() == GenericType.DownloadTypeConn) { if (conn.getFileDateTime() != null && conn.getFileDateTime().getTime() == fileObject .getContent().getLastModifiedTime()) { log.info("There is no New or Updated '" + fileName + "' file on server to validate. Returning ..."); return; } else { log.info("There is New or Updated '" + fileName + "' file on server to validate. Validating ..."); ConnectionsEntity connection = connectionsDao.find(connectionId); connection.setFileDateTime( new Date(fileObject.getContent().getLastModifiedTime())); ApplicationContext ctx = AppContext.getApplicationContext(); ConnectionsDao connDao = (ctx.getBean(ConnectionsDao.class)); if (connDao != null) { connDao.update(connection); } Map<String, byte[]> resultMap = new HashMap<String, byte[]>(); byte data[] = new byte[(int) fileObject.getContent().getSize()]; fileObject.getContent().getInputStream().read(data); resultMap.put(fileObject.getName().getBaseName(), data); Set<String> keySet = resultMap.keySet(); Iterator<String> itr = keySet.iterator(); while (itr.hasNext()) { String strFileName = itr.next(); String result = ""; try { Long longSchemaId = schemaId; SchemaEntity schemaEntity = schemasDao.find(longSchemaId); if (schemaEntity == null) { result = "No schema found in database with Id [" + longSchemaId + "]"; log.error(result); logDao.setErrorLogMessage(result); } else { if (strFileName.endsWith(FileExtensionType.ZIP.getAbbreviation())) { // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one ZipInputStream inStream = null; try { inStream = new ZipInputStream( new ByteArrayInputStream(resultMap.get(fileName))); ZipEntry entry; while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) { if (!entry.isDirectory()) { DatastreamsInput datastreamsInput = new DatastreamsInput(); datastreamsInput .setUploadedFileName(entry.getName()); byte[] byteInput = IOUtils.toByteArray(inStream); result += datastreamsInput.datastreamsInput( new String(byteInput), longSchemaId, byteInput); } inStream.closeEntry(); } log.debug(result); } catch (IOException ex) { result = "Error occured during fetch records from ZIP file."; log.error(result); logDao.setErrorLogMessage(result); } finally { if (inStream != null) inStream.close(); } } else { DatastreamsInput datastreamsInput = new DatastreamsInput(); datastreamsInput.setUploadedFileName(strFileName); result = datastreamsInput.datastreamsInput( new String(resultMap.get(strFileName)), longSchemaId, resultMap.get(strFileName)); log.debug(result); } } } catch (Exception ex) { ex.printStackTrace(); result = "Exception occured during process the message for xml file " + strFileName + " Error - " + ex.getMessage(); log.error(result); logDao.setErrorLogMessage(result); } } } } else if (isDataStream && (conn.getIdConnType() == GenericType.uploadTypeConn)) { File uploadFile = File.createTempFile(fileName, ".tmp"); try { BufferedWriter bw = new BufferedWriter(new FileWriter(uploadFile)); bw.write(datastream); bw.flush(); bw.close(); } catch (IOException ioex) { log.error("Datastream file can't be created"); logDao.setErrorLogMessage("Datastream file can't be created"); return; } if (serviceId == Servers.HTTP.getDbCode()) { try { HttpClient httpclient = new HttpClient(); PostMethod method = new PostMethod(url); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); Part[] parts = new Part[] { new FilePart("file", uploadFile.getName(), uploadFile) }; method.setRequestEntity( new MultipartRequestEntity(parts, method.getParams())); method.setDoAuthentication(true); int statusCode = httpclient.executeMethod(method); String responseBody = new String(method.getResponseBody()); if (statusCode != HttpStatus.SC_OK) { throw new HttpException(method.getStatusLine().toString()); } else { System.out.println(responseBody); } method.releaseConnection(); } catch (Exception ex) { log.error("Exception occurred during uploading of file at HTTP Server: " + ex.getMessage()); logDao.setErrorLogMessage( "Exception occurred during uploading of file at HTTP Server: " + ex.getMessage()); } } else { try { FileObject localFileObject = fsManager .resolveFile(uploadFile.getAbsolutePath()); fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF); System.out.println("File uploaded at : " + new Date()); if (uploadFile.exists()) { uploadFile.delete(); } } catch (Exception ex) { log.error( "Exception occurred during uploading of file: " + ex.getMessage()); logDao.setErrorLogMessage( "Exception occurred during uploading of file: " + ex.getMessage()); } } } } } catch (Exception ex) { log.error("Error " + ": " + ex.getMessage()); } finally { fsManager.close(); } } finally { jobsDao.setWorkStatus(jobId, false); } } else { log.error("Can not set " + jobEntity.getName() + "working."); } } else { log.debug("Job " + jobEntity.getName() + " is working."); } }
From source file:eu.learnpad.core.impl.or.XwikiBridgeInterfaceRestResource.java
@Override public void simulationInstanceNotification(String modelSetId, String modelId, String action, String simulationId, SimulationData data) throws LpRestException { // <host>/learnpad/or/bridge/{modelsetid}/{modelid}/simulationinstancenotification?action={started|stopped},simulationid=id String contentType = "application/xml"; HttpClient httpClient = this.getClient(); String uri = String.format("%s/learnpad/or/bridge/%s/%s/simulationinstancenotification", DefaultRestResource.REST_URI, modelSetId, modelId); PostMethod postMethod = new PostMethod(uri); postMethod.addRequestHeader("Content-Type", contentType); NameValuePair[] queryString = new NameValuePair[2]; queryString[0] = new NameValuePair("action", action); queryString[1] = new NameValuePair("simulationid", simulationId); postMethod.setQueryString(queryString); try {//w w w. j ava 2s . c o m Writer simDataWriter = new StringWriter(); JAXBContext jc = JAXBContext.newInstance(SimulationData.class); jc.createMarshaller().marshal(data, simDataWriter); RequestEntity requestEntity = new StringRequestEntity(simDataWriter.toString(), contentType, "UTF-8"); postMethod.setRequestEntity(requestEntity); httpClient.executeMethod(postMethod); } catch (JAXBException | IOException e) { throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause()); } }
From source file:eu.learnpad.core.impl.or.XwikiBridgeInterfaceRestResource.java
private void invokeSimulationTaskNotification(String restOperationName, String modelSetId, String modelId, String artifactId, String simulationId, SimulationData data) throws LpRestException { // <host>/learnpad/or/bridge/{modelsetid}/{modelid}/{restOperationName}?artifactid=aid,simulationid=id String contentType = "application/xml"; HttpClient httpClient = this.getClient(); String uri = String.format("%s/learnpad/or/bridge/%s/%s/%s", DefaultRestResource.REST_URI, modelSetId, modelId, restOperationName); PostMethod postMethod = new PostMethod(uri); postMethod.addRequestHeader("Content-Type", contentType); NameValuePair[] queryString = new NameValuePair[2]; queryString[0] = new NameValuePair("artifactid", artifactId); queryString[1] = new NameValuePair("simulationid", simulationId); postMethod.setQueryString(queryString); try {/* w w w. ja v a 2 s. co m*/ Writer simDataWriter = new StringWriter(); JAXBContext jc = JAXBContext.newInstance(SimulationData.class); jc.createMarshaller().marshal(data, simDataWriter); RequestEntity requestEntity = new StringRequestEntity(simDataWriter.toString(), contentType, "UTF-8"); postMethod.setRequestEntity(requestEntity); httpClient.executeMethod(postMethod); } catch (JAXBException | IOException e) { throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause()); } }
From source file:eu.learnpad.core.impl.or.XwikiBridgeInterfaceRestResource.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/or/bridge/%s/analysetext", DefaultRestResource.REST_URI, modelSetId);/*from w w w. j a va2 s . com*/ 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; 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:cuanto.api.CuantoConnector.java
/** * Gets all TestRuns that include the specified TestProperties. The properties can be a subset of a TestRun's * properties, but all of the specified properties must match for a TestRun to be returned. * * @param testProperties The properties for which to search. This is a Map with property names as the keys and the * property values as the values. * @return All TestRuns that contain the specified properties. A zero-length array is returned if no matching TestRuns * are found./*from w ww . ja v a 2s . com*/ */ public List<TestRun> getTestRunsWithProperties(Map<String, String> testProperties) { PostMethod post = (PostMethod) getHttpMethod(HTTP_POST, getCuantoUrl() + "/api/getTestRunsWithProperties"); try { Map jsonMap = new HashMap(); jsonMap.put("projectKey", getProjectKey()); jsonMap.put("testProperties", JSONObject.fromObject(testProperties)); JSONObject jsonToPost = JSONObject.fromObject(jsonMap); post.setRequestEntity(new StringRequestEntity(jsonToPost.toString(), "application/json", null)); int httpStatus = getHttpClient().executeMethod(post); if (httpStatus == HttpStatus.SC_OK) { JSONObject jsonReturned = JSONObject.fromObject(getResponseBodyAsString(post)); List<TestRun> testRuns = new ArrayList<TestRun>(); if (jsonReturned.has("testRuns")) { JSONArray returnedRuns = jsonReturned.getJSONArray("testRuns"); for (Object run : returnedRuns) { JSONObject jsonRun = (JSONObject) run; testRuns.add(TestRun.fromJSON(jsonRun)); } } else { throw new RuntimeException("JSON response didn't have testRuns node"); } return testRuns; } else { throw new RuntimeException("Getting the TestRun failed with HTTP status code " + httpStatus + ": \n" + getResponseBodyAsString(post)); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException("Unable to parse JSON response: " + e.getMessage(), e); } }
From source file:com.openkm.util.DocConverter.java
/** * Handle remote OpenOffice server conversion *///from w w w.ja v a2 s . c o m public void remoteConvert(String uri, File inputFile, String srcMimeType, File outputFile, String dstMimeType) throws ConversionException { PostMethod post = new PostMethod(uri); try { Part[] parts = { new FilePart(inputFile.getName(), inputFile), new StringPart("src_mime", srcMimeType), new StringPart("dst_mime", dstMimeType), new StringPart("okm_uuid", Repository.getUuid()) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); HttpClient httpclient = new HttpClient(); int rc = httpclient.executeMethod(post); log.info("Response Code: {}", rc); if (rc == HttpStatus.SC_OK) { FileOutputStream fos = new FileOutputStream(outputFile); BufferedInputStream bis = new BufferedInputStream(post.getResponseBodyAsStream()); IOUtils.copy(bis, fos); bis.close(); fos.close(); } else { throw new IOException("Error in conversion: " + rc); } } catch (HttpException e) { throw new ConversionException("HTTP exception", e); } catch (FileNotFoundException e) { throw new ConversionException("File not found exeption", e); } catch (IOException e) { throw new ConversionException("IO exception", e); } finally { post.releaseConnection(); } }
From source file:com.jmeter.alfresco.utils.HttpUtils.java
/** * Document upload.// w w w .j a v a2s . c om * * @param docFileObj the doc file obj * @param authTicket the auth ticket * @param uploadURI the upload uri * @param siteID the site id * @param uploadDir the upload dir * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public String documentUpload(final File docFileObj, final String authTicket, final String uploadURI, final String siteID, final String uploadDir) throws IOException { String uploadResponse = Constants.EMPTY; PostMethod postRequest = null; try { final String uploadURL = getFileUploadURL(uploadURI, authTicket); LOG.info("documentUpload() | Upload URL: " + uploadURL); final HttpClient httpClient = new HttpClient(); postRequest = new PostMethod(uploadURL); final String mimeType = getMimeType(docFileObj); final String docName = docFileObj.getName(); LOG.debug("documentUpload() | Uploading document: " + docName + " , content-type: " + mimeType); final Part[] parts = { new FilePart("filedata", docName, docFileObj, mimeType, null), new StringPart("filename", docName), new StringPart("overwrite", "true"), new StringPart("siteid", siteID), new StringPart("containerid", ConfigReader.getProperty(Constants.CONTAINER_ID)), new StringPart("uploaddirectory", uploadDir) }; postRequest.setRequestEntity(new MultipartRequestEntity(parts, postRequest.getParams())); final int statusCode = httpClient.executeMethod(postRequest); uploadResponse = postRequest.getResponseBodyAsString(); LOG.info("documentUpload() | Upload status: " + statusCode); LOG.debug("documentUpload() | Upload response: " + uploadResponse); } finally { if (postRequest != null) { //releaseConnection http connection postRequest.releaseConnection(); } } return uploadResponse; }
From source file:gr.upatras.ece.nam.fci.panlab.PanlabGWClient.java
/** * It makes a POST towards the gateway//w ww . j a v a 2 s . c o m * @author ctranoris * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27 * @param ptmAlias sets the name of the provider URI, e.g.: uop * @param content sets the name of the content; send in utf8 */ public boolean POSTExecute(String resourceInstance, String ptmAlias, String content) { boolean status = false; System.out.println("content body=" + "\n" + content); HttpClient client = new HttpClient(); String tgwcontent = content; // resource instance is like uop.rubis_db-6 so we need to make it like // this /uop/uop.rubis_db-6 String ptm = ptmAlias; String url = panlabGWAddress + "/" + ptm + "/" + resourceInstance; System.out.println("Request: " + url); // Create a method instance. PostMethod post = new PostMethod(url); post.setRequestHeader("User-Agent", userAgent); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Provide custom retry handler is necessary post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); //HttpMethodParams. RequestEntity requestEntity = null; try { requestEntity = new StringRequestEntity(tgwcontent, "application/x-www-form-urlencoded", "utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } post.setRequestEntity(requestEntity); try { // Execute the method. int statusCode = client.executeMethod(post); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + post.getStatusLine()); } // Deal with the response. // Use caution: ensure correct character encoding and is not binary // data // print the status and response InputStream responseBody = post.getResponseBodyAsStream(); CopyInputStream cis = new CopyInputStream(responseBody); response_stream = cis.getCopy(); System.out.println("Response body=" + "\n" + convertStreamToString(response_stream)); response_stream.reset(); // System.out.println("for address: " + url + " the response is:\n " // + post.getResponseBodyAsString()); status = true; } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); return false; } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); return false; } finally { // Release the connection. post.releaseConnection(); } return status; }