Example usage for org.apache.http.entity.mime.content FileBody FileBody

List of usage examples for org.apache.http.entity.mime.content FileBody FileBody

Introduction

In this page you can find the example usage for org.apache.http.entity.mime.content FileBody FileBody.

Prototype

public FileBody(final File file) 

Source Link

Usage

From source file:hu.sztaki.lpds.portal.util.stream.HttpClient.java

/**
 * File upload/*w  w  w. j a v a 2s  .c o m*/
 * @param pFile file to be uploaded
 * @param uploadName upload naem
 * @param pValue parameters used during the connection
 * @return http answer code
 * @throws java.lang.Exception communication error
 */
public int fileUpload(File pFile, String uploadName, Hashtable pValue) throws Exception {
    int res = 0;
    MultipartEntity reqEntity = new MultipartEntity();
    // file parameter
    if (uploadName != null) {
        FileBody bin = new FileBody(pFile);
        reqEntity.addPart(uploadName, bin);
    }
    //text parameters
    Enumeration<String> enm = pValue.keys();
    String key;
    while (enm.hasMoreElements()) {
        key = enm.nextElement();
        reqEntity.addPart(key, new StringBody("" + pValue.get(key)));
    }
    httpPost.setEntity(reqEntity);

    HttpResponse response = httpclient.execute(httpPost);
    HttpEntity resEntity = response.getEntity();
    res = response.getStatusLine().getStatusCode();
    close();
    return res;
}

From source file:eu.prestoprime.plugin.mserve.client.MServeClient.java

/**
 * Uploads a file on MServe and returns its fileID
 * // ww  w .j a v  a2  s. c om
 * @param file
 * @return
 * @throws MServeException
 */
public String uploadFile(File file) throws MServeException {
    try {
        URL url = new URL(host + "/auths/" + serviceID + "/mfiles/");

        logger.debug("MServe URL: " + url.toString());

        HttpClient client = new DefaultHttpClient();
        HttpUriRequest request = new HttpPost(url.toString());
        request.setHeader("Accept", "application/json");

        MultipartEntity part = new MultipartEntity();
        part.addPart("file", new FileBody(file));

        ((HttpPost) request).setEntity(part);

        HttpEntity stream = client.execute(request).getEntity();
        InputStream istream = stream.getContent();

        BufferedReader buf = new BufferedReader(new InputStreamReader(istream));
        String line;
        StringBuffer sb = new StringBuffer();
        while (null != ((line = buf.readLine()))) {
            sb.append(line.trim());
        }
        buf.close();
        istream.close();

        logger.debug(sb.toString());

        JSONObject response = new JSONObject(sb.toString());

        return response.getString("id");
    } catch (MalformedURLException e) {
        throw new MServeException("Bad REST interface...");
    } catch (IOException e) {
        throw new MServeException("Unable to make IO...");
    } catch (JSONException e) {
        throw new MServeException("Bad JSON response...");
    }
}

From source file:org.apache.sling.testing.tools.osgi.WebconsoleClient.java

/** Install a bundle using the Felix webconsole HTTP interface, with a specific start level */
public void installBundle(File f, boolean startBundle, int startLevel) throws Exception {

    // Setup request for Felix Webconsole bundle install
    final MultipartEntity entity = new MultipartEntity();
    entity.addPart("action", new StringBody("install"));
    if (startBundle) {
        entity.addPart("bundlestart", new StringBody("true"));
    }/*from ww  w .ja v  a 2 s .c om*/
    entity.addPart("bundlefile", new FileBody(f));

    if (startLevel > 0) {
        entity.addPart("bundlestartlevel", new StringBody(String.valueOf(startLevel)));
        log.info("Installing bundle {} at start level {}", f.getName(), startLevel);
    } else {
        log.info("Installing bundle {} at default start level", f.getName());
    }

    // Console returns a 302 on success (and in a POST this
    // is not handled automatically as per HTTP spec)
    executor.execute(builder.buildPostRequest(CONSOLE_BUNDLES_PATH).withCredentials(username, password)
            .withEntity(entity)).assertStatus(302);
}

From source file:com.glodon.paas.document.api.FileRestAPITest.java

@Test
public void uploadFolderForMultiPart() throws IOException {
    File parentFile = getFile(simpleCall(createPost("/file/1?folder")), null);
    java.io.File file = new ClassPathResource("file/testupload.file").getFile();
    String uploadUrl = "/file/" + file.getName() + "?upload&position=0&type=path";
    HttpPost post = createPost(uploadUrl);
    FileBody fileBody = new FileBody(file);
    StringBody sbId = new StringBody(parentFile.getId());
    StringBody sbSize = new StringBody(String.valueOf(file.length()));
    StringBody sbName = new StringBody("aa/" + file.getName());
    StringBody sbPosition = new StringBody("0");
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("fileId", sbId);
    entity.addPart("size", sbSize);
    entity.addPart("fileName", sbName);
    entity.addPart("position", sbPosition);
    entity.addPart("file", fileBody);
    post.setEntity(entity);//from   ww  w  . j  ava 2 s . co  m

    File uploadFile = getFile(simpleCall(post), null);
    assertEquals(file.getName(), uploadFile.getFullName());
    assertFalse(uploadFile.isFolder());
    File aaFolder = getFile(simpleCall(createGet("/file/1/aa?meta")), "meta");
    assertEquals(aaFolder.getId(), uploadFile.getParentId());
}

