List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity()
From source file:com.ibm.watson.developer_cloud.dialog.v1.DialogService.java
/** * Creates a dialog./*from w w w . j a va2 s . c om*/ * * @param name The dialog name * @param dialogFile The dialog file created by using the Dialog service Applet. * @return The created dialog * @see Dialog */ public Dialog createDialog(final String name, final File dialogFile) { if (name == null || name.isEmpty()) throw new IllegalArgumentException("name can not be null or empty"); if (dialogFile == null || !dialogFile.exists()) throw new IllegalArgumentException("dialogFile can not be null or empty"); try { MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", new FileBody(dialogFile)); reqEntity.addPart("name", new StringBody(name, Charset.forName("UTF-8"))); HttpRequestBase request = Request.Post("/v1/dialogs").withEntity(reqEntity).build(); /*HttpHost proxy=new HttpHost("10.100.1.124",3128); ConnRouteParams.setDefaultProxy(request.getParams(),proxy);*/ HttpResponse response = execute(request); return ResponseUtil.getObject(response, Dialog.class); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:eu.prestoprime.p4gui.connection.AdminConnection.java
public static boolean restoreFromLTO(P4Service service, String from, String to) { try {/* w w w . jav a 2 s .com*/ String path = service.getURL() + "/admin/restore"; HttpRequestBase request = new HttpPost(path); MultipartEntity part = new MultipartEntity(); part.addPart("from", new StringBody(from)); part.addPart("to", new StringBody(to)); ((HttpPost) request).setEntity(part); P4HttpClient client = new P4HttpClient(service.getUserID()); HttpEntity entity = client.executeRequest(request).getEntity(); if (entity != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); String line; if ((line = reader.readLine()) != null) { if (line.equals("Error")) { return false; } else { return true; } } } } catch (Exception e) { e.printStackTrace(); } return false; }
From source file:org.apache.sling.testing.tools.osgi.WebconsoleClient.java
/** Calls PackageAdmin.refreshPackages to enforce re-wiring of all bundles. */ public void refreshPackages() throws Exception { log.info("Refresh packages."); final MultipartEntity entity = new MultipartEntity(); entity.addPart("action", new StringBody("refreshPackages")); executor.execute(builder.buildPostRequest(CONSOLE_BUNDLES_PATH).withCredentials(username, password) .withEntity(entity)).assertStatus(200); }
From source file:org.openml.knime.OpenMLWebservice.java
/** * Upload a run./* w w w . j av a 2 s . c o m*/ * * @param description Description to the run * @param files Run files * @param user Name of the user * @param password Password of the user * @return Response from the server * @throws Exception */ public static String sendRuns(final File description, final File[] files, final String user, final String password) throws Exception { String result = ""; DefaultHttpClient httpclient = new DefaultHttpClient(); Credentials credentials = new UsernamePasswordCredentials(user, password); AuthScope scope = new AuthScope(new URI(WEBSERVICEURL).getHost(), 80); httpclient.getCredentialsProvider().setCredentials(scope, credentials); try { String url = WEBSERVICEURL + "?f=openml.run.upload"; HttpPost httppost = new HttpPost(url); MultipartEntity reqEntity = new MultipartEntity(); FileBody descriptionBin = new FileBody(description); reqEntity.addPart("description", descriptionBin); for (int i = 0; i < files.length; i++) { FileBody bin = new FileBody(files[i]); reqEntity.addPart("predictions", bin); } httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() < 200) { throw new Exception(response.getStatusLine().getReasonPhrase()); } if (resEntity != null) { result = convertStreamToString(resEntity.getContent()); } ErrorDocument errorDoc = null; try { errorDoc = ErrorDocument.Factory.parse(result); } catch (Exception e) { // no error XML should mean no error } if (errorDoc != null && errorDoc.validate()) { ErrorDocument.Error error = errorDoc.getError(); String errorMessage = error.getCode() + " : " + error.getMessage(); if (error.isSetAdditionalInformation()) { errorMessage += " : " + error.getAdditionalInformation(); } throw new Exception(errorMessage); } EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { // ignore } } return result; }
From source file:org.wso2.am.integration.tests.publisher.APIM614AddDocumentationToAnAPIWithDocTypeSampleAndSDKThroughPublisherRestAPITestCase.java
@Test(groups = { "wso2.am" }, description = "Add Documentation To An API With Type HowTo And" + " Source File through the publisher rest API ", dependsOnMethods = "testApiCreation") public void testAddDocumentToAnAPIHowToFile() throws Exception { String fileNameAPIM614 = "APIM614.txt"; String docName = "APIM614PublisherTestHowTo-File-summary"; String docType = "How To"; String sourceType = "file"; String summary = "Testing"; String mimeType = "text/plain"; String docUrl = "http://"; String filePathAPIM614 = TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator + "AM" + File.separator + "lifecycletest" + File.separator + fileNameAPIM614; ;//from w ww.ja v a 2s. c o m String addDocUrl = publisherUrls.getWebAppURLHttp() + "publisher/site/blocks/documentation/ajax/docs.jag"; //Send Http Post request to add a new file HttpPost httppost = new HttpPost(addDocUrl); File file = new File(filePathAPIM614); FileBody fileBody = new FileBody(file, "text/plain"); //Create multipart entity to upload file as multipart file MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("docLocation", fileBody); multipartEntity.addPart("mode", new StringBody("")); multipartEntity.addPart("docName", new StringBody(docName)); multipartEntity.addPart("docUrl", new StringBody(docUrl)); multipartEntity.addPart("sourceType", new StringBody(sourceType)); multipartEntity.addPart("summary", new StringBody(summary)); multipartEntity.addPart("docType", new StringBody(docType)); multipartEntity.addPart("version", new StringBody(apiVersion)); multipartEntity.addPart("apiName", new StringBody(apiName)); multipartEntity.addPart("action", new StringBody("addDocumentation")); multipartEntity.addPart("provider", new StringBody(apiProvider)); multipartEntity.addPart("mimeType", new StringBody(mimeType)); multipartEntity.addPart("optionsRadios", new StringBody(docType)); multipartEntity.addPart("optionsRadios1", new StringBody(sourceType)); multipartEntity.addPart("optionsRadios1", new StringBody(sourceType)); httppost.setEntity(multipartEntity); //Upload created file and validate HttpResponse response = httpClient.execute(httppost); HttpEntity entity = response.getEntity(); JSONObject jsonObject1 = new JSONObject(EntityUtils.toString(entity)); assertFalse(jsonObject1.getBoolean("error"), "Error when adding files to the API "); }
From source file:com.globalsight.everest.tda.TdaHelper.java
public void leverageTDA(TDATM tda, File needLeverageXliffFile, String storePath, String fileName, String sourceLocal, String targetLocal) { int timeoutConnection = 15000; HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); String loginUrl = new String(); if (tda.getHostName().indexOf("http://") < 0) { loginUrl = "http://" + tda.getHostName(); } else {/*from w w w. j a v a 2s.c om*/ loginUrl = tda.getHostName(); } if (tda.getHostName().lastIndexOf("/") < (tda.getHostName().length() - 1)) { loginUrl = loginUrl + "/"; } try { // Judge if the TDA server has the source and target language HttpGet lanGet = new HttpGet(loginUrl + "lang/" + sourceLocal.toLowerCase() + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse lanRes = httpclient.execute(lanGet); StatusLine stl = lanRes.getStatusLine(); if (stl.getStatusCode() != 200) { loggerTDAInfo(stl, sourceLocal.toString()); return; } lanGet.abort(); HttpGet lanGet2 = new HttpGet(loginUrl + "lang/" + targetLocal.toLowerCase() + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse lanRes2 = httpclient.execute(lanGet2); stl = lanRes2.getStatusLine(); if (stl.getStatusCode() != 200) { loggerTDAInfo(stl, targetLocal.toString()); return; } lanGet2.abort(); HttpPost httpPost = new HttpPost(loginUrl + "leverage.json?action=create"); FileBody fileBody = new FileBody(needLeverageXliffFile); StringBody nameBody = new StringBody(tda.getUserName()); StringBody passwordBody = new StringBody(tda.getPassword()); StringBody appKeyBody = new StringBody(appKey); StringBody srcBody = new StringBody(sourceLocal.toLowerCase()); StringBody trBody = new StringBody(targetLocal.toLowerCase()); StringBody confirmBody = new StringBody("true"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", fileBody); reqEntity.addPart("auth_username", nameBody); reqEntity.addPart("auth_password", passwordBody); reqEntity.addPart("auth_app_key", appKeyBody); reqEntity.addPart("source_lang", srcBody); reqEntity.addPart("target_lang", trBody); reqEntity.addPart("confirm", confirmBody); httpPost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); StatusLine sl = response.getStatusLine(); if (sl.getStatusCode() != 201) { loggerTDAInfo(stl, null); return; } JSONObject jso = new JSONObject(EntityUtils.toString(entity)); JSONArray lev = jso.getJSONArray("leverage"); httpPost.abort(); if (lev.length() > 0) { JSONObject obj = lev.getJSONObject(0); String states = obj.getString("state"); // waiting the "not ready" state becoming "ready" state Thread.sleep(3 * 1000); int i = 0; if (!states.equals("ready")) { boolean flag = true; while (flag) { if (i > 40) { s_logger.info("Get TDA job status overtime. TDA job id:" + obj.getInt("id")); s_logger.info("TDA leveraging waited time:" + (40 * 3) + " seconds!"); return; } i++; HttpGet httpget = new HttpGet(loginUrl + "leverage/" + obj.getInt("id") + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); response = httpclient.execute(httpget); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { s_logger.info( "Get TDA job status error, please confirm the TDA url is correct or not! TDA job id:" + obj.getInt("id")); return; } entity = response.getEntity(); JSONObject getObj = new JSONObject(EntityUtils.toString(entity)); if (getObj.getJSONObject("leverage").getString("state").equals("ready")) { s_logger.info("TDA leveraging waited time:" + (i * 3) + " seconds!"); flag = false; } else { Thread.sleep(3 * 1000); } httpget.abort(); } } HttpPost httpPost2 = new HttpPost(loginUrl + "leverage/" + obj.getInt("id") + ".json?action=approve&auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); response = httpclient.execute(httpPost2); entity = response.getEntity(); httpPost2.abort(); HttpGet httpGet = new HttpGet(loginUrl + "leverage/" + obj.getString("id") + "/result.xlf.zip?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse response2 = httpclient.execute(httpGet); entity = response2.getEntity(); ZipInputStream fs = new ZipInputStream(entity.getContent()); int BUFFER = 2048; byte data[] = new byte[BUFFER]; int count; while (fs.getNextEntry() != null) { FileOutputStream fos = new FileOutputStream(storePath + File.separator + fileName); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); while ((count = fs.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } httpGet.abort(); s_logger.info("Leverage TDA TM success, TDA id:" + obj.getString("id")); } } catch (Exception e) { s_logger.error("TDA leverage process error:" + e.getMessage()); } }
From source file:org.ow2.proactive_grid_cloud_portal.scheduler.server.SchedulerServiceImpl.java
/** * Submits a XML file to the REST part by using an HTTP client. * * @param sessionId the id of the client which submits the job * @param file the XML file that is submitted * @return an error message upon failure, "id=<jobId>" upon success * @throws RestServerException// w w w. j a v a 2 s . c o m * @throws ServiceException */ public String submitXMLFile(String sessionId, File file) throws RestServerException, ServiceException { HttpPost method = new HttpPost(SchedulerConfig.get().getRestUrl() + "/scheduler/submit"); method.addHeader("sessionId", sessionId); boolean isJar = isJarFile(file); try { String name = isJar ? "jar" : "file"; String mime = isJar ? "application/java-archive" : "application/xml"; String charset = "ISO-8859-1"; MultipartEntity entity = new MultipartEntity(); entity.addPart("file", new FileBody(file, name, mime, charset)); method.setEntity(entity); HttpResponse execute = httpClient.execute(method); InputStream is = execute.getEntity().getContent(); String ret = convertToString(is); if (execute.getStatusLine().getStatusCode() == Response.Status.OK.getStatusCode()) { return ret; } else { throw new RestServerException(execute.getStatusLine().getStatusCode(), ret); } } catch (IOException e) { throw new ServiceException("Failed to read response: " + e.getMessage()); } finally { method.releaseConnection(); if (file != null) { file.delete(); } } }
From source file:org.megam.deccanplato.provider.box.handler.FileImpl.java
/** * @return// w w w.j a v a2 s . c om */ private Map<String, String> upload() { Map<String, String> outMap = new HashMap<>(); final String BOX_UPLOAD = "/files/content"; Map<String, String> headerMap = new HashMap<String, String>(); headerMap.put("Authorization", "BoxAuth api_key=" + args.get(API_KEY) + "&auth_token=" + args.get(TOKEN)); MultipartEntity entity = new MultipartEntity(); FileBody filename = new FileBody(new File(args.get(FILE_NAME))); FileBody filename1 = new FileBody(new File("/home/pandiyaraja/Documents/AMIs")); StringBody parent_id = null; try { parent_id = new StringBody(args.get(FOLDER_ID)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } entity.addPart("filename", filename); entity.addPart("parent_id", parent_id); TransportTools tools = new TransportTools(BOX_URI + BOX_UPLOAD, null, headerMap); tools.setFileEntity(entity); String responseBody = null; TransportResponse response = null; try { response = TransportMachinery.post(tools); responseBody = response.entityToString(); System.out.println("OUTPUT:" + responseBody); } catch (ClientProtocolException ce) { ce.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } outMap.put(OUTPUT, responseBody); return outMap; }
From source file:org.tellervo.desktop.wsi.WebJaxbAccessor.java
private INTYPE doRequest() throws IOException { HttpClient client = new ContentEncodingHttpClient(); HttpUriRequest req;/*from w ww . jav a 2 s . co m*/ JAXBContext context; Document outDocument = null; try { context = getJAXBContext(); } catch (JAXBException jaxb) { throw new IOException("Unable to acquire JAXB context: " + jaxb.getMessage()); } try { if (requestMethod == RequestMethod.POST) { if (this.sendingObject == null) throw new NullPointerException("requestDocument is null yet required for this type of query"); // Create a new POST request HttpPost post = new HttpPost(url); // Make it a multipart post MultipartEntity postEntity = new MultipartEntity(); req = post; // create an XML document from the given objects outDocument = marshallToDocument(context, sendingObject, getNamespacePrefixMapper()); // add it to the http post request XMLBody xmlb = new XMLBody(outDocument, "application/tellervo+xml", null); postEntity.addPart("xmlrequest", xmlb); postEntity.addPart("traceback", new StringBody(getStackTrace())); post.setEntity(postEntity); } else { // well, that's nice and easy req = new HttpGet(url); } // debug this transaction... TransactionDebug.sent(outDocument, noun); // load cookies ((AbstractHttpClient) client).setCookieStore(WSCookieStoreHandler.getCookieStore().toCookieStore()); req.setHeader("User-Agent", "Tellervo WSI " + Build.getUTF8Version() + " (" + clientModuleVersion + "; ts " + Build.getCompleteVersionNumber() + ")"); if (App.prefs.getBooleanPref(PrefKey.WEBSERVICE_USE_STRICT_SECURITY, false)) { // Using strict security so don't allow self signed certificates for SSL } else { // Not using strict security so allow self signed certificates for SSL if (url.getScheme().equals("https")) WebJaxbAccessor.setSelfSignableHTTPSScheme(client); } // create a responsehandler JaxbResponseHandler<INTYPE> responseHandler = new JaxbResponseHandler<INTYPE>(context, receivingObjectClass); // set the schema we validate against responseHandler.setValidateSchema(getValidationSchema()); // execute the actual http query INTYPE inObject = null; try { inObject = client.execute(req, responseHandler); } catch (EOFException e4) { log.debug("Caught EOFException"); } TransactionDebug.received(inObject, noun, context); // save our cookies? WSCookieStoreHandler.getCookieStore().fromCookieStore(((AbstractHttpClient) client).getCookieStore()); // ok, now inspect the document we got back //TellervoDocumentInspector inspector = new TellervoDocumentInspector(inDocument); // Verify our document based on schema validity //inspector.validate(); // Verify our document structure, throw any exceptions! //inspector.verifyDocument(); return inObject; } catch (UnknownHostException e) { throw new IOException("The URL of the server you have specified is unknown"); } catch (HttpResponseException hre) { if (hre.getStatusCode() == 404) { throw new IOException("The URL of the server you have specified is unknown"); } BugReport bugs = new BugReport(hre); bugs.addDocument("sent.xml", outDocument); new BugDialog(bugs); throw new IOException("The server returned a protocol error " + hre.getStatusCode() + ": " + hre.getLocalizedMessage()); } catch (IllegalStateException ex) { throw new IOException("Webservice URL must be a full URL qualified with a communications protocol.\n" + "Tellervo currently supports http:// and https://."); } catch (ResponseProcessingException rspe) { Throwable cause = rspe.getCause(); BugReport bugs = new BugReport(cause); Document invalidDoc = rspe.getNonvalidatingDocument(); File invalidFile = rspe.getInvalidFile(); if (outDocument != null) bugs.addDocument("sent.xml", outDocument); if (invalidDoc != null) bugs.addDocument("recv-nonvalid.xml", invalidDoc); if (invalidFile != null) bugs.addDocument("recv-malformed.xml", invalidFile); new BugDialog(bugs); XMLDebugView.addDocument(BugReport.getStackTrace(cause), "Parsing Exception", true); // it's probably an ioexception... if (cause instanceof IOException) throw (IOException) cause; throw rspe; } catch (XMLParsingException xmlpe) { Throwable cause = xmlpe.getCause(); BugReport bugs = new BugReport(cause); Document invalidDoc = xmlpe.getNonvalidatingDocument(); File invalidFile = xmlpe.getInvalidFile(); bugs.addDocument("sent.xml", outDocument); if (invalidDoc != null) bugs.addDocument("recv-nonvalid.xml", invalidDoc); if (invalidFile != null) bugs.addDocument("recv-malformed.xml", invalidFile); new BugDialog(bugs); XMLDebugView.addDocument(BugReport.getStackTrace(cause), "Parsing Exception", true); // it's probably an ioexception... if (cause instanceof IOException) throw (IOException) cause; throw xmlpe; } catch (IOException ioe) { throw ioe; } catch (Exception uhe) { BugReport bugs = new BugReport(uhe); bugs.addDocument("sent.xml", outDocument); /* // MalformedDocs are handled automatically by BugReport class if(!(uhe instanceof MalformedDocumentException) && inDocument != null) bugs.addDocument("received.xml", inDocument); */ new BugDialog(bugs); throw new IOException("Exception " + uhe.getClass().getName() + ": " + uhe.getLocalizedMessage()); } finally { //? } }
From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java
/** * Sends data to create and train a classifier, and returns information about the new * classifier. The status has the value of `Training` when the operation is * successful, and might remain at this status for a while. * * @param name the classifier name * @param language IETF primary language for the classifier * @param csvTrainingData the CSV training data * @return the classifier/*from ww w. j a v a 2 s. com*/ * @see Classifier */ public Classifier createClassifier(final String name, final String language, final File csvTrainingData) { if (csvTrainingData == null || !csvTrainingData.exists()) throw new IllegalArgumentException("csvTrainingData can not be null or not be found"); JsonObject contentJson = new JsonObject(); contentJson.addProperty("language", language == null ? LANGUAGE_EN : language); if (name != null && !name.isEmpty()) { contentJson.addProperty("name", name); } try { MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("training_data", new FileBody(csvTrainingData)); reqEntity.addPart("training_metadata", new StringBody(contentJson.toString())); HttpRequestBase request = Request.Post("/v1/classifiers").withEntity(reqEntity).build(); HttpHost proxy = new HttpHost("10.100.1.124", 3128); ConnRouteParams.setDefaultProxy(request.getParams(), proxy); HttpResponse response = execute(request); return ResponseUtil.getObject(response, Classifier.class); } catch (IOException e) { throw new RuntimeException(e); } }