org.apache.http.entity.mime.content.InputStreamBody Java Examples

The following examples show how to use org.apache.http.entity.mime.content.InputStreamBody. 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: ClueWebSearcher.java    From SEAL with Apache License 2.0 6 votes vote down vote up
/** 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;
}
 
Example #2
Source File: HttpConnectorTest.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
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);
}
 
Example #3
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@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);
    }
}
 
Example #4
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@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);
    }
}
 
Example #5
Source File: HttpConnectorTest.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
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);
}
 
Example #6
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@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);
    }
}
 
Example #7
Source File: HttpSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #8
Source File: Utils.java    From JavaTelegramBot-API with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #9
Source File: PostReceiver.java    From android-lite-http with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #10
Source File: RefineHTTPClient.java    From p3-batchrefine with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #11
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@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)));
}
 
Example #12
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@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)));
}
 
Example #13
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@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)));
}
 
Example #14
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@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)));
}
 
Example #15
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@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());
    }
}
 
Example #16
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@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);
    }
}
 
Example #17
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@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());
    }
}
 
Example #18
Source File: UploadAPITest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #19
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
@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)));

}
 
Example #20
Source File: FourSharedUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 4 votes vote down vote up
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());
        }

    }
 
Example #21
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
@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);
}
 
Example #22
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
@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);
}
 
Example #23
Source File: FileUploadDownloadClient.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
private static ContentBody getContentBody(String fileName, InputStream inputStream) {
  return new InputStreamBody(inputStream, ContentType.DEFAULT_BINARY, fileName);
}
 
Example #24
Source File: MultipartEntityBuilder.java    From iaf with Apache License 2.0 4 votes vote down vote up
public MultipartEntityBuilder addBinaryBody(String name, InputStream stream, ContentType contentType, String filename) {
	return addPart(name, new InputStreamBody(stream, contentType, filename));
}
 
Example #25
Source File: RestSchedulerPushPullFileTest.java    From scheduling with GNU Affero General Public License v3.0 4 votes vote down vote up
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());
}