org.apache.http.entity.FileEntity Java Examples
The following examples show how to use
org.apache.http.entity.FileEntity.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JAXRSClientServerBookTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testUpdateBook() throws Exception { String endpointAddress = "http://localhost:" + PORT + "/bookstore/books"; File input = new File(getClass().getResource("resources/update_book.txt").toURI()); CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPut put = new HttpPut(endpointAddress); put.setEntity(new FileEntity(input, ContentType.TEXT_XML)); try { CloseableHttpResponse response = client.execute(put); assertEquals(200, response.getStatusLine().getStatusCode()); InputStream expected = getClass().getResourceAsStream("resources/expected_update_book.txt"); assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)), stripXmlInstructionIfNeeded(EntityUtils.toString(response.getEntity()))); } finally { // Release current connection to the connection pool once you are // done put.releaseConnection(); } }
Example #2
Source File: HttpClientHandler.java From ant-ivy with Apache License 2.0 | 6 votes |
@Override public void upload(final File src, final URL dest, final CopyProgressListener listener, final TimeoutConstraint timeoutConstraint) throws IOException { final int connectionTimeout = (timeoutConstraint == null || timeoutConstraint.getConnectionTimeout() < 0) ? 0 : timeoutConstraint.getConnectionTimeout(); final int readTimeout = (timeoutConstraint == null || timeoutConstraint.getReadTimeout() < 0) ? 0 : timeoutConstraint.getReadTimeout(); final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout) .setConnectTimeout(connectionTimeout) .setAuthenticationEnabled(hasCredentialsConfigured(dest)) .setTargetPreferredAuthSchemes(getAuthSchemePreferredOrder()) .setProxyPreferredAuthSchemes(getAuthSchemePreferredOrder()) .setExpectContinueEnabled(true) .build(); final HttpPut put = new HttpPut(normalizeToString(dest)); put.setConfig(requestConfig); put.setEntity(new FileEntity(src)); try (final CloseableHttpResponse response = this.httpClient.execute(put)) { validatePutStatusCode(dest, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } }
Example #3
Source File: DeployResourceRequest.java From knox with Apache License 2.0 | 6 votes |
@Override protected Callable<BasicResponse> callable() { return () -> { URIBuilder uri = uri( "/admin/api/v1/", resourceType.getName(), "/", resourceName ); HttpPut request = new HttpPut( uri.build() ); if (resourceFileName != null) { File resource = new File(resourceFileName); if (!resource.exists()) { throw new FileNotFoundException(resourceFileName); } HttpEntity entity = new FileEntity(new File(resourceFileName), ContentType.APPLICATION_JSON); request.setEntity(entity); } return new BasicResponse( execute( request ) ); }; }
Example #4
Source File: HttpSchemeStrategy.java From JVoiceXML with GNU Lesser General Public License v2.1 | 6 votes |
/** * Attach the files given in the parameters. * * @param request * the current request * @param parameters * the parameters * @since 0.7.3 */ private void attachFiles(final HttpUriRequest request, final Collection<KeyValuePair> parameters) { if (!(request instanceof HttpPost)) { return; } final HttpPost post = (HttpPost) request; for (KeyValuePair current : parameters) { final Object value = current.getValue(); if (value instanceof File) { final File file = (File) value; final FileEntity fileEntity = new FileEntity(file, ContentType.create("binary/octet-stream")); post.setEntity(fileEntity); } } }
Example #5
Source File: TestServerBootstrapper.java From java-client-api with Apache License 2.0 | 6 votes |
private void installBootstrapExtension() throws IOException { DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, port), new UsernamePasswordCredentials(username, password)); HttpPut put = new HttpPut("http://" + host + ":" + port + "/v1/config/resources/bootstrap?method=POST&post%3Abalanced=string%3F"); put.setEntity(new FileEntity(new File("src/test/resources/bootstrap.xqy"), "application/xquery")); HttpResponse response = client.execute(put); @SuppressWarnings("unused") HttpEntity entity = response.getEntity(); System.out.println("Installed bootstrap extension. Response is " + response.toString()); }
Example #6
Source File: RawHostedIT.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@Test public void canDisallowDelete() throws Exception { rawClient = rawClient(repos.createRawHosted(HOSTED_REPO + "-no-delete")); HttpEntity testEntity = new FileEntity(resolveTestFile(TEST_CONTENT), TEXT_PLAIN); HttpResponse response = rawClient.put(TEST_CONTENT, testEntity); MatcherAssert.assertThat(response.getStatusLine().getStatusCode(), Matchers.is(HttpStatus.CREATED)); Configuration hostedConfig = repositoryManager.get(HOSTED_REPO + "-no-delete").getConfiguration().copy(); hostedConfig.attributes(STORAGE).set(WRITE_POLICY, DENY); repositoryManager.update(hostedConfig); response = rawClient.delete(TEST_CONTENT); MatcherAssert.assertThat(response.getStatusLine().getStatusCode(), Matchers.is(HttpStatus.BAD_REQUEST)); assertThat(response.getStatusLine().getReasonPhrase(), Matchers.containsString("cannot be deleted")); }
Example #7
Source File: JAXRSClientServerSpringBookTest.java From cxf with Apache License 2.0 | 6 votes |
private void doPost(String endpointAddress, int expectedStatus, String contentType, String inResource, String expectedResource) throws Exception { File input = new File(getClass().getResource(inResource).toURI()); CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(endpointAddress); post.setHeader("Content-Type", contentType); post.setEntity(new FileEntity(input, ContentType.TEXT_XML)); try { CloseableHttpResponse response = client.execute(post); assertEquals(expectedStatus, response.getStatusLine().getStatusCode()); if (expectedStatus != 400) { InputStream expected = getClass().getResourceAsStream(expectedResource); assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)), stripXmlInstructionIfNeeded(EntityUtils.toString(response.getEntity()))); } else { assertTrue(EntityUtils.toString(response.getEntity()) .contains("Cannot find the declaration of element")); } } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } }
Example #8
Source File: JAXRSSoapBookTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testAddGetBookRest() throws Exception { String endpointAddress = "http://localhost:" + PORT + "/test/services/rest/bookstore/books"; File input = new File(getClass().getResource("resources/add_book.txt").toURI()); CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(endpointAddress); post.addHeader("Content-Type", "application/xml"); post.setEntity(new FileEntity(input, ContentType.TEXT_XML)); try { CloseableHttpResponse response = client.execute(post); assertEquals(200, response.getStatusLine().getStatusCode()); InputStream expected = getClass().getResourceAsStream("resources/expected_add_book.txt"); assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)), stripXmlInstructionIfNeeded(EntityUtils.toString(response.getEntity()))); } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } }
Example #9
Source File: HelmPublish.java From gradle-plugins with Apache License 2.0 | 6 votes |
@TaskAction public void run() throws IOException { Project project = getProject(); HelmExtension extension = project.getExtensions().getByType(HelmExtension.class); HelmExtension helm = project.getExtensions().getByType(HelmExtension.class); CredentialsProvider credentialsProvider = getCredentialsProvider(); Set<String> packageNames = helm.getPackageNames(); for (String packageName : packageNames) { try (CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build()) { String url = extension.getRepository() + "/" + packageName + "-" + project.getVersion() + ".tgz"; File helmChart = helm.getOutputFile(packageName); HttpPut post = new HttpPut(url); FileEntity entity = new FileEntity(helmChart); post.setEntity(entity); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() > 299) { throw new IOException( "failed to publish " + packageName + " to " + url + ", reason=" + response.getStatusLine()); } } } }
Example #10
Source File: JAXRSClientServerBookTest.java From cxf with Apache License 2.0 | 6 votes |
private void doAddBook(String address) throws Exception { File input = new File(getClass().getResource("resources/add_book.txt").toURI()); CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(address); post.addHeader("Content-Type", "application/xml"); post.setEntity(new FileEntity(input, ContentType.TEXT_XML)); try { CloseableHttpResponse response = client.execute(post); assertEquals(200, response.getStatusLine().getStatusCode()); InputStream expected = getClass().getResourceAsStream("resources/expected_add_book.txt"); assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)), stripXmlInstructionIfNeeded(EntityUtils.toString(response.getEntity()))); } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } }
Example #11
Source File: JAXRSClientServerBookTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testUpdateBookWithDom() throws Exception { String endpointAddress = "http://localhost:" + PORT + "/bookstore/bookswithdom"; File input = new File(getClass().getResource("resources/update_book.txt").toURI()); CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPut put = new HttpPut(endpointAddress); put.setEntity(new FileEntity(input, ContentType.TEXT_XML)); try { CloseableHttpResponse response = client.execute(put); assertEquals(200, response.getStatusLine().getStatusCode()); String resp = EntityUtils.toString(response.getEntity()); InputStream expected = getClass().getResourceAsStream("resources/update_book.txt"); String s = getStringFromInputStream(expected); //System.out.println(resp); //System.out.println(s); assertTrue(resp.indexOf(s) >= 0); } finally { // Release current connection to the connection pool once you are // done put.releaseConnection(); } }
Example #12
Source File: JAXRSClientServerBookTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testUpdateBookWithJSON() throws Exception { String endpointAddress = "http://localhost:" + PORT + "/bookstore/bookswithjson"; File input = new File(getClass().getResource("resources/update_book_json.txt").toURI()); CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPut put = new HttpPut(endpointAddress); put.setEntity(new FileEntity(input, ContentType.APPLICATION_JSON)); try { CloseableHttpResponse response = client.execute(put); assertEquals(200, response.getStatusLine().getStatusCode()); InputStream expected = getClass().getResourceAsStream("resources/expected_update_book.txt"); assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)), stripXmlInstructionIfNeeded(EntityUtils.toString(response.getEntity()))); } finally { // Release current connection to the connection pool once you are // done put.releaseConnection(); } }
Example #13
Source File: JAXRSClientServerBookTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testUpdateBookFailed() throws Exception { String endpointAddress = "http://localhost:" + PORT + "/bookstore/books"; File input = new File(getClass().getResource("resources/update_book_not_exist.txt").toURI()); CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPut put = new HttpPut(endpointAddress); put.setEntity(new FileEntity(input, ContentType.TEXT_XML)); try { CloseableHttpResponse response = client.execute(put); assertEquals(304, response.getStatusLine().getStatusCode()); } finally { // Release current connection to the connection pool once you are done put.releaseConnection(); } }
Example #14
Source File: RequestParamEndpointTest.java From RoboZombie with Apache License 2.0 | 6 votes |
/** * <p>Test for a {@link Request} with a {@link File} entity.</p> * * @since 1.3.0 */ @Test public final void testFileEntity() throws ParseException, IOException, URISyntaxException { Robolectric.getFakeHttpLayer().interceptHttpRequests(false); String subpath = "/fileentity"; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); File file = new File(classLoader.getResource("LICENSE.txt").toURI()); FileEntity fe = new FileEntity(file, null); stubFor(put(urlEqualTo(subpath)) .willReturn(aResponse() .withStatus(200))); requestEndpoint.fileEntity(file); verify(putRequestedFor(urlEqualTo(subpath)) .withRequestBody(equalTo(EntityUtils.toString(fe)))); }
Example #15
Source File: RequestHandler.java From djl-demo with Apache License 2.0 | 6 votes |
/** Handles URLs predicted as malicious. */ private void blockedMaliciousSiteRequested() { try { HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST, "MAL"); HttpEntity httpEntity = new FileEntity(new File("index.html"), ContentType.WILDCARD); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); bufferedWriter.write(response.getStatusLine().toString()); String headers = "Proxy-agent: FilterProxy/1.0\r\n" + httpEntity.getContentType().toString() + "\r\n" + "Content-Length: " + httpEntity.getContentLength() + "\r\n\r\n"; bufferedWriter.write(headers); // Pass index.html content bufferedWriter.write(EntityUtils.toString(httpEntity)); bufferedWriter.flush(); bufferedWriter.close(); } catch (IOException e) { logger.error("Error writing to client when requested a blocked site", e); } }
Example #16
Source File: HttpClientBasic.java From JavaTutorial with Apache License 2.0 | 5 votes |
public void sendFile(String filePath) throws UnsupportedOperationException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(_targetHost+"/file"); File file = new File(filePath); FileEntity entity = new FileEntity(file, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), _charset)); post.setEntity(entity); CloseableHttpResponse response = client.execute(post); processResponse(response); }
Example #17
Source File: ORRESTTool.java From openregistry with Apache License 2.0 | 5 votes |
private static HttpResponse doPost(DefaultHttpClient httpclient, String url, File file) throws IOException{ HttpPost method = new HttpPost(url); if (file != null){ FileEntity fileEntity = new FileEntity(file, "application/xml; charset=\"UTF-8\""); method.setEntity(fileEntity); } return httpclient.execute(method); }
Example #18
Source File: ORRESTTool.java From openregistry with Apache License 2.0 | 5 votes |
private static HttpResponse doPut(DefaultHttpClient httpclient, String url, File file) throws IOException{ HttpPut method = new HttpPut(url); if (file != null){ FileEntity fileEntity = new FileEntity(file, "application/xml; charset=\"UTF-8\""); method.setEntity(fileEntity); } return httpclient.execute(method); }
Example #19
Source File: TempView.java From AndroidWebServ with Apache License 2.0 | 5 votes |
private HttpEntity renderFromCacheFile(File cacheFile, String tempFile, Map<String, Object> data) throws IOException { if (cacheFile.exists()) { if (DEBUG) Log.d(TAG, "Read from cache " + cacheFile); } else { String html = TempHandler.render(tempFile, data); writeStringToFile(cacheFile, html); if (DEBUG) Log.d(TAG, "Cache to " + cacheFile + " and read it."); } return new FileEntity(cacheFile, "text/html"); }
Example #20
Source File: EntityBuilderTest.java From cs-actions with Apache License 2.0 | 5 votes |
@Test public void buildEntityWithFile() throws Exception { ContentType parsedContentType = ContentType.parse(CONTENT_TYPE); final String fileName = "testFile.txt"; PowerMockito.whenNew(File.class).withArguments(fileName).thenReturn(fileMock); PowerMockito.when(fileMock.exists()).thenReturn(true); HttpEntity httpEntity = entityBuilder .setFilePath(fileName) .setContentType(parsedContentType) .buildEntity(); assertThat(httpEntity, instanceOf(FileEntity.class)); FileEntity fileEntity = (FileEntity) httpEntity; assertEquals(CONTENT_TYPE, fileEntity.getContentType().getValue()); }
Example #21
Source File: ApacheHttpClientDelegate.java From docker-maven-plugin with Apache License 2.0 | 5 votes |
private void setEntityIfGiven(HttpEntityEnclosingRequestBase request, Object entity) { if (entity != null) { if (entity instanceof File) { request.setEntity(new FileEntity((File) entity)); } else { request.setEntity(new StringEntity((String) entity, Charset.defaultCharset())); } } }
Example #22
Source File: FileView.java From AndroidWebServ with Apache License 2.0 | 5 votes |
/** * @details contentType为null时,默认通过{@link MIME#getMimeType(File)}获取且charset为{@link Config#ENCODING} * @param contentType 文件响应类型 * @see BaseView#render(Object, Object) */ @Override public HttpEntity render(HttpRequest request, final File file, String contentType) throws IOException { if (contentType == null) { String mine = MIME.getFromFile(file); contentType = null == mine ? "charset=" + Config.ENCODING : mine + ";charset=" + Config.ENCODING; } if (Config.USE_GZIP && GzipUtil.getSingleton().isGZipSupported(request) && GzipFilter.isGzipFile(file)) { if (Config.USE_FILE_CACHE) { File cacheFile = new File(Config.FILE_CACHE_DIR, file.getName() + Config.EXT_GZIP); if (cacheFile.exists()) { if (DEBUG) Log.d(TAG, "Read from cache " + cacheFile); } else { GzipUtil.getSingleton().gzip(file, cacheFile); if (DEBUG) Log.d(TAG, "Cache to " + cacheFile + " and read it."); } return new GzipFileEntity(cacheFile, contentType, true); } else { if (DEBUG) Log.d(TAG, "Directly return gzip stream for " + file); return new GzipFileEntity(file, contentType, false); } } return new FileEntity(file, contentType); }
Example #23
Source File: Entities.java From RoboZombie with Apache License 2.0 | 5 votes |
/** * <p>Discovers the {@link HttpEntity} which is suitable for wrapping an instance of the given {@link Class}. * This discovery proceeds in the following order by checking the provided generic type:</p> * * <ol> * <li>org.apache.http.{@link HttpEntity} --> returned as-is.</li> * <li>{@code byte[]}, {@link Byte}[] --> {@link ByteArrayEntity}</li> * <li>java.io.{@link File} --> {@link FileEntity}</li> * <li>java.io.{@link InputStream} --> {@link BufferedHttpEntity}</li> * <li>{@link CharSequence} --> {@link StringEntity}</li> * <li>java.io.{@link Serializable} --> {@link SerializableEntity} (with an internal buffer)</li> * </ol> * * @param genericType * a generic {@link Class} to be translated to an {@link HttpEntity} type * <br><br> * @return the {@link Class} of the translated {@link HttpEntity} * <br><br> * @throws NullPointerException * if the supplied generic type was {@code null} * <br><br> * @throws EntityResolutionFailedException * if the given generic {@link Class} failed to be translated to an {@link HttpEntity} type * <br><br> * @since 1.3.0 */ public static final Class<?> resolve(Class<?> genericType) { assertNotNull(genericType); try { Class<?> entityType = HttpEntity.class.isAssignableFrom(genericType)? HttpEntity.class : (byte[].class.isAssignableFrom(genericType) || Byte[].class.isAssignableFrom(genericType))? ByteArrayEntity.class: File.class.isAssignableFrom(genericType)? FileEntity.class : InputStream.class.isAssignableFrom(genericType)? BufferedHttpEntity.class : CharSequence.class.isAssignableFrom(genericType)? StringEntity.class : Serializable.class.isAssignableFrom(genericType)? SerializableEntity.class: null; if(entityType == null) { throw new EntityResolutionFailedException(genericType); } return entityType; } catch(Exception e) { throw (e instanceof EntityResolutionFailedException)? (EntityResolutionFailedException)e :new EntityResolutionFailedException(genericType, e); } }
Example #24
Source File: ApacheHttpClientDelegate.java From jkube with Eclipse Public License 2.0 | 5 votes |
private void setEntityIfGiven(HttpEntityEnclosingRequestBase request, Object entity) { if (entity != null) { if (entity instanceof File) { request.setEntity(new FileEntity((File) entity)); } else { request.setEntity(new StringEntity((String) entity, Charset.defaultCharset())); } } }
Example #25
Source File: StreamsRestActions.java From streamsx.topology with Apache License 2.0 | 5 votes |
static ApplicationBundle uploadBundle(Instance instance, File bundle) throws IOException { Request postBundle = Request.Post(instance.self() + "/applicationbundles"); postBundle.addHeader(AUTH.WWW_AUTH_RESP, instance.connection().getAuthorization()); postBundle.body(new FileEntity(bundle, ContentType.create("application/x-jar"))); JsonObject response = requestGsonResponse(instance.connection().executor, postBundle); UploadedApplicationBundle uab = Element.createFromResponse(instance.connection(), response, UploadedApplicationBundle.class); uab.setInstance(instance); return uab; }
Example #26
Source File: UploadApiV2Test.java From packagedrone with Eclipse Public License 1.0 | 5 votes |
protected CloseableHttpResponse upload ( final URIBuilder uri, final File file ) throws IOException, URISyntaxException { final HttpPut httppost = new HttpPut ( uri.build () ); httppost.setEntity ( new FileEntity ( file ) ); return httpclient.execute ( httppost ); }
Example #27
Source File: UploadApiV3Test.java From packagedrone with Eclipse Public License 1.0 | 5 votes |
protected CloseableHttpResponse upload ( final URIBuilder uri, final File file ) throws IOException, URISyntaxException { final HttpPut http = new HttpPut ( uri.build () ); final String encodedAuth = Base64.getEncoder ().encodeToString ( uri.getUserInfo ().getBytes ( StandardCharsets.ISO_8859_1 ) ); http.setHeader ( HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth ); http.setEntity ( new FileEntity ( file ) ); return httpclient.execute ( http ); }
Example #28
Source File: RawHostedIT.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void canDisallowRedeploy() throws Exception { rawClient = rawClient(repos.createRawHosted(HOSTED_REPO + "-no-redeploy", ALLOW_ONCE)); HttpEntity testEntity = new FileEntity(resolveTestFile(TEST_CONTENT), TEXT_PLAIN); HttpResponse response = rawClient.put(TEST_CONTENT, testEntity); MatcherAssert.assertThat(response.getStatusLine().getStatusCode(), Matchers.is(HttpStatus.CREATED)); response = rawClient.put(TEST_CONTENT, testEntity); MatcherAssert.assertThat(response.getStatusLine().getStatusCode(), Matchers.is(HttpStatus.BAD_REQUEST)); assertThat(response.getStatusLine().getReasonPhrase(), Matchers.containsString("cannot be updated")); }
Example #29
Source File: RawHostedIT.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void canDisallowDeploy() throws Exception { rawClient = rawClient(repos.createRawHosted(HOSTED_REPO + "-no-deploy", DENY)); HttpEntity testEntity = new FileEntity(resolveTestFile(TEST_CONTENT), TEXT_PLAIN); HttpResponse response = rawClient.put(TEST_CONTENT, testEntity); MatcherAssert.assertThat(response.getStatusLine().getStatusCode(), Matchers.is(HttpStatus.BAD_REQUEST)); assertThat(response.getStatusLine().getReasonPhrase(), Matchers.containsString("is read-only")); }
Example #30
Source File: QCRestHttpClient.java From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 | 5 votes |
@Override public void setPostEntity(File file, HttpPost httppost) { httppost.setHeader("Content-Type", "application/octet-stream"); httppost.setHeader("Slug", file.getName()); HttpEntity e = new FileEntity(file, ContentType.create(MIME.getType(file))); httppost.setEntity(e); }