List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder setMode
public MultipartEntityBuilder setMode(final HttpMultipartMode mode)
From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.patch.QMetryRestWebservice.java
/** * attach log using run id/*from w ww .j av a 2s .c om*/ * * @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:org.guvnor.ala.wildfly.access.WildflyClient.java
public int deploy(File file) throws WildflyClientException { // the digest auth backend CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host, managementPort), new UsernamePasswordCredentials(user, password)); CloseableHttpClient httpclient = custom().setDefaultCredentialsProvider(credsProvider).build(); HttpPost post = new HttpPost("http://" + host + ":" + managementPort + "/management-upload"); post.addHeader("X-Management-Client-Name", "HAL"); // the file to be uploaded FileBody fileBody = new FileBody(file); // the DMR operation ModelNode operation = new ModelNode(); operation.get("address").add("deployment", file.getName()); operation.get("operation").set("add"); operation.get("runtime-name").set(file.getName()); operation.get("enabled").set(true); operation.get("content").add().get("input-stream-index").set(0); // point to the multipart index used ByteArrayOutputStream bout = new ByteArrayOutputStream(); try {//from w ww. jav a 2s. c om operation.writeBase64(bout); } catch (IOException ex) { getLogger(WildflyClient.class.getName()).log(SEVERE, null, ex); } // the multipart MultipartEntityBuilder builder = create(); builder.setMode(BROWSER_COMPATIBLE); builder.addPart("uploadFormElement", fileBody); builder.addPart("operation", new ByteArrayBody(bout.toByteArray(), create("application/dmr-encoded"), "blob")); HttpEntity entity = builder.build(); post.setEntity(entity); try { HttpResponse response = httpclient.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { throw new WildflyClientException("Error Deploying App Status Code: " + statusCode); } return statusCode; } catch (IOException ex) { LOG.error("Error Deploying App : " + ex.getMessage(), ex); throw new WildflyClientException("Error Deploying App : " + ex.getMessage(), ex); } }
From source file:com.secdec.codedx.api.client.CodeDxClient.java
/** * Kicks off a CodeDx analysis run on a specified project * * @return A StartAnalysisResponse object * @param projectId The project ID//from w w w .j av a2 s. co m * @param artifacts An array of streams to send over as analysis artifacts * @throws ClientProtocolException * @throws IOException * @throws CodeDxClientException * */ public StartAnalysisResponse startAnalysis(int projectId, InputStream[] artifacts) throws ClientProtocolException, IOException, CodeDxClientException { HttpPost postRequest = new HttpPost(url + "projects/" + projectId + "/analysis"); postRequest.addHeader(KEY_HEADER, key); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (InputStream artifact : artifacts) { builder.addPart("file[]", new InputStreamBody(artifact, "file[]")); } HttpEntity entity = builder.build(); postRequest.setEntity(entity); HttpResponse response = httpClient.execute(postRequest); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != 202) { throw new CodeDxClientException( "Failed to start analysis. " + IOUtils.toString(response.getEntity().getContent()), responseCode); } String data = IOUtils.toString(response.getEntity().getContent()); return gson.<StartAnalysisResponse>fromJson(data, new TypeToken<StartAnalysisResponse>() { }.getType()); }
From source file:org.brutusin.rpc.client.http.HttpEndpoint.java
private CloseableHttpResponse doExec(String serviceId, JsonNode input, HttpMethod httpMethod, final ProgressCallback progressCallback) throws IOException { RpcRequest request = new RpcRequest(); request.setJsonrpc("2.0"); request.setMethod(serviceId);/* ww w . j av a 2s .c o m*/ request.setParams(input); final String payload = JsonCodec.getInstance().transform(request); final HttpUriRequest req; if (httpMethod == HttpMethod.GET) { String urlparam = URLEncoder.encode(payload, "UTF-8"); req = new HttpGet(this.endpoint + "?jsonrpc=" + urlparam); } else { HttpEntityEnclosingRequestBase reqBase; if (httpMethod == HttpMethod.POST) { reqBase = new HttpPost(this.endpoint); } else if (httpMethod == HttpMethod.PUT) { reqBase = new HttpPut(this.endpoint); } else { throw new AssertionError(); } req = reqBase; HttpEntity entity; Map<String, InputStream> files = JsonCodec.getInstance().getStreams(input); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.STRICT); builder.addPart("jsonrpc", new StringBody(payload, ContentType.APPLICATION_JSON)); if (files != null && !files.isEmpty()) { files = sortFiles(files); for (Map.Entry<String, InputStream> entrySet : files.entrySet()) { String key = entrySet.getKey(); InputStream is = entrySet.getValue(); if (is instanceof MetaDataInputStream) { MetaDataInputStream mis = (MetaDataInputStream) is; builder.addPart(key, new InputStreamBody(mis, mis.getName())); } else { builder.addPart(key, new InputStreamBody(is, key)); } } } entity = builder.build(); if (progressCallback != null) { entity = new ProgressHttpEntityWrapper(entity, progressCallback); } reqBase.setEntity(entity); } HttpClientContext context = contexts.get(); if (this.clientContextFactory != null && context == null) { context = clientContextFactory.create(); contexts.set(context); } return this.httpClient.execute(req, context); }
From source file:org.wso2.appcloud.integration.test.utils.clients.ApplicationClient.java
public void changeAppIcon(String applicationHash, File appIcon) throws AppCloudIntegrationTestException { HttpClient httpclient = null;/*from w w w .jav a 2 s. c o m*/ org.apache.http.HttpResponse response = null; try { httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build(); int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).build(); HttpPost httppost = new HttpPost(this.endpoint); httppost.setConfig(requestConfig); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart(PARAM_NAME_CHANGE_ICON, new FileBody(appIcon)); builder.addPart(PARAM_NAME_ACTION, new StringBody(CHANGE_APP_ICON_ACTION, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APPLICATION_HASH_ID, new StringBody(applicationHash, ContentType.TEXT_PLAIN)); httppost.setEntity(builder.build()); httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE)); response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity()); throw new AppCloudIntegrationTestException("Update app icon failed " + result); } } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) { // In most of the cases, even though connection is timed out, actual activity is completed. // And this will be asserted so if it failed due to a valid case, it will be captured. log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1); } catch (IOException e) { log.error("Failed to invoke app icon update API.", e); throw new AppCloudIntegrationTestException("Failed to invoke app icon update API.", e); } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(httpclient); } }
From source file:com.licryle.httpposter.HttpPoster.java
/** * Builds the {@link _ProgressiveEntity} that we will send to the server. * Takes for input an {@link HttpConfiguration} that contains the Post * variables and File Names to send.//from w w w. j a va2s . c o m * * @param mConf Configuration of the POST request to be processed. * @return A ProgressiveEntity which progress can be tracked as we send it to * the server. * * @throws IOException When a file in the list of files from * {@link HttpConfiguration#getFiles()} cannot be read. * * @see {@link com.licryle.httpposter.HttpPoster._ProgressiveEntity} * @see {@link com.licryle.httpposter.HttpConfiguration} */ protected _ProgressiveEntity _buildEntity(HttpConfiguration mConf) throws IOException { Log.d("HttpPoster", String.format("_buildEntity: Entering for Instance %d", _iInstanceId)); /********* Build request content *********/ MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create(); mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); mBuilder.setBoundary(mConf.getHTTPBoundary()); int iFileNb = 0; Iterator mFiles = mConf.getFiles().iterator(); while (mFiles.hasNext()) { final File mFile = (File) mFiles.next(); try { mBuilder.addBinaryBody("file_" + iFileNb, mFile, ContentType.DEFAULT_BINARY, mFile.getName()); } catch (Exception e) { throw new IOException(); } iFileNb++; } Iterator mArgs = mConf.getArgs().entrySet().iterator(); while (mArgs.hasNext()) { Map.Entry mPair = (Map.Entry) mArgs.next(); mBuilder.addTextBody((String) mPair.getKey(), (String) mPair.getValue(), ContentType.MULTIPART_FORM_DATA); } Log.d("HttpPoster", String.format("_buildEntity: Leaving for Instance %d", _iInstanceId)); return new _ProgressiveEntity(mBuilder.build(), this); }
From source file:com.gargoylesoftware.htmlunit.html.HtmlFileInputTest.java
/** * Test HttpClient for uploading a file with non-ASCII name, if it works it means HttpClient has fixed its bug. * * Test for http://issues.apache.org/jira/browse/HTTPCLIENT-293, * which is related to http://sourceforge.net/p/htmlunit/bugs/535/ * * @throws Exception if the test fails/* ww w . ja v a2 s . c om*/ */ @Test public void uploadFileWithNonASCIIName_HttpClient() throws Exception { final String filename = "\u6A94\u6848\uD30C\uC77C\u30D5\u30A1\u30A4\u30EB\u0645\u0644\u0641.txt"; final String path = getClass().getClassLoader().getResource(filename).toExternalForm(); final File file = new File(new URI(path)); assertTrue(file.exists()); final Map<String, Class<? extends Servlet>> servlets = new HashMap<>(); servlets.put("/upload2", Upload2Servlet.class); startWebServer("./", null, servlets); final HttpPost filePost = new HttpPost("http://localhost:" + PORT + "/upload2"); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(Charset.forName("UTF-8")); builder.addPart("myInput", new FileBody(file, ContentType.APPLICATION_OCTET_STREAM)); filePost.setEntity(builder.build()); final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); final HttpResponse httpResponse = clientBuilder.build().execute(filePost); InputStream content = null; try { content = httpResponse.getEntity().getContent(); final String response = new String(IOUtils.toByteArray(content)); //this is the value with ASCII encoding assertFalse("3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 2E 74 78 74 <br>myInput".equals(response)); } finally { IOUtils.closeQuietly(content); } }
From source file:org.wso2.appcloud.integration.test.utils.clients.ApplicationClient.java
public void createNewApplication(String applicationName, String runtime, String appTypeName, String applicationRevision, String applicationDescription, String uploadedFileName, String runtimeProperties, String tags, File uploadArtifact, boolean isNewVersion, String applicationContext, String conSpec, boolean setDefaultVersion, String appCreationMethod, String gitRepoUrl, String gitRepoBranch, String projectRoot) throws AppCloudIntegrationTestException { HttpClient httpclient = null;// w w w . j a v a 2 s. c o m org.apache.http.HttpResponse response = null; int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod(); try { httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).build(); HttpPost httppost = new HttpPost(this.endpoint); httppost.setConfig(requestConfig); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart(PARAM_NAME_ACTION, new StringBody(CREATE_APPLICATION_ACTION, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APP_CREATION_METHOD, new StringBody(appCreationMethod, ContentType.TEXT_PLAIN)); if (GITHUB.equals(appCreationMethod)) { builder.addPart(PARAM_NAME_GIT_REPO_URL, new StringBody(gitRepoUrl, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_GIT_REPO_BRANCH, new StringBody(gitRepoBranch, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_PROJECT_ROOT, new StringBody(projectRoot, ContentType.TEXT_PLAIN)); } else if (DEFAULT.equals(appCreationMethod)) { builder.addPart(PARAM_NAME_FILE_UPLOAD, new FileBody(uploadArtifact)); builder.addPart(PARAM_NAME_UPLOADED_FILE_NAME, new StringBody(uploadedFileName, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_IS_FILE_ATTACHED, new StringBody(Boolean.TRUE.toString(), ContentType.TEXT_PLAIN));//Setting true to send the file in request } builder.addPart(PARAM_NAME_CONTAINER_SPEC, new StringBody(conSpec, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APPLICATION_NAME, new StringBody(applicationName, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APPLICATION_DESCRIPTION, new StringBody(applicationDescription, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_RUNTIME, new StringBody(runtime, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APP_TYPE_NAME, new StringBody(appTypeName, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APP_CONTEXT, new StringBody(applicationContext, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APPLICATION_REVISION, new StringBody(applicationRevision, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_PROPERTIES, new StringBody(runtimeProperties, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_TAGS, new StringBody(tags, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_IS_NEW_VERSION, new StringBody(Boolean.toString(isNewVersion), ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_SET_DEFAULT_VERSION, new StringBody(Boolean.toString(setDefaultVersion), ContentType.TEXT_PLAIN)); httppost.setEntity(builder.build()); httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE)); response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity()); throw new AppCloudIntegrationTestException("CreateNewApplication failed " + result); } } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) { // In most of the cases, even though connection is timed out, actual activity is completed. // If application is not created, in next test case, it will be identified. log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1); } catch (IOException e) { log.error("Failed to invoke application creation API.", e); throw new AppCloudIntegrationTestException("Failed to invoke application creation API.", e); } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(httpclient); } }