类org.apache.http.entity.mime.content.InputStreamBody源码实例Demo

下面列出了怎么用org.apache.http.entity.mime.content.InputStreamBody的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: blynk-server   文件: OTATest.java
@Test
public void testOTAWrongToken() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(400, response.getStatusLine().getStatusCode());
        String error = TestUtil.consumeText(response);

        assertNotNull(error);
        assertEquals("Invalid token.", error);
    }
}
 
源代码2 项目: blynk-server   文件: OTATest.java
@Test
public void testAuthorizationFailed() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString("123:123".getBytes()));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(403, response.getStatusLine().getStatusCode());
        String error = TestUtil.consumeText(response);

        assertNotNull(error);
        assertEquals("Authentication failed.", error);
    }
}
 
源代码3 项目: blynk-server   文件: OTATest.java
@Test
public void basicOTAForNonExistingSingleUser() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/[email protected]");
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(400, response.getStatusLine().getStatusCode());
        String er = TestUtil.consumeText(response);
        assertNotNull(er);
        assertEquals("Requested user not found.", er);
    }
}
 
源代码4 项目: CloverETL-Engine   文件: HttpConnectorTest.java
public void testBuildMultiPartContentByte() throws IOException {
	HashMap<String, HttpConnectorMutlipartEntity> multipartEntities = new HashMap<String, HttpConnectorMutlipartEntity>();
	HttpConnectorMutlipartEntity entity;
	entity = new HttpConnectorMutlipartEntity();
	entity.name = "test1";
	entity.contentByte = "123456789".getBytes();
	entity.fileNameAttribute = "ContentByteFile";
	multipartEntities.put(entity.name, entity);
	
	PartWithName[] result = this.createHttpConnector().buildMultiPart(multipartEntities);
	assertEquals(1, result.length);
	assertEquals("ContentByteFile", result[0].value.getFilename());
	byte[] data = new byte[9];
	int readSize = ((InputStreamBody) result[0].value).getInputStream().read(data);
	assertEquals(readSize, 9);
	assertTrue(Arrays.equals("123456789".getBytes(), data));
	
	assertEquals("test1", result[0].name);
}
 
源代码5 项目: CloverETL-Engine   文件: HttpConnectorTest.java
public void testBuildMultiPartContentByte2() throws IOException {
	HashMap<String, HttpConnectorMutlipartEntity> multipartEntities = new HashMap<String, HttpConnectorMutlipartEntity>();
	HttpConnectorMutlipartEntity entity;
	entity = new HttpConnectorMutlipartEntity();
	entity.name = "test1";
	entity.contentByte = "123456789".getBytes();
	multipartEntities.put(entity.name, entity);
	
	PartWithName[] result = this.createHttpConnector().buildMultiPart(multipartEntities);
	assertEquals(1, result.length);
	assertEquals("test1", result[0].value.getFilename());
	//assertEquals(9,result[0].value.getContentLength());
	byte[] data = new byte[9];
	int readSize = ((InputStreamBody) result[0].value).getInputStream().read(data);
	assertEquals(readSize, 9);
	assertTrue(Arrays.equals("123456789".getBytes(), data));
	
	assertEquals("test1", result[0].name);
}
 
源代码6 项目: SEAL   文件: ClueWebSearcher.java
/** Utility method:
 * Formulate an HTTP POST request to upload the batch query file
 * @param queryBody
 * @return
 * @throws UnsupportedEncodingException
 */
private HttpPost makePost(String queryBody) throws UnsupportedEncodingException {
    HttpPost post = new HttpPost(ClueWebSearcher.BATCH_CATB_BASEURL);
    InputStreamBody qparams = 
        new InputStreamBody(
                new ReaderInputStream(new StringReader(queryBody)),
                "text/plain",
        "query.txt");

    MultipartEntity entity = new MultipartEntity();
    entity.addPart("viewstatus", new StringBody("1")); 
    entity.addPart("indextype",  new StringBody("catbparams"));
    entity.addPart("countmax",   new StringBody("100"));
    entity.addPart("formattype", new StringBody(format));
    entity.addPart("infile",     qparams);

    post.setEntity(entity);
    return post;
}
 
源代码7 项目: JavaTelegramBot-API   文件: Utils.java
/**
 * Adds an input file to a request, with the given field name.
 *
 * @param request The request to be added to.
 * @param fieldName The name of the field.
 * @param inputFile The input file.
 */
