List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity()
From source file:com.parworks.androidlibrary.ar.ARSiteImpl.java
@Override public BaseImage addBaseImage(String filename, InputStream image) { // handleStateSync(mId, State.NEEDS_MORE_BASE_IMAGES, // State.NEEDS_BASE_IMAGE_PROCESSING); // make httputils HttpUtils httpUtils = new HttpUtils(mApiKey, mTime, mSignature); // make query string Map<String, String> params = new HashMap<String, String>(); params.put("site", mId); params.put("filename", filename); // make entity MultipartEntity imageEntity = new MultipartEntity(); InputStreamBody imageInputStreamBody = new InputStreamBody(image, filename); imageEntity.addPart("image", imageInputStreamBody); // do post/*from ww w .j av a2 s .c o m*/ HttpResponse serverResponse = httpUtils .doPost(HttpUtils.PARWORKS_API_BASE_URL + HttpUtils.ADD_BASE_IMAGE_PATH, imageEntity, params); // handle status code HttpUtils.handleStatusCode(serverResponse.getStatusLine().getStatusCode()); // parse response ARResponseHandler responseHandler = new ARResponseHandlerImpl(); AddBaseImageResponse addBaseImageResponse = responseHandler.handleResponse(serverResponse, AddBaseImageResponse.class); // return baseimageinfo if (addBaseImageResponse.getSuccess() == true) { return new BaseImage(addBaseImageResponse.getId()); } else { throw new ARException( "Successfully communicated with the server but failed to add the base image. Perhaps the site does not exist, or there is a problem with the image."); } }
From source file:pl.psnc.synat.wrdz.zmkd.plan.MigrationPlanProcessorBean.java
/** * Creates a new object in ZMD./*from w w w . j a v a2s.com*/ * * @param client * http client instance * @param files * map of the new object's files; keys contain the file names/paths inside the new object's structure * @param fileSequence * map of the new object's file sequence values; keys contain the file names/paths inside the new * object's structure * @param originIdentifier * identifier of the object the new object was migrated from * @param originType * the type of migration performed * @return creation request identifier * @throws IOException * if object upload fails */ private String saveObject(HttpClient client, Map<String, File> files, Map<String, Integer> fileSequence, String originIdentifier, MigrationType originType) throws IOException { DateFormat format = new SimpleDateFormat(ORIGIN_DATE_FORMAT); HttpPost post = new HttpPost(zmkdConfiguration.getZmdObjectUrl()); MultipartEntity entity = new MultipartEntity(); try { entity.addPart(ORIGIN_ID, new StringBody(originIdentifier, ENCODING)); entity.addPart(ORIGIN_TYPE, new StringBody(originType.name(), ENCODING)); entity.addPart(ORIGIN_DATE, new StringBody(format.format(new Date()), ENCODING)); int i = 0; for (Entry<String, File> dataFile : files.entrySet()) { FileBody file = new FileBody(dataFile.getValue()); StringBody path = new StringBody(dataFile.getKey(), ENCODING); entity.addPart(String.format(FILE_SRC, i), file); entity.addPart(String.format(FILE_DEST, i), path); if (fileSequence.containsKey(dataFile.getKey())) { StringBody seq = new StringBody(fileSequence.get(dataFile.getKey()).toString(), ENCODING); entity.addPart(String.format(FILE_SEQ, i), seq); } i++; } } catch (UnsupportedEncodingException e) { throw new WrdzRuntimeException("The encoding " + ENCODING + " is not supported"); } post.setEntity(entity); HttpResponse response = client.execute(post); EntityUtils.consumeQuietly(response.getEntity()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) { String location = response.getFirstHeader("location").getValue(); return location.substring(location.lastIndexOf('/') + 1); } else { throw new IOException("Unexpected response: " + response.getStatusLine()); } }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Sends a {@link MultipartEntity} post with text and image files. * * @param url the url to which to POST to. * @param user the user or <code>null</code>. * @param pwd the password or <code>null</code>. * @param stringsMap the {@link HashMap} containing the key and string pairs to send. * @param filesMap the {@link HashMap} containing the key and image file paths * (jpg, png supported) pairs to send. * @throws Exception if something goes wrong. */// w w w. jav a 2 s .c om public static void sentMultiPartPost(String url, String user, String pwd, HashMap<String, String> stringsMap, HashMap<String, File> filesMap) throws Exception { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(url); if (user != null && pwd != null && user.trim().length() > 0 && pwd.trim().length() > 0) { String ret = getB64Auth(user, pwd); httppost.setHeader("Authorization", ret); } MultipartEntity mpEntity = new MultipartEntity(); Set<Entry<String, String>> stringsEntrySet = stringsMap.entrySet(); for (Entry<String, String> stringEntry : stringsEntrySet) { ContentBody cbProperties = new StringBody(stringEntry.getValue()); mpEntity.addPart(stringEntry.getKey(), cbProperties); } Set<Entry<String, File>> filesEntrySet = filesMap.entrySet(); for (Entry<String, File> filesEntry : filesEntrySet) { String propName = filesEntry.getKey(); File file = filesEntry.getValue(); if (file.exists()) { String ext = file.getName().toLowerCase().endsWith("jpg") ? "jpeg" : "png"; ContentBody cbFile = new FileBody(file, "image/" + ext); mpEntity.addPart(propName, cbFile); } } httppost.setEntity(mpEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { resEntity.consumeContent(); } httpclient.getConnectionManager().shutdown(); }
From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java
public boolean uploadPics(File[] pics, String text, Twitter twitter) { JSONObject jsonresponse = new JSONObject(); final String ids_string = getMediaIds(pics, twitter); if (ids_string == null) { return false; }/*from w w w . ja va 2 s .c om*/ try { AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "POST"; String oauth_signature_method = "HMAC-SHA1"; String uuid_string = UUID.randomUUID().toString(); uuid_string = uuid_string.replaceAll("-", ""); String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here // get the timestamp Calendar tempcal = Calendar.getInstance(); long ts = tempcal.getTimeInMillis();// get current time in milliseconds String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds // the parameter string must be in alphabetical order, "text" parameter added at end String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0"; System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string); String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json"; String twitter_endpoint_host = "api.twitter.com"; String twitter_endpoint_path = "/1.1/statuses/update.json"; String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string); String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret)); String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\""; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpCore/1.1"); HttpProtocolParams.setUseExpectContinue(params, false); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(twitter_endpoint_host, 443); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try { try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); Socket socket = ssf.createSocket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0); conn.bind(socket, params); BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("media_ids", new StringBody(ids_string)); reqEntity.addPart("status", new StringBody(text)); reqEntity.addPart("trim_user", new StringBody("1")); request2.setEntity(reqEntity); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); String responseBody = EntityUtils.toString(response2.getEntity()); System.out.println("response=" + responseBody); // error checking here. Otherwise, status should be updated. jsonresponse = new JSONObject(responseBody); conn.close(); } catch (HttpException he) { System.out.println(he.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage()); } catch (NoSuchAlgorithmException nsae) { System.out.println(nsae.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage()); } catch (KeyManagementException kme) { System.out.println(kme.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage()); } finally { conn.close(); } } catch (JSONException jsone) { jsone.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } catch (Exception e) { } return true; }
From source file:MyZone.Settings.java
public boolean createNewUser(String username, String firstName, String lastName, String gender, String searchable) {//from w w w . j a v a2s. c o m globalProperties = new globalAttributes(); try { if (!(new File(prefix + username).exists())) { boolean success = (new File(prefix + username)).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/audios").exists())) { boolean success = (new File(prefix + username + "/audios")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/videos").exists())) { boolean success = (new File(prefix + username + "/videos")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/photos").exists())) { boolean success = (new File(prefix + username + "/photos")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/zones").exists())) { boolean success = (new File(prefix + username + "/zones")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/zones/All").exists())) { boolean success = (new File(prefix + username + "/zones/All")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/zones/All/wall").exists())) { boolean success = (new File(prefix + username + "/zones/All/wall")).mkdirs(); if (!success) return false; } if (!(new File(prefix + "/CAs").exists())) { boolean success = (new File(prefix + "/CAs")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/cert").exists())) { boolean success = (new File(prefix + username + "/cert")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/friends").exists())) { boolean success = (new File(prefix + username + "/friends")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/keys").exists())) { boolean success = (new File(prefix + username + "/keys")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/thumbnails").exists())) { boolean success = (new File(prefix + username + "/thumbnails")).mkdirs(); if (!success) return false; } File file = new File(prefix + username + "/keys/" + username + ".pub"); boolean pubKeyExists = file.exists(); file = new File(prefix + username + "/keys/" + username + ".pri"); boolean priKeyExists = file.exists(); KeyPairUtil x = new KeyPairUtil(); KeyPair keys = null; if (!pubKeyExists || !priKeyExists) { keys = x.generateKeys(prefix + username + "/keys/", username, globalProperties.keyPairAlgorithm, globalProperties.certificateKeySize); } if (keys != null) keyFound = true; certFound = false; if (CAServerName != null) { File caKeyFile = new File(prefix + "/CAs/CA@" + CAServerName + ".pub"); CAKeyFound = true; if (!caKeyFile.exists()) { CAKeyFound = false; } } else { CAKeyFound = false; } certCorrupted = false; this.username = username; zones.clear(); friends.clear(); mirrors.clear(); originals.clear(); pendingFriendships.clear(); awaitingFriendships.clear(); sentMirroringRequests.clear(); receivedMirroringRequests.clear(); passphrases.clear(); zone z = new zone(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis(), Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis(), "All", 1800, null); zones.add(z); lastSyncTime1 = 0; lastSyncTime2 = 0; save(ALL); HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost("http://joinmyzone.com/upload.php"); FileBody publicKey = new FileBody(new File(prefix + username + "/keys/" + username + ".pub")); StringBody sFirstName = new StringBody(firstName); StringBody sLastName = new StringBody(lastName); StringBody sGender = new StringBody(gender); StringBody sSearchable = new StringBody(searchable); StringBody sEmail = new StringBody(username); StringBody sResend = new StringBody("false"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("firstName", sFirstName); reqEntity.addPart("lastName", sLastName); reqEntity.addPart("gender", sGender); reqEntity.addPart("searchable", sSearchable); reqEntity.addPart("email", sEmail); reqEntity.addPart("re-email", sEmail); reqEntity.addPart("resendCertificate", sResend); reqEntity.addPart("publicKey", publicKey); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } } catch (Exception e) { if (DEBUG) { e.printStackTrace(); } } return true; }
From source file:org.opencastproject.workingfilerepository.remote.WorkingFileRepositoryRemoteImpl.java
/** * {@inheritDoc}/*from ww w .j a va 2s .co m*/ * * @see org.opencastproject.workingfilerepository.api.WorkingFileRepository#put(java.lang.String, java.lang.String, * java.lang.String, java.io.InputStream) */ @Override public URI put(String mediaPackageID, String mediaPackageElementID, String filename, InputStream in) { String url = UrlSupport .concat(new String[] { MEDIAPACKAGE_PATH_PREFIX, mediaPackageID, mediaPackageElementID }); HttpPost post = new HttpPost(url); MultipartEntity entity = new MultipartEntity(); ContentBody body = new InputStreamBody(in, filename); entity.addPart("file", body); post.setEntity(entity); HttpResponse response = getResponse(post); try { if (response != null) { String content = EntityUtils.toString(response.getEntity()); return new URI(content); } } catch (Exception e) { throw new RuntimeException(e); } finally { closeConnection(response); } throw new RuntimeException("Unable to put file"); }
From source file:uk.ac.bbsrc.tgac.miso.core.manager.ERASubmissionManager.java
/** * Submits the given set of Submittables to the ERA submission service endpoint * * @param submissionData of type Set<Submittable<Document>> * @return Document//w ww . j a v a 2 s . com * @throws SubmissionException when an error occurred with the submission process */ public Document submit(Set<Submittable<Document>> submissionData) throws SubmissionException { try { DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); if (submissionEndPoint == null) { throw new SubmissionException( "No submission endpoint configured. Please check your submission.properties file."); } if (submissionData == null || submissionData.size() == 0) { throw new SubmissionException("No submission data set."); } if (accountName == null || dropBox == null || authKey == null) { throw new SubmissionException("An accountName, dropBox and authKey must be supplied!"); } if (centreName == null) { throw new SubmissionException( "No centreName configured. Please check your submission.properties file and specify your Center Name as given by the SRA."); } String curl = "curl -k "; StringBuilder sb = new StringBuilder(); sb.append(curl); String proxyHost = submissionProperties.getProperty("submission.proxyHost"); String proxyUser = submissionProperties.getProperty("submission.proxyUser"); String proxyPass = submissionProperties.getProperty("submission.proxyPass"); if (proxyHost != null && !proxyHost.equals("")) { sb.append("-x ").append(proxyHost); if (proxyUser != null && !proxyUser.equals("")) { sb.append("-U ").append(proxyUser); if (proxyPass != null && !proxyPass.equals("")) { sb.append(":").append(proxyPass); } } } //submit via REST to endpoint try { Map<String, List<Submittable<Document>>> map = new HashMap<String, List<Submittable<Document>>>(); map.put("study", new ArrayList<Submittable<Document>>()); map.put("sample", new ArrayList<Submittable<Document>>()); map.put("experiment", new ArrayList<Submittable<Document>>()); map.put("run", new ArrayList<Submittable<Document>>()); Document submissionXml = docBuilder.newDocument(); String subName = null; String d = df.format(new Date()); submissionProperties.put("submissionDate", d); for (Submittable<Document> s : submissionData) { if (s instanceof Submission) { //s.buildSubmission(); ERASubmissionFactory.generateParentSubmissionXML(submissionXml, (Submission) s, submissionProperties); subName = ((Submission) s).getName(); } else if (s instanceof Study) { map.get("study").add(s); } else if (s instanceof Sample) { map.get("sample").add(s); } else if (s instanceof Experiment) { map.get("experiment").add(s); } else if (s instanceof SequencerPoolPartition) { map.get("run").add(s); } } if (submissionXml != null && subName != null) { String url = getSubmissionEndPoint() + "?auth=ERA%20" + dropBox + "%20" + authKey; HttpClient httpclient = getEvilTrustingTrustManager(new DefaultHttpClient()); HttpPost httppost = new HttpPost(url); MultipartEntity reqEntity = new MultipartEntity(); String submissionXmlFileName = subName + File.separator + subName + "_submission_" + d + ".xml"; File subtmp = new File(submissionStoragePath + submissionXmlFileName); SubmissionUtils.transform(submissionXml, subtmp, true); reqEntity.addPart("SUBMISSION", new FileBody(subtmp)); for (String key : map.keySet()) { List<Submittable<Document>> submittables = map.get(key); String submittableXmlFileName = subName + File.separator + subName + "_" + key.toLowerCase() + "_" + d + ".xml"; File elementTmp = new File(submissionStoragePath + submittableXmlFileName); Document submissionDocument = docBuilder.newDocument(); ERASubmissionFactory.generateSubmissionXML(submissionDocument, submittables, key, submissionProperties); SubmissionUtils.transform(submissionDocument, elementTmp, true); reqEntity.addPart(key.toUpperCase(), new FileBody(elementTmp)); } httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); try { Document submissionReport = docBuilder.newDocument(); SubmissionUtils.transform(resEntity.getContent(), submissionReport); File savedReport = new File( submissionStoragePath + subName + File.separator + "report_" + d + ".xml"); SubmissionUtils.transform(submissionReport, savedReport); return submissionReport; } catch (IOException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } finally { submissionProperties.remove("submissionDate"); } } else { throw new SubmissionException("Response from submission endpoint (" + url + ") was not OK (200). Was: " + response.getStatusLine().getStatusCode()); } } else { throw new SubmissionException( "Could not find a Submission in the supplied set of Submittables"); } } catch (IOException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } finally { submissionProperties.remove("submissionDate"); } } catch (ParserConfigurationException e) { e.printStackTrace(); } return null; }
From source file:org.gitana.platform.client.support.RemoteImpl.java
@Override public void upload(String uri, InputStream in, long length, String mimetype, String filename) throws Exception { String URL = buildURL(uri, false); HttpPost httpPost = new HttpPost(URL); InputStreamBody inputStreamBody = new InputStreamBody(in, mimetype, filename); MultipartEntity entity = new MultipartEntity(); entity.addPart(filename, inputStreamBody); httpPost.setEntity(entity);/* w w w. j a va 2 s . c om*/ HttpResponse httpResponse = invoker.execute(httpPost); if (!HttpUtil.isOk(httpResponse)) { throw new RuntimeException("Upload failed: " + EntityUtils.toString(httpResponse.getEntity())); } // consume the response fully so that the client connection can be reused EntityUtils.consume(httpResponse.getEntity()); }
From source file:com.ibm.watson.developer_cloud.dialog.v1.DialogService.java
/** * Updates a dialog./*from w w w.j a v a 2 s .c om*/ * * @param dialogId The dialog identifier * @param dialogFile The dialog file * @return the created dialog * @throws UnsupportedEncodingException * @see Dialog */ public Dialog updateDialog(final String dialogId, final File dialogFile) throws UnsupportedEncodingException { if (dialogId == null || dialogId.isEmpty()) throw new IllegalArgumentException("dialogId can not be null or empty"); if (dialogFile == null || !dialogFile.exists()) throw new IllegalArgumentException("dialogFile can not be null or empty"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", new FileBody(dialogFile)); HttpRequestBase request = Request.Put("/v1/dialogs/" + dialogId).withEntity(reqEntity).build(); /*HttpHost proxy=new HttpHost("10.100.1.124",3128); ConnRouteParams.setDefaultProxy(request.getParams(),proxy);*/ executeWithoutResponse(request); Dialog dialog = new Dialog().withDialogId(dialogId); return dialog; }