List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity()
From source file:org.fedoraproject.eclipse.packager.bodhi.api.BodhiClient.java
@Override public BodhiUpdateResponse createNewUpdate(String[] builds, String release, String type, String request, String bugs, String notes, String csrfToken, boolean suggestReboot, boolean enableKarmaAutomatism, int stableKarmaThreshold, int unstableKarmaThreshold, boolean closeBugsWhenStable) throws BodhiClientException { try {/* ww w. j a va 2 s .c o m*/ HttpPost post = new HttpPost(getPushUpdateUrl()); post.addHeader(ACCEPT_HTTP_HEADER_NAME, MIME_JSON); StringBuffer buildsNVR = new StringBuffer(); for (int i = 0; i < (builds.length - 1); i++) { buildsNVR.append(builds[i]); buildsNVR.append(BUILDS_DELIMITER); } buildsNVR.append(builds[(builds.length - 1)]); String buildsParamValue = buildsNVR.toString(); // Construct the multipart POST request body. MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(BUILDS_PARAM_NAME, new StringBody(buildsParamValue)); reqEntity.addPart(TYPE_PARAM_NAME, new StringBody(type)); reqEntity.addPart(REQUEST_PARAM_NAME, new StringBody(request)); reqEntity.addPart(BUGS_PARAM_NAME, new StringBody(bugs)); reqEntity.addPart(CSRF_PARAM_NAME, new StringBody(csrfToken)); reqEntity.addPart(AUTOKARMA_PARAM_NAME, new StringBody(String.valueOf(enableKarmaAutomatism))); reqEntity.addPart(NOTES_PARAM_NAME, new StringBody(notes)); reqEntity.addPart(SUGGEST_REBOOT, new StringBody(String.valueOf(suggestReboot))); reqEntity.addPart(STABLE_KARMA, new StringBody(String.valueOf(stableKarmaThreshold))); reqEntity.addPart(UNSTABLE_KARMA, new StringBody(String.valueOf(unstableKarmaThreshold))); reqEntity.addPart(CLOSE_BUGS_WHEN_STABLE, new StringBody(String.valueOf(closeBugsWhenStable))); post.setEntity(reqEntity); HttpResponse response = httpclient.execute(post); HttpEntity resEntity = response.getEntity(); int returnCode = response.getStatusLine().getStatusCode(); if (returnCode != HttpURLConnection.HTTP_OK) { throw new BodhiClientException(NLS.bind("{0} {1}", response.getStatusLine().getStatusCode(), //$NON-NLS-1$ response.getStatusLine().getReasonPhrase()), response); } else { String rawJsonString = ""; //$NON-NLS-1$ if (resEntity != null) { try { rawJsonString = parseResponse(resEntity); } catch (IOException e) { // ignore } EntityUtils.consume(resEntity); // clean up resources } // log JSON string if in debug mode if (PackagerPlugin.inDebugMode()) { FedoraPackagerLogger logger = FedoraPackagerLogger.getInstance(); logger.logInfo(NLS.bind(BodhiText.BodhiClient_rawJsonStringMsg, rawJsonString)); } // deserialize the result from the JSON response GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); BodhiUpdateResponse result = gson.fromJson(rawJsonString, BodhiUpdateResponse.class); return result; } } catch (IOException e) { throw new BodhiClientException(e.getMessage(), e); } }
From source file:org.openurp.thesis.service.impl.CnkiThesisCheckServiceImpl.java
/** * //from www . jav a 2 s. c o m * * @param author * @param article * @param file * @return * @throws Exception * @see http://pmlc.cnki.net/school/SwfUpload/handlers.js#uploadSuccess */ public boolean upload(String author, String article, File file) { Charset utf8 = Charset.forName("UTF-8"); MultipartEntity reqEntity = new MultipartEntity(); String content = null; try { reqEntity.addPart("JJ", new StringBody("", utf8)); reqEntity.addPart("DW", new StringBody("", utf8)); reqEntity.addPart("FL", new StringBody("", utf8)); reqEntity.addPart("PM", new StringBody(article, utf8)); reqEntity.addPart("ZZ", new StringBody(author, utf8)); reqEntity.addPart("FD", new StringBody(foldId, utf8)); reqEntity.addPart("ASPSESSID", new StringBody(sessionId, utf8)); reqEntity.addPart("Filedata", new FileBody(file)); HttpPost httpost = new HttpPost(uploadUrl); httpost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpost); HttpEntity entity = response.getEntity(); content = EntityUtils.toString(entity); EntityUtils.consume(entity); } catch (Exception e) { throw new UnhandledException(e); } logger.debug("upload " + file.getName() + " response is " + content); /* ?200??handlers.jsuploadSuccess */ return StringUtils.trim(content).equals("200"); }
From source file:org.fedoraproject.eclipse.packager.api.UploadSourceCommand.java
/** * Check if upload file has already been uploaded. Do nothing, if file is * missing.//from w w w . j ava 2 s .co m * * @throws UploadFailedException * If something went wrong sending/receiving the request to/from * the lookaside cache. * @throws FileAvailableInLookasideCacheException * If the upload candidate file is already present in the * lookaside cache. */ private void checkSourceAvailable() throws FileAvailableInLookasideCacheException, UploadFailedException { HttpClient client = getClient(); try { String uploadURI = null; uploadURI = this.projectRoot.getLookAsideCache().getUploadUrl().toString(); assert uploadURI != null; if (fedoraSslEnabled) { // user requested Fedora SSL enabled client try { client = fedoraSslEnable(client); } catch (GeneralSecurityException e) { throw new UploadFailedException(e.getMessage(), e); } } else if (trustAllSSLEnabled) { // use accept all SSL enabled client try { client = trustAllSslEnable(client); } catch (GeneralSecurityException e) { throw new UploadFailedException(e.getMessage(), e); } } HttpPost post = new HttpPost(uploadURI); // provide hint which URL is going to be used FedoraPackagerLogger logger = FedoraPackagerLogger.getInstance(); logger.logDebug(NLS.bind(FedoraPackagerText.UploadSourceCommand_usingUploadURLMsg, uploadURI)); // Construct the multipart POST request body. MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(FILENAME_PARAM_NAME, new StringBody(fileToUpload.getName())); reqEntity.addPart(PACKAGENAME_PARAM_NAME, new StringBody(projectRoot.getSpecfileModel().getName())); reqEntity.addPart(CHECKSUM_PARAM_NAME, new StringBody(SourcesFile.calculateChecksum(fileToUpload))); post.setEntity(reqEntity); HttpResponse response = client.execute(post); HttpEntity resEntity = response.getEntity(); int returnCode = response.getStatusLine().getStatusCode(); if (returnCode != HttpURLConnection.HTTP_OK) { throw new UploadFailedException(response.getStatusLine().getReasonPhrase(), response); } else { String resString = ""; //$NON-NLS-1$ if (resEntity != null) { try { resString = parseResponse(resEntity); } catch (IOException e) { // ignore } EntityUtils.consume(resEntity); // clean up resources } // If this file has already been uploaded bail out if (resString.toLowerCase().equals(RESOURCE_AVAILABLE)) { throw new FileAvailableInLookasideCacheException(fileToUpload.getName()); } else if (resString.toLowerCase().equals(RESOURCE_MISSING)) { // check passed return; } else { // something is fishy throw new UploadFailedException(FedoraPackagerText.somethingUnexpectedHappenedError); } } } catch (IOException e) { throw new UploadFailedException(e.getMessage(), e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources client.getConnectionManager().shutdown(); } }
From source file:bluej.collect.DataCollectorImpl.java
public static void packageOpened(Package pkg) { final ProjectDetails proj = new ProjectDetails(pkg.getProject()); final MultipartEntity mpe = new MultipartEntity(); final Map<FileKey, List<String>> versions = new HashMap<FileKey, List<String>>(); for (ClassTarget ct : pkg.getClassTargets()) { String relative = CollectUtility.toPath(proj, ct.getSourceFile()); mpe.addPart("project[source_files][][name]", CollectUtility.toBody(relative)); String anonymisedContent = CollectUtility.readFileAndAnonymise(proj, ct.getSourceFile()); if (anonymisedContent != null) { mpe.addPart("source_histories[][source_history_type]", CollectUtility.toBody("complete")); mpe.addPart("source_histories[][name]", CollectUtility.toBody(relative)); mpe.addPart("source_histories[][content]", CollectUtility.toBody(anonymisedContent)); versions.put(new FileKey(proj, relative), Arrays.asList(Utility.splitLines(anonymisedContent))); }//w w w . jav a 2 s . c o m } submitEvent(pkg.getProject(), pkg, EventName.PACKAGE_OPENING, new Event() { @Override public void success(Map<FileKey, List<String>> fileVersions) { fileVersions.putAll(versions); } @Override public MultipartEntity makeData(int sequenceNum, Map<FileKey, List<String>> fileVersions) { return mpe; } }); }
From source file:com.cianmcgovern.android.ShopAndShare.Share.java
/** * Uploads the text file specified by filename * /*w ww . ja v a 2 s .c o m*/ * @param instance * The results instance to use * @param location * The location as specified by the user * @param store * The store as specified by the user * @return Response message from server * @throws ClientProtocolException * @throws IOException */ private String upload(Results instance, String location, String store) throws ClientProtocolException, IOException { Log.v(Constants.LOG_TAG, "Inside upload"); HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); String filename = Results.getInstance().toFile(); HttpPost httpPost = new HttpPost(Constants.FULL_URL); File file = new File(filename); MultipartEntity entity = new MultipartEntity(); ContentBody cb = new FileBody(file, "plain/text"); entity.addPart("inputfile", cb); ContentBody cbLocation = new StringBody(location); entity.addPart("location", cbLocation); ContentBody cbStore = new StringBody(store); entity.addPart("store", cbStore); httpPost.setEntity(entity); Log.v(Constants.LOG_TAG, "Sending post"); HttpResponse response = httpClient.execute(httpPost); HttpEntity resEntity = response.getEntity(); String message = EntityUtils.toString(resEntity); Log.v(Constants.LOG_TAG, "Response from upload is: " + message); resEntity.consumeContent(); httpClient.getConnectionManager().shutdown(); file.delete(); return message; }
From source file:org.opencastproject.loadtest.impl.IngestJob.java
/** * Use the TrustedHttpClient from matterhorn to ingest the mediapackage. * // w w w. j av a 2s . c om * @param workingDirectory * The path to the working directory for the LoadTesting. * @param mediaPackageLocation * The location of the mediapackage we want to ingest. */ private void ingestMediaPackageWithJava(String workingDirectory, String mediaPackageLocation, String workflowID) { logger.info("Ingesting recording with HttpTrustedClient: {}", id); try { URL url = new URL(loadTest.getCoreAddress() + "/ingest/addZippedMediaPackage"); File fileDesc = new File(mediaPackageLocation); // Set the file as the body of the request MultipartEntity entities = new MultipartEntity(); // Check to see if the properties have an alternate workflow definition attached String workflowInstance = id; try { entities.addPart("workflowDefinitionId", new StringBody(workflowID, Charset.forName("UTF-8"))); entities.addPart("workflowInstanceId", new StringBody(workflowInstance, Charset.forName("UTF-8"))); entities.addPart(fileDesc.getName(), new InputStreamBody(new FileInputStream(fileDesc), fileDesc.getName())); } catch (FileNotFoundException ex) { logger.error("Could not find zipped mediapackage " + fileDesc.getAbsolutePath()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("This system does not support UTF-8", e); } logger.debug("Ingest URL is " + url.toString()); HttpPost postMethod = new HttpPost(url.toString()); postMethod.setEntity(entities); // Send the file HttpResponse response = null; int retValue = -1; try { logger.debug( "Sending the file " + fileDesc.getAbsolutePath() + " with a size of " + fileDesc.length()); response = client.execute(postMethod); } catch (TrustedHttpClientException e) { logger.error("Unable to ingest recording {}, message reads: {}.", id, e.getMessage()); } catch (NullPointerException e) { logger.error("Unable to ingest recording {}, null pointer exception!", id); } finally { if (response != null) { retValue = response.getStatusLine().getStatusCode(); client.close(response); } else { retValue = -1; } } if (retValue == HttpURLConnection.HTTP_OK) { logger.info(id + " successfully ingested."); } else { logger.info(id + " ingest failed with return code " + retValue + " and status line " + response.getStatusLine().toString()); } } catch (MalformedURLException e) { logger.error("Malformed URL for ingest target \"" + loadTest.getCoreAddress() + "/ingest/addZippedMediaPackage\""); } }
From source file:org.fcrepo.integration.api.FedoraDatastreamsIT.java
License:asdf
@Test public void testRetrieveMultipartDatastreams() throws Exception { final HttpPost objMethod = postObjMethod("FedoraDatastreamsTest9"); assertEquals(201, getStatus(objMethod)); final HttpPost post = new HttpPost(serverAddress + "objects/FedoraDatastreamsTest9/datastreams/"); final MultipartEntity multiPartEntity = new MultipartEntity(); multiPartEntity.addPart("ds1", new StringBody("asdfg")); multiPartEntity.addPart("ds2", new StringBody("qwerty")); post.setEntity(multiPartEntity);/*from w ww . j a v a2 s. c o m*/ final HttpResponse postResponse = client.execute(post); assertEquals(201, postResponse.getStatusLine().getStatusCode()); // TODO: we should actually evaluate the multipart response for the // things we're expecting final HttpGet getDSesMethod = new HttpGet( serverAddress + "objects/FedoraDatastreamsTest9/datastreams/__content__"); final HttpResponse response = client.execute(getDSesMethod); assertEquals(200, response.getStatusLine().getStatusCode()); final String content = EntityUtils.toString(response.getEntity()); assertTrue("Didn't find the first datastream!", compile("asdfg", DOTALL).matcher(content).find()); assertTrue("Didn't find the second datastream!", compile("qwerty", DOTALL).matcher(content).find()); }
From source file:org.deviceconnect.android.profile.restful.test.NormalFileDescriptorProfileTestCase.java
/** * ????.//from w w w.j av a2s. c om * <pre> * ?HTTP * Method: PUT * Path: /file_descriptor/write?deviceid=xxxx&mediaid=xxxx&position=xxx * Entity: "test" * </pre> * <pre> * ?? * result?0??????? * </pre> */ public void testWrite002() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/" + FileDescriptorProfileConstants.PROFILE_NAME); builder.append("/" + FileDescriptorProfileConstants.ATTRIBUTE_WRITE); builder.append("?"); builder.append(DConnectProfileConstants.PARAM_DEVICE_ID + "=" + getDeviceId()); builder.append("&"); builder.append(FileDescriptorProfileConstants.PARAM_PATH + "=test.txt"); builder.append("&"); builder.append(FileDescriptorProfileConstants.PARAM_POSITION + "=0"); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN + "=" + getAccessToken()); try { MultipartEntity entity = new MultipartEntity(); entity.addPart("media", new StringBody("test")); HttpPut request = new HttpPut(builder.toString()); request.addHeader("Content-Disposition", "form-data; name=\"media\"; filename=\"test.txt\""); request.setEntity(entity); JSONObject root = sendRequest(request); Assert.assertNotNull("root is null.", root); assertResultOK(root); } catch (JSONException e) { fail("Exception in JSONObject." + e.getMessage()); } catch (UnsupportedEncodingException e) { fail("Exception in StringBody." + e.getMessage()); } }
From source file:org.andrico.andrico.facebook.FBBase.java
private MultipartEntity makeMultipartEntityFromParameters(FBMethod method, ByteArrayBody.WriteToProgressHandler runnable) throws UnsupportedEncodingException { MultipartEntity multipartEntity = new MultipartEntity(); for (String key : method.mParameters.keySet()) { multipartEntity.addPart(key, new StringBody(method.mParameters.get(key))); }//from w w w .j av a2 s . c o m multipartEntity.addPart("data", new ByteArrayBody(method.mData, method.mDataFilename, runnable)); return multipartEntity; }