public static void processInputFileField(MultipartBody request, String fieldName, InputFile inputFile) {
    String fileId = inputFile.getFileID();
    if (fileId != null) {
        request.field(fieldName, fileId, false);
    } else if (inputFile.getInputStream() != null) {
        request.field(fieldName, new InputStreamBody(inputFile.getInputStream(), inputFile.getFileName()), true);
    } else { // assume file is not null (this is existing behaviour as of 1.5.1)
        request.field(fieldName, new FileContainer(inputFile), true);
    }
}
 
源代码8 项目: blynk-server   文件: UploadAPITest.java
private String upload(String filename) throws Exception {
    InputStream logoStream = UploadAPITest.class.getResourceAsStream("/" + filename);

    HttpPost post = new HttpPost("http://localhost:" + properties.getHttpPort() + "/upload");
    ContentBody fileBody = new InputStreamBody(logoStream, ContentType.APPLICATION_OCTET_STREAM, filename);
    StringBody stringBody1 = new StringBody("Message 1", ContentType.MULTIPART_FORM_DATA);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    builder.addPart("text1", stringBody1);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String staticPath;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        staticPath = TestUtil.consumeText(response);

        assertNotNull(staticPath);
        assertTrue(staticPath.startsWith("/static"));
        assertTrue(staticPath.endsWith("bin"));
    }

    return staticPath;
}
 
源代码9 项目: blynk-server   文件: OTATest.java
@Test
public void testImprovedUploadMethod() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + clientPair.token);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

    HttpGet index = new HttpGet("http://localhost:" + properties.getHttpPort() + path);

    try (CloseableHttpResponse response = httpclient.execute(index)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("application/octet-stream", response.getHeaders("Content-Type")[0].getValue());
    }
}
 
源代码10 项目: blynk-server   文件: OTATest.java
@Test
public void testOTAFailedWhenNoDevice() throws Exception {
    clientPair.hardwareClient.stop();

    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + clientPair.token);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(400, response.getStatusLine().getStatusCode());
        String error = TestUtil.consumeText(response);

        assertNotNull(error);
        assertEquals("No device in session.", error);
    }
}
 
源代码11 项目: blynk-server   文件: OTATest.java
@Test
public void basicOTAForAllDevices() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start");
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

    HttpGet index = new HttpGet("http://localhost:" + properties.getHttpPort() + path);

    try (CloseableHttpResponse response = httpclient.execute(index)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("application/octet-stream", response.getHeaders("Content-Type")[0].getValue());
    }
}
 
源代码12 项目: blynk-server   文件: OTATest.java
@Test
public void testStopOTA() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start");
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }
    String responseUrl = "http://127.0.0.1:18080" + path;

    HttpGet stopOta = new HttpGet(httpsAdminServerUrl + "/ota/stop");
    stopOta.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    try (CloseableHttpResponse response = httpclient.execute(stopOta)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
    }

    clientPair.hardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111"));
    clientPair.hardwareClient.verifyResult(ok(1));
    verify(clientPair.hardwareClient.responseMock, never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
}
 
源代码13 项目: blynk-server   文件: OTATest.java
@Test
public void basicOTAForSingleUser() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?user=" + getUserName());
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

    TestHardClient newHardwareClient = new TestHardClient("localhost", properties.getHttpPort());
    newHardwareClient.start();
    newHardwareClient.login(clientPair.token);
    verify(newHardwareClient.responseMock, timeout(1000)).channelRead(any(), eq(ok(1)));
    newHardwareClient.reset();

    newHardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111"));
    verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(ok(1)));
    verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
}
 
源代码14 项目: blynk-server   文件: OTATest.java
@Test
public void basicOTAForSingleUserAndNonExistingProject() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?user=" + getUserName() + "&project=123");
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

    TestHardClient newHardwareClient = new TestHardClient("localhost", properties.getHttpPort());
    newHardwareClient.start();
    newHardwareClient.login(clientPair.token);
    verify(newHardwareClient.responseMock, timeout(1000)).channelRead(any(), eq(ok(1)));
    newHardwareClient.reset();

    newHardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111"));
    verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(ok(1)));
    verify(clientPair.hardwareClient.responseMock, never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
}
 
