下面列出了怎么用org.apache.commons.httpclient.methods.multipart.StringPart的API类实例代码及写法,或者点击链接到github查看源代码。
public PostRequest buildMultipartPostRequest(File file, String filename, String siteId, String containerId) throws IOException
{
Part[] parts =
{
new FilePart("filedata", file.getName(), file, "text/plain", null),
new StringPart("filename", filename),
new StringPart("description", "description"),
new StringPart("siteid", siteId),
new StringPart("containerid", containerId)
};
MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new HttpMethodParams());
ByteArrayOutputStream os = new ByteArrayOutputStream();
multipartRequestEntity.writeRequest(os);
PostRequest postReq = new PostRequest(UPLOAD_URL, os.toByteArray(), multipartRequestEntity.getContentType());
return postReq;
}
@Test
public void testUploadFile() throws IOException, URISyntaxException {
final HttpClient c = loginWithCookie("administrator", "olat");
final URI uri = UriBuilder.fromUri(getNodeURI()).path("files").build();
// create single page
final URL fileUrl = RepositoryEntriesITCase.class.getResource("singlepage.html");
assertNotNull(fileUrl);
final File file = new File(fileUrl.toURI());
final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", file), new StringPart("filename", file.getName()) };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertEquals(code, 200);
final OlatNamedContainerImpl folder = BCCourseNode.getNodeFolderContainer((BCCourseNode) bcNode, course1.getCourseEnvironment());
final VFSItem item = folder.resolve(file.getName());
assertNotNull(item);
}
@Test
public void testUploadFile() throws IOException, URISyntaxException {
final HttpClient c = loginWithCookie("administrator", "olat");
final URI uri = UriBuilder.fromUri(getNodeURI()).path("files").build();
// create single page
final URL fileUrl = RepositoryEntriesITCase.class.getResource("singlepage.html");
assertNotNull(fileUrl);
final File file = new File(fileUrl.toURI());
final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", file), new StringPart("filename", file.getName()) };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertEquals(code, 200);
final OlatNamedContainerImpl folder = BCCourseNode.getNodeFolderContainer((BCCourseNode) bcNode, course1.getCourseEnvironment());
final VFSItem item = folder.resolve(file.getName());
assertNotNull(item);
}
/**
* <p>This creates a HttpMethod with the message as its payload and image attachment. The message should be a properly formatted JSON
* String (No validation is done on this).</p>
*
* <p>The message can be easily created using the {@link #getJsonPayload(Message)} method.</p>
*
* @param uri The full URI which we will post to
* @param message A properly formatted JSON message. UTF-8 is expected
* @param image A complete instance of ImageAttachment object
* @throws IOException
*/
public HttpMethod getJsonPostForMultipartRequestEntity(String uri, String message, ImageAttachment image) throws IOException {
PostMethod post = new PostMethod(uri);
StringPart bodyPart = new StringPart("json", message);
bodyPart.setContentType("application/json");
FilePart filePart= new FilePart("feedItemFileUpload", image.retrieveObjectFile());
filePart.setContentType(image.retrieveContentType());
Part[] parts = {
bodyPart,
filePart,
};
post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
return post;
}
private void addPartIfNotNull(List<Part> list, String partName, Object partValue)
{
if (partValue != null)
{
list.add(new StringPart(partName, partValue.toString()));
}
}
private void addMultipart_Parts( MultipartPostMethod method, Map<String, String> parameterizedMap){
for (Iterator it = model.getParameters().entrySet().iterator(); it.hasNext();) {
Map.Entry me = (Map.Entry) it.next();
String key = (String) me.getKey();
List values = (List) me.getValue();
StringBuilder sb = new StringBuilder();
int cnt = 0;
for (Iterator it2 = values.iterator(); it2.hasNext();) {
String val = (String) it2.next();
if (cnt != 0) {
sb.append(",");
}
sb.append(val);
cnt++;
}
String parameterizedVal = ParseUtils.getParametizedArg(sb.toString(), parameterizedMap);
if (parameterizedVal.startsWith("@")) {
String path = "";
String contentType = "";
try {
path = parameterizedVal.substring(1, parameterizedVal.length()).trim();
path = path.replace('\\', '/');
contentType = getContentType(getFileExt(path));
File f = new File(path);
method.addPart(new FilePart(key, f, contentType, null));
// postMethod.addParameter("file", f);
// postMethod.addPart(new FilePart("file", f));
} catch (FileNotFoundException fnfe) {
ExceptionHandler.handle(fnfe);
}
} else {
method.addPart(new StringPart(key, parameterizedVal));
}
}
}
@Test
public void testImportCp() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("cp-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "cp-demo.zip"), new StringPart("resourcename", "CP demo"),
new StringPart("displayname", "CP demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("CP demo", re.getDisplayname());
}
@Test
public void testImportTest() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("qti-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "qti-demo.zip"), new StringPart("resourcename", "QTI demo"),
new StringPart("displayname", "QTI demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("QTI demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testImportQuestionnaire() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("questionnaire-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "questionnaire-demo.zip"), new StringPart("resourcename", "Questionnaire demo"),
new StringPart("displayname", "Questionnaire demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("Questionnaire demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testImportWiki() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("wiki-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "wiki-demo.zip"), new StringPart("resourcename", "Wiki demo"),
new StringPart("displayname", "Wiki demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("Wiki demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testImportBlog() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("blog-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "blog-demo.zip"), new StringPart("resourcename", "Blog demo"),
new StringPart("displayname", "Blog demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("Blog demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testPortrait() throws IOException, URISyntaxException {
final URL portraitUrl = RepositoryEntriesITCase.class.getResource("portrait.jpg");
assertNotNull(portraitUrl);
final File portrait = new File(portraitUrl.toURI());
final HttpClient c = loginWithCookie("rest-one", "A6B7C8");
// upload portrait
final String request = "/users/" + id1.getKey() + "/portrait";
final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", portrait), new StringPart("filename", "portrait.jpg") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertEquals(code, 200);
method.releaseConnection();
// check if big and small portraits exist
final DisplayPortraitManager dps = DisplayPortraitManager.getInstance();
final File uploadDir = dps.getPortraitDir(id1);
assertTrue(new File(uploadDir, DisplayPortraitManager.PORTRAIT_SMALL_FILENAME).exists());
assertTrue(new File(uploadDir, DisplayPortraitManager.PORTRAIT_BIG_FILENAME).exists());
// check get portrait
final String getRequest = "/users/" + id1.getKey() + "/portrait";
final GetMethod getMethod = createGet(getRequest, MediaType.APPLICATION_OCTET_STREAM, true);
final int getCode = c.executeMethod(getMethod);
assertEquals(getCode, 200);
final InputStream in = getMethod.getResponseBodyAsStream();
int b = 0;
int count = 0;
while ((b = in.read()) > -1) {
count++;
}
assertEquals(-1, b);// up to end of file
assertTrue(count > 1000);// enough bytes
method.releaseConnection();
}
@Test
public void testImportCp() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("cp-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "cp-demo.zip"), new StringPart("resourcename", "CP demo"),
new StringPart("displayname", "CP demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("CP demo", re.getDisplayname());
}
@Test
public void testImportTest() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("qti-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "qti-demo.zip"), new StringPart("resourcename", "QTI demo"),
new StringPart("displayname", "QTI demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("QTI demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testImportQuestionnaire() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("questionnaire-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "questionnaire-demo.zip"), new StringPart("resourcename", "Questionnaire demo"),
new StringPart("displayname", "Questionnaire demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("Questionnaire demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testImportWiki() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("wiki-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "wiki-demo.zip"), new StringPart("resourcename", "Wiki demo"),
new StringPart("displayname", "Wiki demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("Wiki demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testImportBlog() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("blog-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "blog-demo.zip"), new StringPart("resourcename", "Blog demo"),
new StringPart("displayname", "Blog demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("Blog demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testPortrait() throws IOException, URISyntaxException {
final URL portraitUrl = RepositoryEntriesITCase.class.getResource("portrait.jpg");
assertNotNull(portraitUrl);
final File portrait = new File(portraitUrl.toURI());
final HttpClient c = loginWithCookie("rest-one", "A6B7C8");
// upload portrait
final String request = "/users/" + id1.getKey() + "/portrait";
final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", portrait), new StringPart("filename", "portrait.jpg") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertEquals(code, 200);
method.releaseConnection();
// check if big and small portraits exist
final DisplayPortraitManager dps = DisplayPortraitManager.getInstance();
final File uploadDir = dps.getPortraitDir(id1);
assertTrue(new File(uploadDir, DisplayPortraitManager.PORTRAIT_SMALL_FILENAME).exists());
assertTrue(new File(uploadDir, DisplayPortraitManager.PORTRAIT_BIG_FILENAME).exists());
// check get portrait
final String getRequest = "/users/" + id1.getKey() + "/portrait";
final GetMethod getMethod = createGet(getRequest, MediaType.APPLICATION_OCTET_STREAM, true);
final int getCode = c.executeMethod(getMethod);
assertEquals(getCode, 200);
final InputStream in = getMethod.getResponseBodyAsStream();
int b = 0;
int count = 0;
while ((b = in.read()) > -1) {
count++;
}
assertEquals(-1, b);// up to end of file
assertTrue(count > 1000);// enough bytes
method.releaseConnection();
}
private static RequestEntity buildMultiPartEntity(final IContext context,
final IMendixObject source, Map<String, String> params)
throws IOException, CoreException {
// MWE: don't set contenttype to CONTENTTYPE_MULTIPART; this will be
// done by the request entity and add the boundaries
List<Part> parts = Lists.newArrayList();
// This object self could be a filedocument
if (Core.isSubClassOf(FileDocument.entityName, source.getType())) {
String partName = getFileDocumentFileName(context, source);
if (partName == null || partName.isEmpty())
throw new IllegalArgumentException("The filename of a System.FileDocument in a multipart request should reflect the part name and cannot be empty");
addFilePart(context, partName, source, parts);
}
// .. or one of its children could be a filedocument. This way multiple
// file parts, or specifically named file parts can be send
for (String name : getAssociationsReferingToFileDocs(source
.getMetaObject())) {
IMendixIdentifier subObject = (IMendixIdentifier) source.getValue(
context, name);
params.remove(Utils.getShortMemberName(name));
if (subObject != null) {
addFilePart(context, Utils.getShortMemberName(name),
Core.retrieveId(context, subObject), parts);
}
}
// serialize any other members as 'normal' key value pairs
for (Entry<String, String> e : params.entrySet()) {
parts.add(new StringPart(e.getKey(), e.getValue(),
RestServices.UTF8));
}
params.clear();
return new MultipartRequestEntity(parts.toArray(new Part[0]),
new HttpMethodParams());
}
public static PostMethod sendMultipartPostRequest(String url, String body)
throws IOException {
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
// our handlers ignore key...so we can put anything here
Part[] parts = {new StringPart("body", body)};
postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
httpClient.executeMethod(postMethod);
return postMethod;
}
public static PutMethod sendMultipartPutRequest(String url, String body)
throws IOException {
HttpClient httpClient = new HttpClient();
PutMethod putMethod = new PutMethod(url);
// our handlers ignore key...so we can put anything here
Part[] parts = {new StringPart("body", body)};
putMethod.setRequestEntity(new MultipartRequestEntity(parts, putMethod.getParams()));
httpClient.executeMethod(putMethod);
return putMethod;
}
/**
* Given host, port and schema, send a http POST request to upload the {@link Schema}.
*
* @return <code>true</code> on success.
* <P><code>false</code> on failure.
*/
public static boolean postSchema(@Nonnull String host, int port, @Nonnull Schema schema) {
Preconditions.checkNotNull(host);
Preconditions.checkNotNull(schema);
try {
URL url = new URL("http", host, port, "/schemas");
PostMethod httpPost = new PostMethod(url.toString());
try {
Part[] parts = {new StringPart(schema.getSchemaName(), schema.toSingleLineJsonString())};
MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts, new HttpMethodParams());
httpPost.setRequestEntity(requestEntity);
int responseCode = HTTP_CLIENT.executeMethod(httpPost);
if (responseCode >= 400) {
String response = httpPost.getResponseBodyAsString();
LOGGER.warn("Got error response code: {}, response: {}", responseCode, response);
return false;
}
return true;
} finally {
httpPost.releaseConnection();
}
} catch (Exception e) {
LOGGER.error("Caught exception while posting the schema: {} to host: {}, port: {}", schema.getSchemaName(), host,
port, e);
return false;
}
}
private static Part[] createSendPhotoRequestParts(TelegramBot bot, byte[] image, String imageType, String caption) {
List<Part> partList = new ArrayList<>();
partList.add(new StringPart("chat_id", bot.getChatId()));
partList.add(new FilePart("photo", new ByteArrayPartSource(String.format("image.%s", imageType), image)));
if (StringUtils.isNotBlank(caption)) {
partList.add(new StringPart("caption", caption, "UTF-8"));
}
if (StringUtils.isNotBlank(bot.getParseMode())) {
partList.add(new StringPart("parse_mode", bot.getParseMode()));
}
return partList.toArray(new Part[0]);
}
/**
* This method uploads a content-type asset (ex: wsdl,policy,wadl,swagger)
* to a running G-Reg instance
*
* @param filePath The absolute path of the file
* @param fileVersion Version of the file
* @param fileName Name of the file
* @param shortName Asset shortname mentioned in the RXT
* @param cookieHeader Session cookie
* @throws IOException
*/
public static PostMethod uploadContentTypeAssets(String filePath, String fileVersion, String fileName,
String shortName, String cookieHeader, String apiUrl)
throws IOException {
File file = new File(filePath);
//The api implementation requires fileUpload name in the format
//of shortname_file (ex: wsdl_file)
FilePart fp = new FilePart(shortName + "_file", file);
fp.setContentType(MediaType.TEXT_PLAIN);
String version = fileVersion;
String name = fileName;
StringPart sp1 = new StringPart("file_version", version);
sp1.setContentType(MediaType.TEXT_PLAIN);
StringPart sp2 = new StringPart(shortName + "_file_name", name);
sp2.setContentType(MediaType.TEXT_PLAIN);
//Set file parts and string parts together
final Part[] part = {fp, sp1, sp2};
HttpClient httpClient = new HttpClient();
PostMethod httpMethod = new PostMethod(apiUrl);
httpMethod.addRequestHeader("Cookie", cookieHeader);
httpMethod.addRequestHeader("Accept", MediaType.APPLICATION_JSON);
httpMethod.setRequestEntity(
new MultipartRequestEntity(part, httpMethod.getParams())
);
httpClient.executeMethod(httpMethod);
return httpMethod;
}
/**
* This method uploads a content-type asset (ex: wsdl,policy,wadl,swagger)
* to a running G-Reg instance
*
* @param filePath The absolute path of the file
* @param fileVersion Version of the file
* @param fileName Name of the file
* @param shortName Asset shortname mentioned in the RXT
* @param cookieHeader Session cookie
* @throws IOException
*/
public static PostMethod uploadContentTypeAssets(String filePath, String fileVersion, String fileName,
String shortName, String cookieHeader, String apiUrl)
throws IOException {
File file = new File(filePath);
//The api implementation requires fileUpload name in the format
//of shortname_file (ex: wsdl_file)
FilePart fp = new FilePart(shortName + "_file", file);
fp.setContentType(MediaType.TEXT_PLAIN);
String version = fileVersion;
String name = fileName;
StringPart sp1 = new StringPart("file_version", version);
sp1.setContentType(MediaType.TEXT_PLAIN);
StringPart sp2 = new StringPart(shortName + "_file_name", name);
sp2.setContentType(MediaType.TEXT_PLAIN);
//Set file parts and string parts together
final Part[] part = {fp, sp1, sp2};
HttpClient httpClient = new HttpClient();
PostMethod httpMethod = new PostMethod(apiUrl);
httpMethod.addRequestHeader("Cookie", cookieHeader);
httpMethod.addRequestHeader("Accept", MediaType.APPLICATION_JSON);
httpMethod.setRequestEntity(
new MultipartRequestEntity(part, httpMethod.getParams())
);
httpClient.executeMethod(httpMethod);
return httpMethod;
}
public void upLoadFile(LogFile file, long ticketId)
{
if(!isConnected())
{
PacketSamurai.getUserInterface().log("You have to be connected to use the Remote Log Repository");
return;
}
try
{
PostMethod filePost = new PostMethod(_repoLocation+_repoTicketScript);
Part[] parts =
{
new StringPart("user", this.getUserName()),
new StringPart("pass", this.getPassword()),
new StringPart("id", Long.toString(ticketId)),
new StringPart("req[comment]", file.getComments()),
new StringPart("req[analyzerflags]", Long.toString(file.getAnalyserBitSet())),
new StringPart("req[servertype]", file.getServerType()),
new StringPart("req[protocol]", file.getProtocolName()),
new LogFilePart(file.getName(), file)
};
filePost.setRequestEntity( new MultipartRequestEntity(parts, filePost.getParams()) );
System.out.println("a");
int response = _httpClient.executeMethod(filePost);
System.out.println("b");
if (response != HttpStatus.SC_OK)
{
System.out.println("HTTP "+response);
System.out.println(filePost.getResponseBodyAsString());
}
else
{
file.setRemote(true);
filePost.getResponseHeaders();
System.out.println("OK");
System.out.println(filePost.getResponseBodyAsString());
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
@Override
protected ServerStatus _doIt() {
/* multi server status */
MultiServerStatus status = new MultiServerStatus();
try {
/* upload project contents */
File appPackage = packager.getDeploymentPackage(super.getApplication(), appStore, command);
deployedAppPackageName = PackageUtils.getApplicationPackageType(appStore);
if (appPackage == null) {
status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to read application content", null));
return status;
}
URI targetURI = URIUtil.toURI(target.getUrl());
PutMethod uploadMethod = new PutMethod(targetURI.resolve("/v2/apps/" + getApplication().getGuid() + "/bits?async=true").toString());
uploadMethod.addRequestHeader(new Header("Authorization", "bearer " + target.getCloud().getAccessToken().getString("access_token")));
Part[] parts = {new StringPart(CFProtocolConstants.V2_KEY_RESOURCES, "[]"), new FilePart(CFProtocolConstants.V2_KEY_APPLICATION, appPackage)};
uploadMethod.setRequestEntity(new MultipartRequestEntity(parts, uploadMethod.getParams()));
/* send request */
ServerStatus jobStatus = HttpUtil.executeMethod(uploadMethod);
status.add(jobStatus);
if (!jobStatus.isOK())
return status;
/* long running task, keep track */
int attemptsLeft = MAX_ATTEMPTS;
JSONObject resp = jobStatus.getJsonData();
String taksStatus = resp.getJSONObject(CFProtocolConstants.V2_KEY_ENTITY).getString(CFProtocolConstants.V2_KEY_STATUS);
while (!CFProtocolConstants.V2_KEY_FINISHED.equals(taksStatus) && !CFProtocolConstants.V2_KEY_FAILURE.equals(taksStatus)) {
if (CFProtocolConstants.V2_KEY_FAILED.equals(taksStatus)) {
/* delete the tmp file */
appPackage.delete();
status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Upload failed", null));
return status;
}
if (attemptsLeft == 0) {
/* delete the tmp file */
appPackage.delete();
status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Upload timeout exceeded", null));
return status;
}
/* two seconds */
Thread.sleep(2000);
/* check whether job has finished */
URI jobLocation = targetURI.resolve(resp.getJSONObject(CFProtocolConstants.V2_KEY_METADATA).getString(CFProtocolConstants.V2_KEY_URL));
GetMethod jobRequest = new GetMethod(jobLocation.toString());
ServerStatus confStatus = HttpUtil.configureHttpMethod(jobRequest, target.getCloud());
if (!confStatus.isOK())
return confStatus;
/* send request */
jobStatus = HttpUtil.executeMethod(jobRequest);
status.add(jobStatus);
if (!jobStatus.isOK())
return status;
resp = jobStatus.getJsonData();
taksStatus = resp.getJSONObject(CFProtocolConstants.V2_KEY_ENTITY).getString(CFProtocolConstants.V2_KEY_STATUS);
--attemptsLeft;
}
if (CFProtocolConstants.V2_KEY_FAILURE.equals(jobStatus)) {
status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to upload application bits", null));
return status;
}
/* delete the tmp file */
appPackage.delete();
return status;
} catch (Exception e) {
String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
logger.error(msg, e);
status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
return status;
}
}
@SuppressWarnings("deprecation")
public MultiPartRequest build() throws IOException
{
List<Part> parts = new ArrayList<>();
if (fileData != null)
{
FilePart fp = new FilePart("filedata", fileData.getFileName(), fileData.getFile(), fileData.getMimetype(), null);
// Get rid of the default values added upon FilePart instantiation
fp.setCharSet(fileData.getEncoding());
fp.setContentType(fileData.getMimetype());
parts.add(fp);
addPartIfNotNull(parts, "name", fileData.getFileName());
}
addPartIfNotNull(parts, "relativepath", relativePath);
addPartIfNotNull(parts, "updatenoderef", updateNodeRef);
addPartIfNotNull(parts, "description", description);
addPartIfNotNull(parts, "contenttype", contentTypeQNameStr);
addPartIfNotNull(parts, "aspects", getCommaSeparated(aspects));
addPartIfNotNull(parts, "majorversion", majorVersion);
addPartIfNotNull(parts, "overwrite", overwrite);
addPartIfNotNull(parts, "autorename", autoRename);
addPartIfNotNull(parts, "nodetype", nodeType);
addPartIfNotNull(parts, "renditions", getCommaSeparated(renditionIds));
HttpMethodParams params = new HttpMethodParams();
if (!properties.isEmpty())
{
for (String propertyName : properties.keySet())
{
Serializable expected = properties.get(propertyName);
if (expected instanceof List)
{
List<String> multipleValues = (List<String>) expected;
for (String value : multipleValues)
{
{
parts.add(new StringPart(propertyName, value));
}
}
}
else
{
parts.add(new StringPart(propertyName, (String) expected));
}
}
}
MultipartRequestEntity req = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), new HttpMethodParams());
ByteArrayOutputStream os = new ByteArrayOutputStream();
req.writeRequest(os);
return new MultiPartRequest(os.toByteArray(), req.getContentType(), req.getContentLength());
}
/**
*
*/
private Map<String, String> sendToZoho(String zohoUrl, String nodeUuid, String lang) throws PathNotFoundException,
AccessDeniedException, RepositoryException, DatabaseException, IOException, OKMException {
Map<String, String> result = new HashMap<String, String>();
File tmp = null;
try {
String path = OKMRepository.getInstance().getNodePath(null, nodeUuid);
String fileName = PathUtils.getName(path);
tmp = File.createTempFile("okm", ".tmp");
InputStream is = OKMDocument.getInstance().getContent(null, path, false);
Document doc = OKMDocument.getInstance().getProperties(null, path);
FileOutputStream fos = new FileOutputStream(tmp);
IOUtils.copy(is, fos);
fos.flush();
fos.close();
String id = UUID.randomUUID().toString();
String saveurl = Config.APPLICATION_BASE + "/extension/ZohoFileUpload";
Part[] parts = {new FilePart("content", tmp), new StringPart("apikey", Config.ZOHO_API_KEY),
new StringPart("output", "url"), new StringPart("mode", "normaledit"),
new StringPart("filename", fileName), new StringPart("skey", Config.ZOHO_SECRET_KEY),
new StringPart("lang", lang), new StringPart("id", id),
new StringPart("format", getFormat(doc.getMimeType())), new StringPart("saveurl", saveurl)};
PostMethod filePost = new PostMethod(zohoUrl);
filePost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
int status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK) {
log.debug("OK: " + filePost.getResponseBodyAsString());
ZohoToken zot = new ZohoToken();
zot.setId(id);
zot.setUser(getThreadLocalRequest().getRemoteUser());
zot.setNode(nodeUuid);
zot.setCreation(Calendar.getInstance());
ZohoTokenDAO.create(zot);
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(filePost.getResponseBodyAsStream()));
String line;
while ((line = rd.readLine()) != null) {
if (line.startsWith("URL=")) {
result.put("url", line.substring(4));
result.put("id", id);
break;
}
}
rd.close();
} else {
String error = HttpStatus.getStatusText(status) + "\n\n" + filePost.getResponseBodyAsString();
log.error("ERROR: {}", error);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMZohoService, ErrorCode.CAUSE_Zoho), error);
}
} finally {
FileUtils.deleteQuietly(tmp);
}
return result;
}
private MockMultipartHttpServletRequest createMultipartHttpRequest(StreamPipe pipe, boolean addAntiVirusParts, boolean antiVirusLastPartFailed) throws Exception {
MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
request.setContentType("multipart/mixed;boundary=gc0p4Jq0M2Yt08jU534c0p");
List<Part> parts = new ArrayList<Part>();
String string = "<hello>test</hello>";
StringPart stringPart = new StringPart("string1", string);
parts.add(stringPart);
URL url = ClassUtils.getResourceURL(this, "/Documents/doc001.pdf");
File file = new File(url.toURI());
FilePart filePart = new FilePart("file1", file.getName(), file);
parts.add(filePart);
if (addAntiVirusParts) {
StringPart antiVirusPassedPart = new StringPart(
pipe.getAntiVirusPartName(),
pipe.getAntiVirusPassedMessage());
parts.add(antiVirusPassedPart);
}
URL url2 = ClassUtils.getResourceURL(this, "/Documents/doc002.pdf");
File file2 = new File(url2.toURI());
FilePart filePart2 = new FilePart("file2", file2.getName(), file2);
parts.add(filePart2);
if (addAntiVirusParts) {
String antiVirusLastPartMessage;
if (antiVirusLastPartFailed) {
antiVirusLastPartMessage = "Fail";
if (antiVirusLastPartMessage.equalsIgnoreCase(
pipe.getAntiVirusPassedMessage())) {
throw new Exception("fail message ["
+ antiVirusLastPartMessage
+ "] must differ from pass message ["
+ pipe.getAntiVirusPassedMessage() + "]");
}
} else {
antiVirusLastPartMessage = pipe
.getAntiVirusPassedMessage();
}
StringPart antiVirusPassedPart2 = new StringPart(
pipe.getAntiVirusPartName(),
antiVirusLastPartMessage);
parts.add(antiVirusPassedPart2);
}
Part allParts[] = new Part[parts.size()];
allParts = parts.toArray(allParts);
MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
allParts, new PostMethod().getParams());
ByteArrayOutputStream requestContent = new ByteArrayOutputStream();
multipartRequestEntity.writeRequest(requestContent);
request.setContent(requestContent.toByteArray());
request.setContentType(multipartRequestEntity.getContentType());
return request;
}