From source file:com.glodon.paas.document.api.PerformanceRestAPITest.java

/**
 *  multipart// w w  w  .  j a va  2 s. c  om
 */
@Test
public void testUploadFileForMultiPart() throws IOException {
    File parentFile = createFile("testUpload");
    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/" + file.getName() + "?upload&position=0&type=path";
    HttpPost post = createPost(uploadUrl);
    FileBody fileBody = new FileBody(file);
    StringBody sbId = new StringBody(parentFile.getId());
    StringBody sbSize = new StringBody(String.valueOf(file.length()));
    StringBody sbName = new StringBody(file.getName());
    StringBody sbPosition = new StringBody("0");

    MultipartEntity entity = new MultipartEntity();
    entity.addPart("fileId", sbId);
    entity.addPart("size", sbSize);
    entity.addPart("fileName", sbName);
    entity.addPart("position", sbPosition);
    entity.addPart("file", fileBody);
    post.setEntity(entity);
    String response = simpleCall(post);
    assertNotNull(response);
    File resultFile = convertString2Obj(response, new TypeReference<File>() {
    });
    assertEquals(file.getName(), resultFile.getFullName());
    assertTrue(file.length() == resultFile.getSize());
}

From source file:uk.co.jarofgreen.cityoutdoors.API.BaseCall.java

protected void addFileToCall(String key, String fileName) {
    multipartEntity.addPart(key, new FileBody(new File(fileName)));
}

From source file:nya.miku.wishmaster.http.ExtendedMultipartBuilder.java

private ExtendedMultipartBuilder addFile(String key, File value, final int randomTail) {
    return addPart(key, new FileBody(value) {
        @Override//  w w  w.j  ava2  s  .c  o m
        public long getContentLength() {
            return super.getContentLength() + randomTail;
        }

        @Override
        public void writeTo(OutputStream out) throws IOException {
            super.writeTo(out);
            if (randomTail > 0) {
                byte[] buf = new byte[randomTail];
                getRandom().nextBytes(buf);
                out.write(buf);
            }
        }
    });
}

From source file:com.github.mhendred.face4j.CopyOfResponderImpl.java

/**
 * @see {@link Responder#doPost(File, URI, List)}
 *///from   w ww . j a  v  a 2  s.c  o  m
public String doPost(final File file, final URI uri, final List<NameValuePair> params)
        throws FaceClientException, FaceServerException {
    try {
        final MultipartEntity entity = new MultipartEntity();

        entity.addPart("image", new FileBody(file));

        try {
            for (NameValuePair nvp : params) {
                entity.addPart(nvp.getName(), new StringBody(nvp.getValue()));
            }
        }

        catch (UnsupportedEncodingException uee) {
            throw new FaceClientException(uee);
        }

        postMethod.setURI(uri);
        postMethod.setEntity(entity);

        final long start = System.currentTimeMillis();
        final HttpResponse response = httpClient.execute(postMethod);

        return checkResponse(response);
    }

    catch (IOException ioe) {
        throw new FaceClientException(ioe);
    }
}

From source file:com.diversityarrays.dalclient.httpimpl.DalHttpFactoryImpl.java

@Override
public DalRequest createForUpload(String url, List<Pair<String, String>> pairs, String rand_num,
        String namesInOrder, String signature, File fileForUpload) {

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (Pair<String, String> pair : pairs) {
        builder.addTextBody(pair.a, pair.b);
    }/* www.  j a  v  a2 s .  c  o  m*/

    builder.addPart("uploadfile", new FileBody(fileForUpload)).addTextBody("rand_num", rand_num)
            .addTextBody("url", url);

    HttpEntity entity = builder.addTextBody("param_order", namesInOrder).addTextBody("signature", signature)
            .build();

    HttpPost post = new HttpPost(url);
    post.setEntity(entity);

    return new DalRequestImpl(post);
}

From source file:io.undertow.server.handlers.form.MultipartFormDataParserTestCase.java

@Test
public void testFileUpload() throws Exception {
    DefaultServer.setRootHandler(new BlockingHandler(createHandler()));
    TestHttpClient client = new TestHttpClient();
    try {/*from   w w  w  . j ava  2 s  .  c o  m*/

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        //post.setHeader(Headers.CONTENT_TYPE, MultiPartHandler.MULTIPART_FORM_DATA);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file", new FileBody(
                new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);

    } finally {
        client.getConnectionManager().shutdown();
    }
}