源代码15 项目: blynk-server   文件: OTATest.java
@Test
public void basicOTAForSingleUserAndExistingProject() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?user=" + getUserName() + "&project=My%20Dashboard");
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

    TestHardClient newHardwareClient = new TestHardClient("localhost", properties.getHttpPort());
    newHardwareClient.start();
    newHardwareClient.login(clientPair.token);
    verify(newHardwareClient.responseMock, timeout(1000)).channelRead(any(), eq(ok(1)));
    newHardwareClient.reset();

    newHardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111"));
    verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(ok(1)));
    verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
}
 
源代码16 项目: p3-batchrefine   文件: RefineHTTPClient.java
private String createProjectAndUpload(URL original) throws IOException {
    CloseableHttpResponse response = null;

    URLConnection connection = original.openConnection();

    try (InputStream iStream = connection.getInputStream()) {

        /*
         * Refine requires projects to be named, but these are not important
* for us, so we just use a random string.
*/
        String name = RandomStringUtils
                .randomAlphanumeric(IDENTIFIER_LENGTH);

        HttpEntity entity = MultipartEntityBuilder
                .create()
                .addPart("project-file",
                        new InputStreamBody(iStream, contentType(original, connection), BOGUS_FILENAME))
                .addPart("project-name",
                        new StringBody(name, ContentType.TEXT_PLAIN))
                .build();

        response = doPost("/command/core/create-project-from-upload",
                entity);

        URI projectURI = new URI(response.getFirstHeader("Location")
                .getValue());

        //TODO check if this is always UTF-8
        return URLEncodedUtils.parse(projectURI, "UTF-8").get(0).getValue();

    } catch (Exception e) {
        throw launderedException(e);
    } finally {
        Utils.safeClose(response);
    }
}
 
源代码17 项目: android-lite-http   文件: PostReceiver.java
private HttpEntity getMultipartEntity(String path) throws UnsupportedEncodingException, FileNotFoundException {
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("stringKey", new StringBody("StringBody", "text/plain", Charset.forName("utf-8")));
    byte[] bytes = new byte[]{1, 2, 3};
    entity.addPart("bytesKey", new ByteArrayBody(bytes, "bytesfilename"));
    entity.addPart("fileKey", new FileBody(new File(path + "well.png")));
    entity.addPart("isKey", new InputStreamBody(new FileInputStream(new File(path + "well.png")), "iswell.png"));

    return entity;
}
 
源代码18 项目: iaf   文件: HttpSender.java
protected FormBodyPart createMultipartBodypart(String name, InputStream is, String fileName, String contentType) {
	if (log.isDebugEnabled()) log.debug(getLogPrefix()+"appending filepart ["+name+"] with value ["+is+"] fileName ["+fileName+"] and contentType ["+contentType+"]");
	FormBodyPartBuilder bodyPart = FormBodyPartBuilder.create()
		.setName(name)
		.setBody(new InputStreamBody(is, ContentType.create(contentType, getCharSet()), fileName));
	return bodyPart.build();
}
 
