下面列出了org.apache.http.entity.mime.MIME#org.apache.http.entity.mime.content.ContentBody 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
ContentBody constructContentBody() throws UnsupportedEncodingException {
ContentType contentTypeObject = constructContentTypeObject();
if (filePath != null) { // FILE part
if (contentTypeObject != null) {
return new FileBody(new File(filePath), contentTypeObject);
} else {
return new FileBody(new File(filePath));
}
} else if (content != null) { // TEXT part
if (contentTypeObject != null) {
return new StringBody(content, contentTypeObject);
} else {
return new StringBody(content, ContentType.TEXT_PLAIN);
}
} else { // BYTE ARRAY part
if (contentTypeObject != null) {
return new ByteArrayBody(this.fileBytes, contentTypeObject, fileName);
} else {
return new ByteArrayBody(this.fileBytes, fileName);
}
}
}
private static void buildPart(MultipartEntityBuilder part, String n, Object v) {
if (v instanceof ContentBody) {
part.addPart(n, (ContentBody) v);
} else
if (v instanceof File) {
part.addBinaryBody(n , (File) v);
} else
if (v instanceof byte[]) {
part.addBinaryBody(n , (byte[]) v);
} else
if (v instanceof InputStream) {
part.addBinaryBody(n , (InputStream) v);
} else
{
part.addTextBody(n , String.valueOf(v));
}
}
@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);
}
}
@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);
}
}
@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);
}
}
/**
* Upload with <a href="http://www.sockshare.com/apidocs.php">API</a>.
*/
private void apiUpload() throws UnsupportedEncodingException, IOException, Exception{
uploading();
ContentBody cbFile = createMonitoredFileBody();
NUHttpPost httppost = new NUHttpPost(apiURL);
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("file", cbFile);
mpEntity.addPart("user", new StringBody(sockShareAccount.username));
mpEntity.addPart("password", new StringBody(sockShareAccount.password));
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
String reqResponse = EntityUtils.toString(response.getEntity());
//NULogger.getLogger().info(reqResponse);
if(reqResponse.contains("File Uploaded Successfully")){
gettingLink();
downURL = StringUtils.stringBetweenTwoStrings(reqResponse, "<link>", "</link>");
}
else{
//Handle the errors
status = UploadStatus.GETTINGERRORS;
throw new Exception(StringUtils.stringBetweenTwoStrings(reqResponse, "<message>", "</message>"));
}
}
private static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
//httppost.setHeader("Cookie", sidcookie+";"+mysessioncookie);
file = new File("h:/UploadingdotcomUploaderPlugin.java");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("Filename", new StringBody(file.getName()));
mpEntity.addPart("notprivate", new StringBody("false"));
mpEntity.addPart("folder", new StringBody("/"));
mpEntity.addPart("Filedata", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into zippyshare.com");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
uploadresponse = EntityUtils.toString(resEntity);
}
downloadlink=parseResponse(uploadresponse, "value=\"http://", "\"");
downloadlink="http://"+downloadlink;
System.out.println("Download Link : "+downloadlink);
httpclient.getConnectionManager().shutdown();
}
private static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
file = new File("h:/UploadingdotcomUploaderPlugin.java");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("emai", new StringBody("Free"));
mpEntity.addPart("upload_range", new StringBody("1"));
mpEntity.addPart("upfile_0", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into MegaShare.com");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
uploadresponse = response.getLastHeader("Location").getValue();
System.out.println("Upload response : "+uploadresponse);
System.out.println(response.getStatusLine());
httpclient.getConnectionManager().shutdown();
}
public static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost(postURL);
File file = new File("d:/hai.html");
System.out.println(ukeycookie);
httppost.setHeader("Cookie", ukeycookie + ";" + skeycookie + ";" + usercookie);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("", cbFile);
httppost.setEntity(mpEntity);
System.out.println("Now uploading your file into mediafire...........................");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Getting upload response key value..........");
uploadresponsekey = EntityUtils.toString(resEntity);
getUploadResponseKey();
System.out.println("upload resoponse key " + uploadresponsekey);
}
}
private static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
file = new File("h:/install.txt");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("Filename", new StringBody(file.getName()));
mpEntity.addPart("Filedata", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into sharesend.com");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
uploadresponse = EntityUtils.toString(resEntity);
}
System.out.println("Upload Response : " + uploadresponse);
System.out.println("Download Link : http://sharesend.com/" + uploadresponse);
httpclient.getConnectionManager().shutdown();
}
private static void fileUpload() throws Exception {
file = new File("/home/vigneshwaran/VIGNESH/dinesh.txt");
httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("Filename", new StringBody(file.getName()));
mpEntity.addPart("ssd", new StringBody(ssd));
mpEntity.addPart("Filedata", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into slingfile.com");
HttpResponse response = httpclient.execute(httppost);
// HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
}
private static void fileUpload() throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
httppost.setHeader("Cookie", sidcookie);
file = new File("h:/install.txt");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("filepc", cbFile);
mpEntity.addPart("server", new StringBody(server));
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into uploadbox.com");
HttpResponse response = httpclient.execute(httppost);
System.out.println(response.getStatusLine());
uploadresponse = response.getLastHeader("Location").getValue();
uploadresponse = getData(uploadresponse);
downloadlink = parseResponse(uploadresponse, "name=\"loadlink\" id=\"loadlink\" class=\"text\" onclick=\"this.select();\" value=\"", "\"");
deletelink = parseResponse(uploadresponse, "name=\"deletelink\" id=\"deletelink\" class=\"text\" onclick=\"this.select();\" value=\"", "\"");
System.out.println("Download link " + downloadlink);
System.out.println("deletelink : " + deletelink);
}
public static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
file = new File("/home/vigneshwaran/dinesh.txt");
HttpPost httppost = new HttpPost(postURL);
httppost.setHeader("Cookie", langcookie + ";" + sessioncookie + ";" + mailcookie + ";" + namecookie + ";" + rolecookie + ";" + orderbycookie + ";" + directioncookie + ";");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("files[]", cbFile);
httppost.setEntity(mpEntity);
System.out.println("Now uploading your file into wupload...........................");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (response.getStatusLine().getStatusCode() == 302
&& response.getFirstHeader("Location").getValue().contains("upload/done/")) {
System.out.println("Upload successful :)");
} else {
System.out.println("Upload failed :(");
}
}
private static void fileUpload() throws Exception {
file = new File("C:\\Documents and Settings\\All Users\\Documents\\My Pictures\\Sample Pictures\\Sunset.jpg");
httpclient = new DefaultHttpClient();
//http://upload3.divshare.com/cgi-bin/upload.cgi?sid=8ef15852c69579ebb2db1175ce065ba6
HttpPost httppost = new HttpPost(downURL + "cgi-bin/upload.cgi?sid=" + sid);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("file[0]", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into divshare.com");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(resEntity));
}
private static void fileUpload() throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
file = new File("h:/Sakura haruno.jpg");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("Filename", new StringBody(file.getName()));
mpEntity.addPart("Filedata", cbFile);
// mpEntity.addPart("server", new StringBody(server));
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into ugotfile.com");
HttpResponse response = httpclient.execute(httppost);
System.out.println(response.getStatusLine());
if (response != null) {
uploadresponse = EntityUtils.toString(response.getEntity());
}
System.out.println("Upload Response : " + uploadresponse);
downloadlink = parseResponse(uploadresponse, "[\"", "\"");
downloadlink = downloadlink.replaceAll("\\\\/", "/");
deletelink = parseResponse(uploadresponse, "\",\"", "\"");
deletelink = deletelink.replaceAll("\\\\/", "/");
System.out.println("Download Link : " + downloadlink);
System.out.println("Delete Link : " + deletelink);
}
public static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
file = new File("C:\\Documents and Settings\\dinesh\\Desktop\\GeDotttUploaderPlugin.java");
HttpPost httppost = new HttpPost("https://docs.zoho.com/uploadsingle.do?isUploadStatus=false&folderId=0&refFileElementId=refFileElement0");
httppost.setHeader("Cookie", cookies.toString());
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("multiupload_file", cbFile);
httppost.setEntity(mpEntity);
System.out.println("Now uploading your file into zoho docs...........................");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
String tmp = EntityUtils.toString(resEntity);
// System.out.println(tmp);
if(tmp.contains("File Uploaded Successfully"))
System.out.println("File Uploaded Successfully");
}
// uploadresponse = response.getLastHeader("Location").getValue();
// System.out.println("Upload response : " + uploadresponse);
}
@Programmatic
public byte[] convertToPdf(
final byte[] docxBytes,
final String url) {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
final HttpPost httpPost = new HttpPost(url);
ContentBody bin = new ByteArrayBody(docxBytes, "dummy.docx");
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("files", bin)
.build();
httpPost.setEntity(reqEntity);
try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
HttpEntity resEntity = response.getEntity();
return resEntity != null ? EntityUtils.toByteArray(resEntity) : null;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Determines the total length of the multipart content (content length of
* individual parts plus that of extra elements required to delimit the parts
* from one another). If any of the @{link BodyPart}s contained in this object
* is of a streaming entity of unknown length the total length is also unknown.
* <p>
* This method buffers only a small amount of data in order to determine the
* total length of the entire entity. The content of individual parts is not
* buffered.
* </p>
*
* @return total length of the multipart entity if known, {@code -1} otherwise.
*/
public long getTotalLength() {
long contentLen = 0;
for (final FormBodyPart part: getBodyParts()) {
final ContentBody body = part.getBody();
final long len = body.getContentLength();
if (len >= 0) {
contentLen += len;
} else {
return -1;
}
}
final ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
doWriteTo(out, false);
final byte[] extra = out.toByteArray();
return contentLen + extra.length;
} catch (final IOException ex) {
// Should never happen
return -1;
}
}
public HttpClientWrapper(HttpProxy proxy) {
super();
//client = HttpClientBuilder.create().build();//不使用连接池
client = this.getCloseableHttpClient(proxy);
this.contentBodies = new ArrayList<ContentBody>();
this.nameValuePostBodies = new LinkedList<NameValuePair>();
}
/**
* POST方式发送名值对请求URL,上传文件(包括图片)
*
* @param url
* @return
* @throws HttpException
* @throws IOException
*/
public ResponseStatus postEntity(String url, String urlEncoding) throws HttpException, IOException {
if (url == null)
return null;
HttpEntity entity = null;
HttpRequestBase request = null;
CloseableHttpResponse response = null;
try {
this.parseUrl(url);
HttpPost httpPost = new HttpPost(toUrl());
//对请求的表单域进行填充
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (NameValuePair nameValuePair : this.getNVBodies()) {
entityBuilder.addPart(nameValuePair.getName(),
new StringBody(nameValuePair.getValue(), ContentType.create("text/plain", urlEncoding)));
}
for (ContentBody contentBody : getContentBodies()) {
entityBuilder.addPart("file", contentBody);
}
entityBuilder.setCharset(CharsetUtils.get(urlEncoding));
httpPost.setEntity(entityBuilder.build());
request = httpPost;
response = client.execute(request);
//响应状态
StatusLine statusLine = response.getStatusLine();
// 获取响应对象
entity = response.getEntity();
ResponseStatus ret = new ResponseStatus();
ret.setStatusCode(statusLine.getStatusCode());
getResponseStatus(entity, ret);
return ret;
} finally {
close(entity, request, response);
}
}
public Session uploadFile(byte [] bytes,String filename,String appName,String dirName){
MultipartEntityBuilder multipartEntity= (MultipartEntityBuilder) this.getProviderService().provider();
ContentBody byteArrayBody = new ByteArrayBody(bytes, filename);
multipartEntity.addPart("file", byteArrayBody);
multipartEntity.addTextBody("dirName", dirName);
multipartEntity.addTextBody("filename", filename);
multipartEntity.addTextBody("appName",appName);
return this;
}
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;
}
@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());
}
}
@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);
}
}
@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());
}
}
@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)));
}
@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)));
}
@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)));
}
@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)));
}
public void fileUpload() throws Exception {
uploading();
httpPost = new NUHttpPost(postURL);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = createMonitoredFileBody();
mpEntity.addPart("MAX_FILE_SIZE", new StringBody(MAX_FILE_SIZE));
mpEntity.addPart("UPLOAD_IDENTIFIER", new StringBody(UPLOAD_IDENTIFIER));
mpEntity.addPart("go", new StringBody(go));
mpEntity.addPart("files", cbFile);
mpEntity.addPart("agree", new StringBody("1"));
mpEntity.addPart("submit", new StringBody("Upload Now"));
httpPost.setEntity(mpEntity);
NULogger.getLogger().info("Now uploading your file into depositfiles...........................");
HttpResponse response = httpclient.execute(httpPost, httpContext);
HttpEntity resEntity = response.getEntity();
NULogger.getLogger().info(response.getStatusLine().toString());
if (resEntity != null) {
gettingLink();
uploadresponse = EntityUtils.toString(resEntity);
downloadlink = StringUtils.stringBetweenTwoStrings(uploadresponse, "ud_download_url = '", "'");
deletelink = StringUtils.stringBetweenTwoStrings(uploadresponse, "ud_delete_url = '", "'");
NULogger.getLogger().log(Level.INFO, "download link : {0}", downloadlink);
NULogger.getLogger().log(Level.INFO, "delete link : {0}", deletelink);
downURL = downloadlink;
delURL = deletelink;
} else {
throw new Exception("Error in depositfiles!");
}
}