List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file)
From source file:MyZone.Settings.java
public boolean createNewUser(String username, String firstName, String lastName, String gender, String searchable) {/*from w w w . ja v a2 s . com*/ 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:com.qmetry.qaf.automation.integration.qmetry.qmetry6.patch.QMetryRestWebservice.java
/** * attach log using run id/*w w w. j a va 2 s. co m*/ * * @param token * - token generate using username and password * @param projectID * @param releaseID * @param cycleID * @param testCaseRunId * @param filePath * - absolute path of file to be attached * @return */ public int attachTestLogsUsingRunId(String token, String projectID, String releaseID, String cycleID, long testCaseRunId, File filePath) { try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss"); final String CurrentDate = format.format(new Date()); Path path = Paths.get(filePath.toURI()); byte[] outFileArray = Files.readAllBytes(path); if (outFileArray != null) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(baseURL + "/rest/attachments/testLog"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(filePath); builder.addTextBody("desc", "Attached on " + CurrentDate, ContentType.TEXT_PLAIN); builder.addTextBody("type", "TCR", ContentType.TEXT_PLAIN); builder.addTextBody("entityId", String.valueOf(testCaseRunId), ContentType.TEXT_PLAIN); builder.addPart("file", bin); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); httppost.addHeader("usertoken", token); httppost.addHeader("scope", projectID + ":" + releaseID + ":" + cycleID); CloseableHttpResponse response = httpclient.execute(httppost); String str = null; try { str = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } finally { } JsonElement gson = new Gson().fromJson(str, JsonElement.class); JsonElement data = gson.getAsJsonObject().get("data"); int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString()); return id; } finally { httpclient.close(); } } else { System.out.println(filePath + " file does not exists"); } } catch (Exception ex) { System.out.println("Error in attaching file - " + filePath); System.out.println(ex.getMessage()); } return 0; }
From source file:fr.mael.jiwigo.dao.impl.ImageDaoImpl.java
public void addSimple(File file, Integer category, String title, Integer level) throws JiwigoException { HttpPost httpMethod = new HttpPost(((SessionManagerImpl) sessionManager).getUrl()); // nameValuePairs.add(new BasicNameValuePair("method", "pwg.images.addSimple")); // for (int i = 0; i < parametres.length; i += 2) { // nameValuePairs.add(new BasicNameValuePair(parametres[i], parametres[i + 1])); // }/*from www.j av a 2s . c o m*/ // method.setEntity(new UrlEncodedFormEntity(nameValuePairs)); if (file != null) { MultipartEntity multipartEntity = new MultipartEntity(); // String string = nameValuePairs.toString(); // dirty fix to remove the enclosing entity{} // String substring = string.substring(string.indexOf("{"), // string.lastIndexOf("}") + 1); try { multipartEntity.addPart("method", new StringBody(MethodsEnum.ADD_SIMPLE.getLabel())); multipartEntity.addPart("category", new StringBody(category.toString())); multipartEntity.addPart("name", new StringBody(title)); if (level != null) { multipartEntity.addPart("level", new StringBody(level.toString())); } } catch (UnsupportedEncodingException e) { throw new JiwigoException(e); } // StringBody contentBody = new StringBody(substring, // Charset.forName("UTF-8")); // multipartEntity.addPart("entity", contentBody); FileBody fileBody = new FileBody(file); multipartEntity.addPart("image", fileBody); ((HttpPost) httpMethod).setEntity(multipartEntity); } HttpResponse response; StringBuilder sb = new StringBuilder(); try { response = ((SessionManagerImpl) sessionManager).getClient().execute(httpMethod); int responseStatusCode = response.getStatusLine().getStatusCode(); switch (responseStatusCode) { case HttpURLConnection.HTTP_CREATED: break; case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_BAD_REQUEST: throw new JiwigoException("status code was : " + responseStatusCode); case HttpURLConnection.HTTP_FORBIDDEN: throw new JiwigoException("status code was : " + responseStatusCode); case HttpURLConnection.HTTP_NOT_FOUND: throw new JiwigoException("status code was : " + responseStatusCode); default: throw new JiwigoException("status code was : " + responseStatusCode); } HttpEntity resultEntity = response.getEntity(); BufferedHttpEntity responseEntity = new BufferedHttpEntity(resultEntity); BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent())); String line; try { while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } } finally { reader.close(); } } catch (ClientProtocolException e) { throw new JiwigoException(e); } catch (IOException e) { throw new JiwigoException(e); } String stringResult = sb.toString(); }
From source file:fi.hut.soberit.sensors.services.BatchDataUploadService.java
protected void populateMultipartEntity(MultipartEntity multipartEntity, File file) { multipartEntity.addPart(uploadFileField, new FileBody(file)); }
From source file:pl.psnc.synat.wrdz.zmkd.plan.MigrationPlanProcessorBean.java
/** * Creates a new object in ZMD.//from w ww . jav a2 s. c o m * * @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.uf.togathor.db.couchdb.ConnectionHandler.java
public static String getIdFromFileUploader(String url, List<NameValuePair> params) throws IOException, UnsupportedOperationException { // Making HTTP request // defaultHttpClient HttpParams httpParams = new BasicHttpParams(); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParams, "UTF-8"); HttpClient httpClient = new DefaultHttpClient(httpParams); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("database", Const.DATABASE); Charset charSet = Charset.forName("UTF-8"); // Setting up the // encoding//from w w w .j a va2s . co m MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (int index = 0; index < params.size(); index++) { if (params.get(index).getName().equalsIgnoreCase(Const.FILE)) { // If the key equals to "file", we use FileBody to // transfer the data entity.addPart(params.get(index).getName(), new FileBody(new File(params.get(index).getValue()))); } else { // Normal string data entity.addPart(params.get(index).getName(), new StringBody(params.get(index).getValue(), charSet)); } } httpPost.setEntity(entity); print(httpPost); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); InputStream is = httpEntity.getContent(); // if (httpResponse.getStatusLine().getStatusCode() > 400) // { // if (httpResponse.getStatusLine().getStatusCode() == 500) throw new SpikaException(ConnectionHandler.getError(entity.getContent())); // throw new IOException(httpResponse.getStatusLine().getReasonPhrase()); // } // BufferedReader reader = new BufferedReader(new // InputStreamReader(is, "iso-8859-1"), 8); BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); String json = sb.toString(); Logger.debug("RESPONSE", json); return json; }
From source file:com.atlassian.jira.rest.client.internal.async.AsynchronousIssueRestClient.java
@Override public Promise<Void> addAttachments(final URI attachmentsUri, final File... files) { final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.defaultCharset()); for (final File file : files) { entity.addPart(FILE_BODY_TYPE, new FileBody(file)); }/*from w ww . ja v a2s.c om*/ return postAttachments(attachmentsUri, entity); }
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//from w w w .j a va 2s . c om * @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:com.ibm.watson.developer_cloud.dialog.v1.DialogService.java
/** * Updates a dialog./*from w w w . j a v a 2s . co m*/ * * @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; }
From source file:com.gorillalogic.monkeytalk.ant.RunTask.java
private String sendFormPost(String url, File proj, Map<String, String> additionalParams) throws IOException { HttpClient base = new DefaultHttpClient(); SSLContext ctx = null;/*from w w w. java 2 s . c o m*/ try { ctx = SSLContext.getInstance("TLS"); } catch (NoSuchAlgorithmException ex) { log("exception in sendFormPost():"); } X509TrustManager tm = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } }; try { ctx.init(null, new TrustManager[] { tm }, null); } catch (KeyManagementException ex) { log("exception in sendFormPost():"); } SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); HttpClient client = new DefaultHttpClient(ccm, base.getParams()); try { HttpPost post = new HttpPost(url); MultipartEntity multipart = new MultipartEntity(); for (String key : additionalParams.keySet()) multipart.addPart(key, new StringBody(additionalParams.get(key), Charset.forName("UTF-8"))); if (proj != null) { multipart.addPart("uploaded_file", new FileBody(proj)); } post.setEntity(multipart); HttpResponse resp = client.execute(post); HttpEntity out = resp.getEntity(); InputStream in = out.getContent(); return FileUtils.readStream(in); } catch (Exception ex) { throw new IOException("POST failed", ex); } finally { try { client.getConnectionManager().shutdown(); } catch (Exception ex) { // ignore } } }