源代码19 项目: scheduling   文件: RestSchedulerPushPullFileTest.java
public void testIt(String spaceName, String spacePath, String destPath, boolean encode) throws Exception {
    File testPushFile = RestFuncTHelper.getDefaultJobXmlfile();
    // you can test pushing pulling a big file :
    // testPushFile = new File("path_to_a_big_file");
    File destFile = new File(new File(spacePath, destPath), testPushFile.getName());
    if (destFile.exists()) {
        destFile.delete();
    }

    // PUSHING THE FILE
    String pushfileUrl = getResourceUrl("dataspace/" + spaceName + "/" +
                                        (encode ? URLEncoder.encode(destPath, "UTF-8")
                                                : destPath.replace("\\", "/")));
    // either we encode or we test human readable path (with no special character inside)

    HttpPost reqPush = new HttpPost(pushfileUrl);
    setSessionHeader(reqPush);
    // we push a xml job as a simple test

    MultipartEntity multipartEntity = new MultipartEntity();
    multipartEntity.addPart("fileName", new StringBody(testPushFile.getName()));
    multipartEntity.addPart("fileContent",
                            new InputStreamBody(FileUtils.openInputStream(testPushFile),
                                                MediaType.APPLICATION_OCTET_STREAM,
                                                null));
    reqPush.setEntity(multipartEntity);
    HttpResponse response = executeUriRequest(reqPush);

    System.out.println(response.getStatusLine());
    assertHttpStatusOK(response);
    Assert.assertTrue(destFile + " exists for " + spaceName, destFile.exists());

    Assert.assertTrue("Original file and result are equals for " + spaceName,
                      FileUtils.contentEquals(testPushFile, destFile));

    // LISTING THE TARGET DIRECTORY
    String pullListUrl = getResourceUrl("dataspace/" + spaceName + "/" +
                                        (encode ? URLEncoder.encode(destPath, "UTF-8")
                                                : destPath.replace("\\", "/")));

    HttpGet reqPullList = new HttpGet(pullListUrl);
    setSessionHeader(reqPullList);

    HttpResponse response2 = executeUriRequest(reqPullList);

    System.out.println(response2.getStatusLine());
    assertHttpStatusOK(response2);

    InputStream is = response2.getEntity().getContent();
    List<String> lines = IOUtils.readLines(is);
    HashSet<String> content = new HashSet<>(lines);
    System.out.println(lines);
    Assert.assertTrue("Pushed file correctly listed", content.contains(testPushFile.getName()));

    // PULLING THE FILE
    String pullfileUrl = getResourceUrl("dataspace/" + spaceName + "/" +
                                        (encode ? URLEncoder.encode(destPath + "/" + testPushFile.getName(),
                                                                    "UTF-8")
                                                : destPath.replace("\\", "/") + "/" + testPushFile.getName()));

    HttpGet reqPull = new HttpGet(pullfileUrl);
    setSessionHeader(reqPull);

    HttpResponse response3 = executeUriRequest(reqPull);

    System.out.println(response3.getStatusLine());
    assertHttpStatusOK(response3);

    InputStream is2 = response3.getEntity().getContent();

    File answerFile = tmpFolder.newFile();
    FileUtils.copyInputStreamToFile(is2, answerFile);

    Assert.assertTrue("Original file and result are equals for " + spaceName,
                      FileUtils.contentEquals(answerFile, testPushFile));

    // DELETING THE HIERARCHY
    String rootPath = destPath.substring(0, destPath.contains("/") ? destPath.indexOf("/") : destPath.length());
    String deleteUrl = getResourceUrl("dataspace/" + spaceName + "/" +
                                      (encode ? URLEncoder.encode(rootPath, "UTF-8")
                                              : rootPath.replace("\\", "/")));
    HttpDelete reqDelete = new HttpDelete(deleteUrl);
    setSessionHeader(reqDelete);

    HttpResponse response4 = executeUriRequest(reqDelete);

    System.out.println(response4.getStatusLine());

    assertHttpStatusOK(response4);

    Assert.assertTrue(destFile + " still exist", !destFile.exists());
}
 
源代码20 项目: blynk-server   文件: OTATest.java
@Test
public void testImprovedUploadMethodAndCheckOTAStatusForDeviceThatNeverWasOnline() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + clientPair.token);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

    clientPair.appClient.getDevice(1, 0);

    Device device = clientPair.appClient.parseDevice(1);
    assertNotNull(device);
    assertEquals("[email protected]", device.deviceOtaInfo.otaInitiatedBy);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaInitiatedAt, 5000);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaUpdateAt, 5000);

    clientPair.hardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111"));

    assertEquals("[email protected]", device.deviceOtaInfo.otaInitiatedBy);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaInitiatedAt, 5000);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaUpdateAt, 5000);
}
 
源代码21 项目: blynk-server   文件: OTATest.java
@Test
public void testImprovedUploadMethodAndCheckOTAStatusForDeviceThatWasOnline() throws Exception {
    clientPair.hardwareClient.send("internal " + b("ver 0.3.1 fm 0.3.3 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111"));
    clientPair.hardwareClient.verifyResult(ok(1));

    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + clientPair.token);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

    clientPair.appClient.getDevice(1, 0);
    Device device = clientPair.appClient.parseDevice(1);

    assertNotNull(device);

    assertEquals("0.3.1", device.hardwareInfo.blynkVersion);
    assertEquals(10, device.hardwareInfo.heartbeatInterval);
    assertEquals("111", device.hardwareInfo.build);
    assertEquals("[email protected]", device.deviceOtaInfo.otaInitiatedBy);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaInitiatedAt, 5000);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaUpdateAt, 5000);

    clientPair.hardwareClient.send("internal " + b("ver 0.3.1 fm 0.3.3 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 112"));
    clientPair.hardwareClient.verifyResult(ok(2));

    clientPair.appClient.getDevice(1, 0);
    device = clientPair.appClient.parseDevice(2);

    assertNotNull(device);

    assertEquals("0.3.1", device.hardwareInfo.blynkVersion);
    assertEquals(10, device.hardwareInfo.heartbeatInterval);
    assertEquals("112", device.hardwareInfo.build);
    assertEquals("[email protected]", device.deviceOtaInfo.otaInitiatedBy);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaInitiatedAt, 5000);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaUpdateAt, 5000);
}
 
