org.apache.commons.httpclient.methods.multipart.FilePart Java Examples

The following examples show how to use org.apache.commons.httpclient.methods.multipart.FilePart. 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: CoursesFoldersITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #2
Source File: UploadWebScriptTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: WebAPI.java    From h2o-2 with Apache License 2.0 6 votes vote down vote up
/**
 * Imports a model from a JSON file.
 */
public static void importModel() throws Exception {
  // Upload file to H2O
  HttpClient client = new HttpClient();
  PostMethod post = new PostMethod(URL + "/Upload.json?key=" + JSON_FILE.getName());
  Part[] parts = { new FilePart(JSON_FILE.getName(), JSON_FILE) };
  post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
  if( 200 != client.executeMethod(post) )
    throw new RuntimeException("Request failed: " + post.getStatusLine());
  post.releaseConnection();

  // Parse the key into a model
  GetMethod get = new GetMethod(URL + "/2/ImportModel.json?" //
      + "destination_key=MyImportedNeuralNet&" //
      + "type=NeuralNetModel&" //
      + "json=" + JSON_FILE.getName());
  if( 200 != client.executeMethod(get) )
    throw new RuntimeException("Request failed: " + get.getStatusLine());
  get.releaseConnection();
}
 
Example #4
Source File: ChatterCommands.java    From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * <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;
}
 
Example #5
Source File: UploadServletTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private MockHttpServletRequest getMultipartRequest( ) throws Exception
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    byte [ ] fileContent = new byte [ ] {
            1, 2, 3
    };
    Part [ ] parts = new Part [ ] {
        new FilePart( "file1", new ByteArrayPartSource( "file1", fileContent ) )
    };
    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( parts, new PostMethod( ).getParams( ) );
    // Serialize request body
    ByteArrayOutputStream requestContent = new ByteArrayOutputStream( );
    multipartRequestEntity.writeRequest( requestContent );
    // Set request body to HTTP servlet request
    request.setContent( requestContent.toByteArray( ) );
    // Set content type to HTTP servlet request (important, includes Mime boundary string)
    request.setContentType( multipartRequestEntity.getContentType( ) );
    request.setMethod( "POST" );
    return request;
}
 
Example #6
Source File: CoursesFoldersITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #7
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #8
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #9
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #10
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #11
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #12
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #13
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #14
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #15
Source File: RestConsumer.java    From RestServices with Apache License 2.0 5 votes vote down vote up
private static void addFilePart(final IContext context, String partname,
		final IMendixObject source, List<Part> parts) throws IOException {
	ByteArrayPartSource p = new ByteArrayPartSource(
			getFileDocumentFileName(context, source),
			IOUtils.toByteArray(Core.getFileDocumentContent(context, source)));
	parts.add(new FilePart(partname, p));
}
 
Example #16
Source File: Telegram.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
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]);
}
 
Example #17
Source File: FileUploadWithAttachmentUtil.java    From product-es with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #18
Source File: FileUploadWithAttachmentUtil.java    From product-es with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #19
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #20
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #21
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #22
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #23
Source File: OnlyHttpClient3Upload.java    From oim-fx with MIT License 5 votes vote down vote up
public String upload(String http, String tagName, File file, Map<String, String> dataMap) {
	String body = null;
	PostMethod filePost = new PostMethod(http);

	try {
		if (dataMap != null) {
			// 通过以下方法可以模拟页面参数提交
			// filePost.setParameter("name", "中文");
			Iterator<Map.Entry<String, String>> i = dataMap.entrySet().iterator();
			while (i.hasNext()) {
				Map.Entry<String, String> entry = i.next();
				String inputName = (String) entry.getKey();
				String inputValue = (String) entry.getValue();
				filePost.setParameter(inputName, inputValue);
			}
		}

		Part[] parts = { new FilePart(file.getName(), file) };
		filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
		HttpClient client = new HttpClient();
		client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
		int status = client.executeMethod(filePost);
		body = filePost.getResponseBodyAsString();
		if (status == HttpStatus.SC_OK) {// 上传成功
		} else {// 上传失败
		}
	} catch (Exception ex) {
		ex.printStackTrace();
	} finally {
		filePost.releaseConnection();
	}
	return body;
}
 
Example #24
Source File: DifidoClient.java    From difido-reports with Apache License 2.0 5 votes vote down vote up
public void addFile(final int executionId, final String uid, final File file) throws Exception {
	PostMethod method = new PostMethod(baseUri + "executions/" + executionId + "/details/" + uid + "/file/");
	Part[] parts = new Part[] { new FilePart("file", file) };
	method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
	final int responseCode = client.executeMethod(method);
	handleResponseCode(method, responseCode);
}
 
Example #25
Source File: CustomModelImportTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public PostRequest buildMultipartPostRequest(File file) throws IOException
{
    Part[] parts = { new FilePart("filedata", file.getName(), file, "application/zip", null) };

    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;
}
 
Example #26
Source File: MultipartPostMethod.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Adds a binary file part
 * 
 * @param parameterName The name of the parameter
 * @param parameterFile The name of the file.
 * @throws FileNotFoundException If the file cannot be found.
 */
public void addParameter(String parameterName, File parameterFile) 
throws FileNotFoundException {
    LOG.trace("enter MultipartPostMethod.addParameter(String parameterName, "
        + "File parameterFile)");
    Part param = new FilePart(parameterName, parameterFile);
    parameters.add(param);
}
 
Example #27
Source File: BusinessJob.java    From http4e with Apache License 2.0 5 votes vote down vote up
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));

      }
   }
}
 
Example #28
Source File: OnlyHttpClient3Upload.java    From oim-fx with MIT License 4 votes vote down vote up
public static String uploads(String http, String tagName, List<File> files, Map<String, String> dataMap) {
	String body = null;
	PostMethod filePost = new PostMethod(http);

	try {
		filePost.setRequestHeader("Content-Type", "application/octet-stream;charset=UTF-8");
		if (dataMap != null) {
			// 通过以下方法可以模拟页面参数提交
			// filePost.setParameter("name", "中文");
			Iterator<Map.Entry<String, String>> i = dataMap.entrySet().iterator();
			while (i.hasNext()) {
				Map.Entry<String, String> entry = i.next();
				String inputName = (String) entry.getKey();
				String inputValue = (String) entry.getValue();
				filePost.setParameter(inputName, inputValue);
			}
		}
		if (null != files && !files.isEmpty()) {
			int size = files.size();
			Part[] parts = new Part[size];
			for (int i = 0; i < size; i++) {
				File file = files.get(i);
				parts[i] = new FilePart(file.getName(), file);
			}
			filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
		}

		HttpClient client = new HttpClient();
		client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
		int status = client.executeMethod(filePost);
		body = filePost.getResponseBodyAsString();
		System.out.println(body);
		if (status == HttpStatus.SC_OK) {// 上传成功
		} else {// 上传失败
		}
	} catch (Exception ex) {
		ex.printStackTrace();
	} finally {
		filePost.releaseConnection();
	}
	return body;
}
 
Example #29
Source File: UploadBitsCommand.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@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;
	}
}
 
Example #30
Source File: MultiPartBuilder.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@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());
}