List of usage examples for org.apache.http.entity FileEntity FileEntity
public FileEntity(File file)
From source file:com.glodon.paas.document.api.PerformanceRestAPITest.java
/** * ?/*from w w w . j a v a 2s . co m*/ */ @Test public void testLockFile() throws IOException { //create project String projectName = "project_" + UUIDUtil.getUUIDStr(); File project = null; try { project = createSimpleProject(projectName); } catch (UnsupportedEncodingException e1) { fail(); } //upload file java.io.File file = new java.io.File("src/test/resources/file/testupload.file"); if (!file.exists()) { file = new java.io.File(tempUploadFile); } String uploadUrl = "/file/" + project.getId() + "?upload&position=0&type=id&fileName=" + file.getName(); HttpPost post = createPost(uploadUrl); post.setHeader("content-type", "application/octet-stream"); FileEntity entity = new FileEntity(file); post.setEntity(entity); String response = simpleCall(post); assertNotNull(response); File resultFile = convertString2Obj(response, new TypeReference<File>() { }); //lock file String url = "/file/" + resultFile.getId() + "?lock&type=id"; response = simpleCall(createPut(url)); assertNotNull(response); Map<String, Object> map = convertString2Obj(response, new TypeReference<Map<String, Object>>() { }); assertTrue(map.containsKey("lockTime")); assertTrue(map.containsKey("owner")); }
From source file:com.glodon.paas.document.api.PerformanceRestAPITest.java
/** * ?/*from ww w. j a va2 s .co m*/ */ @Test public void testUnlockFile() throws IOException { //create project String projectName = "project_" + UUIDUtil.getUUIDStr(); File project = null; try { project = createSimpleProject(projectName); } catch (UnsupportedEncodingException e1) { fail(); } //upload file java.io.File file = new java.io.File("src/test/resources/file/testupload.file"); if (!file.exists()) { file = new java.io.File(tempUploadFile); } String uploadUrl = "/file/" + project.getId() + "?upload&position=0&type=id&fileName=" + file.getName(); HttpPost post = createPost(uploadUrl); post.setHeader("content-type", "application/octet-stream"); FileEntity entity = new FileEntity(file); post.setEntity(entity); String response = simpleCall(post); assertNotNull(response); File resultFile = convertString2Obj(response, new TypeReference<File>() { }); //lock file String url = "/file/" + resultFile.getId() + "?lock&type=id"; simpleCall(createPut(url)); //unlock file url = "/file/" + resultFile.getId() + "?unlock&type=id"; response = simpleCall(createPut(url)); assertNotNull(response); Map<String, String> map = convertString2Obj(response, new TypeReference<Map<String, String>>() { }); assertEquals("success", map.get("result")); }
From source file:com.github.sardine.impl.SardineImpl.java
@Override public void put(String url, File localFile, String contentType) throws IOException { FileEntity content = new FileEntity(localFile); //don't use ExpectContinue for repetable FileEntity, some web server (IIS for exmaple) may return 400 bad request after retry this.put(url, content, contentType, false); }
From source file:com.globalsight.connector.mindtouch.util.MindTouchHelper.java
public String putPageFile(String filePath, String targetLocale, String sourceLocale, MindTouchPageInfo pageInfo) {/*from w w w . j a va 2s . c o m*/ if (!isTargetServerExist(targetLocale) && !mtc.getIsPostToSourceServer()) { return null; } CloseableHttpClient httpClient = getHttpClient(); String entityContent = null; int count = 0; String path = null; File picFile = null; while (entityContent == null && count < 3) { count++; HttpResponse response = null; try { String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1); String tempFileName = URLEncoder.encode(fileName); tempFileName = URLEncoder.encode(tempFileName); path = getNewPath(pageInfo, sourceLocale, targetLocale); String url = getPutServerUrl(targetLocale) + "/@api/deki/pages/=" + path + "/files/=" + tempFileName; if (count > 1) { logger.info("Retry to putPageFile for url: " + url); } HttpPut httpput = getHttpPut(url, targetLocale); picFile = new File(filePath); FileEntity reqEntity = new FileEntity(picFile); httpput.setEntity(reqEntity); response = httpClient.execute(httpput); if (response.getEntity() != null) { entityContent = EntityUtils.toString(response.getEntity()); } if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) { logger.error("Fail to put file back to MindTouch server for file '" + filePath + "' : " + entityContent); } } catch (Exception e) { logger.error("Fail to put file back to MindTouch server for file '" + filePath + "'.", e); } finally { consumeQuietly(response); } } if (picFile != null && picFile.exists()) { picFile.delete(); } return entityContent; }
From source file:pt.meocloud.sdk.MeoCloudImpl.java
/** * Max file size: 2048MB//from w w w .ja va 2 s . c o m * Disallowed characters: +*<>:"/\|?* * */ @Override public MeoCloudResponse<Metadata> uploadFile(String filePath, String path, Boolean overwrite, String parentRevision) { try { String builderPath = String.format("/%s/%s/%s%s", MEOCLOUD_API_VERSION, MEOCLOUD_API_METHOD_FILES, apiMode.getCode(), path); URIBuilder builder = new URIBuilder(); builder.setScheme(MEOCLOUD_SCHEME); builder.setHost(MEOCLOUD_API_CONTENT_ENDPOINT); builder.setPath(builderPath); List<NameValuePair> parameters = new LinkedList<>(); if (overwrite != null) { builder.addParameter(OVERWRITE_PARAM, overwrite.toString()); parameters.add(new BasicNameValuePair(OVERWRITE_PARAM, overwrite.toString())); } if (parentRevision != null) { builder.addParameter(PARENT_REV_PARAM, parentRevision); parameters.add(new BasicNameValuePair(PARENT_REV_PARAM, parentRevision)); } String apiCall = builder.build().toString(); HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(apiCall); signHttpRequest(post, "POST", apiCall, parameters); FileEntity fileEntity = new FileEntity(new File(filePath)); // fileEntity.setChunked(true); post.setEntity(fileEntity); HttpResponse response = client.execute(post); Integer statusCode = response.getStatusLine().getStatusCode(); MeoCloudResponse<Metadata> meoCloudResponse = new MeoCloudResponse<>(); meoCloudResponse.setCode(statusCode); if (statusCode == HttpStatus.SC_OK) { String responseBody = convertStreamToString(response.getEntity().getContent()); Metadata metatada = Metadata.fromJson(responseBody, Metadata.class); meoCloudResponse.setResponse(metatada); } else process(meoCloudResponse, statusCode); } catch (Exception e) { log.error("Exception caught uploading file.", e); } return null; }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java
/** * Creates the entity data to be sent./*from ww w.jav a2 s .co m*/ * <p> * If there is a file entry with a non-empty MIME type we use that to * set the request Content-Type header, otherwise we default to whatever * header is present from a Header Manager. * <p> * If the content charset {@link #getContentEncoding()} is null or empty * we use the HC4 default provided by {@link HTTP#DEF_CONTENT_CHARSET} which is * ISO-8859-1. * * @param entity to be processed, e.g. PUT or PATCH * @return the entity content, may be empty * @throws UnsupportedEncodingException for invalid charset name * @throws IOException cannot really occur for ByteArrayOutputStream methods */ protected String sendEntityData(HttpEntityEnclosingRequestBase entity) throws IOException { // Buffer to hold the entity body StringBuilder entityBody = new StringBuilder(1000); boolean hasEntityBody = false; final HTTPFileArg[] files = getHTTPFiles(); // Allow the mimetype of the file to control the content type // This is not obvious in GUI if you are not uploading any files, // but just sending the content of nameless parameters final HTTPFileArg file = files.length > 0 ? files[0] : null; String contentTypeValue = null; if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) { contentTypeValue = file.getMimeType(); entity.setHeader(HEADER_CONTENT_TYPE, contentTypeValue); // we provide the MIME type here } // Check for local contentEncoding (charset) override; fall back to default for content body // we do this here rather so we can use the same charset to retrieve the data final String charset = getContentEncoding(HTTP.DEF_CONTENT_CHARSET.name()); // Only create this if we are overriding whatever default there may be // If there are no arguments, we can send a file as the body of the request if (!hasArguments() && getSendFileAsPostBody()) { hasEntityBody = true; // If getSendFileAsPostBody returned true, it's sure that file is not null File reservedFile = FileServer.getFileServer().getResolvedFile(files[0].getPath()); FileEntity fileRequestEntity = new FileEntity(reservedFile); // no need for content-type here entity.setEntity(fileRequestEntity); } // If none of the arguments have a name specified, we // just send all the values as the entity body else if (getSendParameterValuesAsPostBody()) { hasEntityBody = true; // Just append all the parameter values, and use that as the entity body StringBuilder entityBodyContent = new StringBuilder(); for (JMeterProperty jMeterProperty : getArguments()) { HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue(); // Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue if (charset != null) { entityBodyContent.append(arg.getEncodedValue(charset)); } else { entityBodyContent.append(arg.getEncodedValue()); } } StringEntity requestEntity = new StringEntity(entityBodyContent.toString(), charset); entity.setEntity(requestEntity); } // Check if we have any content to send for body if (hasEntityBody) { // If the request entity is repeatable, we can send it first to // our own stream, so we can return it final HttpEntity entityEntry = entity.getEntity(); if (entityEntry.isRepeatable()) { entityBody.append("<actual file content, not shown here>"); } else { // this probably cannot happen entityBody.append("<RequestEntity was not repeatable, cannot view what was sent>"); } } return entityBody.toString(); // may be the empty string }
From source file:org.fcrepo.integration.http.api.FedoraLdpIT.java
License:asdf
/** * Ensure that the objects can be created with a Digest header * with a SHA1 sum of the binary content *///from w w w . j a v a 2 s .c o m @Test public void testIngestWithBinaryAndChecksum() { final HttpPost method = postObjMethod(); final File img = new File("src/test/resources/test-objects/img.png"); method.addHeader(CONTENT_TYPE, "application/octet-stream"); method.addHeader("Digest", "SHA=f0b632679fab4f22e031010bd81a3b0544294730"); method.addHeader(LINK, NON_RDF_SOURCE_LINK_HEADER); method.setEntity(new FileEntity(img)); assertEquals("Didn't get a CREATED response!", CREATED.getStatusCode(), getStatus(method)); }
From source file:org.fcrepo.integration.http.api.FedoraLdpIT.java
License:asdf
/** * Ensure that the objects cannot be created when a Digest header * contains a SHA1 sum that does not match the uploaded binary * content/* w ww.ja va2s. c om*/ */ @Test public void testIngestWithBinaryAndChecksumMismatch() { final HttpPost method = postObjMethod(); final File img = new File("src/test/resources/test-objects/img.png"); method.addHeader(CONTENT_TYPE, "application/octet-stream"); method.addHeader("Digest", "SHA=fedoraicon"); method.addHeader(LINK, NON_RDF_SOURCE_LINK_HEADER); method.setEntity(new FileEntity(img)); assertEquals("Should be a 409 Conflict!", CONFLICT.getStatusCode(), getStatus(method)); }
From source file:org.fcrepo.integration.http.api.FedoraLdpIT.java
License:asdf
/** * Ensure that the a malformed Digest header returns a 400 Bad Request *///from w w w . j a v a 2 s. co m @Test public void testIngestWithBinaryAndMalformedDigestHeader() { final HttpPost method = postObjMethod(); final File img = new File("src/test/resources/test-objects/img.png"); method.addHeader(CONTENT_TYPE, "application/octet-stream"); method.addHeader("Digest", "md5=not a valid hash,SHA:thisisbadtoo"); method.addHeader(LINK, NON_RDF_SOURCE_LINK_HEADER); method.setEntity(new FileEntity(img)); assertEquals("Should be a 400 BAD REQUEST!", BAD_REQUEST.getStatusCode(), getStatus(method)); }