源代码22 项目: blynk-server   文件: OTATest.java
@Test
public void testConnectedDeviceGotOTACommand() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start");
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);
    }

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

    clientPair.hardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 123"));
    clientPair.hardwareClient.verifyResult(ok(1));
    verify(clientPair.hardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
    clientPair.hardwareClient.reset();

    clientPair.appClient.getDevice(1, 0);
    Device device = clientPair.appClient.parseDevice();

    assertNotNull(device);
    assertNotNull(device.deviceOtaInfo);
    assertEquals("[email protected]", device.deviceOtaInfo.otaInitiatedBy);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaInitiatedAt, 5000);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaInitiatedAt, 5000);
    assertNotEquals(device.deviceOtaInfo.otaInitiatedAt, device.deviceOtaInfo.otaUpdateAt);
    assertEquals("123", device.hardwareInfo.build);

    clientPair.hardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build ") + "Aug 14 2017 20:31:49");
    clientPair.hardwareClient.verifyResult(ok(1));
    verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

}
 
private static void upload(String login, String password, String file) throws ApiException {

        System.out.println("Trying to login to 4shared........");
        File f = new File(file);
        if (!f.exists() || !f.canRead() || f.isDirectory()) {
            System.out.println("File does not exist, unreadable or not a file");
            return;
        }

        DesktopAppJax2 da = new DesktopAppJax2Service().getDesktopAppJax2Port();
        String loginRes = da.login(login, password);
        if (!loginRes.isEmpty()) {
            System.out.println("Login failed: " + loginRes);
            return;
        }

        if (!da.hasRightUpload()) {
            System.out.println("Uploading is temporarily disabled");
            return;
        }

        System.out.println("4shared Login successful :)");
        long newFileId = da.uploadStartFile(login, password, -1, f.getName(), f.length());
        System.out.println("File id : " + newFileId);
        String sessionKey = da.createUploadSessionKey(login, password, -1);
        long dcId = da.getNewFileDataCenter(login, password);
        String url = da.getUploadFormUrl((int) dcId, sessionKey);

        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            MultipartEntity me = new MultipartEntity();
            StringBody rfid = new StringBody("" + newFileId);
            StringBody rfb = new StringBody("" + 0);
            InputStreamBody isb = new InputStreamBody(new BufferedInputStream(new FileInputStream(f)), "FilePart");
            me.addPart("resumableFileId", rfid);
            me.addPart("resumableFirstByte", rfb);
            me.addPart("FilePart", isb);

            post.setEntity(me);
            HttpResponse resp = client.execute(post);
            HttpEntity resEnt = resp.getEntity();

            String res = da.uploadFinishFile(login, password, newFileId, DigestUtils.md5Hex(new FileInputStream(f)));
            if (res.isEmpty()) {
                System.out.println("File uploaded.");
                downloadlink = da.getFileDownloadLink(login, password, newFileId);
                System.out.println("Download link : " + downloadlink);
            } else {
                System.out.println("Upload failed: " + res);
            }
        } catch (Exception ex) {
            System.out.println("Upload failed: " + ex.getMessage());
        }

    }
 
源代码24 项目: incubator-pinot   文件: FileUploadDownloadClient.java
private static ContentBody getContentBody(String fileName, InputStream inputStream) {
  return new InputStreamBody(inputStream, ContentType.DEFAULT_BINARY, fileName);
}
 
源代码25 项目: iaf   文件: MultipartEntityBuilder.java
public MultipartEntityBuilder addBinaryBody(String name, InputStream stream, ContentType contentType, String filename) {
	return addPart(name, new InputStreamBody(stream, contentType, filename));
}
 
 类所在包
 类方法
 同包方法