Do not read the file in the package .jar - java

This code reads the firmware upgrade file from JAR package and send as Post request to device:
CloseableHttpClient client2 = HttpClients.createDefault();
HttpPost post = new HttpPost("http://" + IP + "/moxa-cgi/UploadFirmwareFile.cgi");
InputStream stream = Main.class.getResourceAsStream("vport364a_v1_5.rom");
byte b[] = new byte[stream.available()];
stream.read(b);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("uploadfile", b, ContentType.APPLICATION_OCTET_STREAM, "vport364a_v1_5.rom");
post.setEntity(builder.build());
HttpResponse response2 = client2.execute(post);
For unknown reasons, the code stopped working as execute jar package: firmware upgrade file send as nulls. On line:
stream.read(b);
only nulls already.
If I run code in IDE Netbeans, it works.Why?

Related

Send file to bitbucket project using java and intellij

I am trying to send a file to a bitbucket master repository through my java selenium project.
I am currently able to send the file to another project on my local machine using
System.setProperty("webdriver.chrome.logfile",
"C:\\Users\\IdeaProjects\\project\\chromelogs1.txt");
However using the bitbucket location it doesnt work, any ideas?
I'm trying
System.setProperty("webdriver.chrome.logfile",
"https:\\bitbucket.org\\noting-automation\\src\\master\\Noting\\chromelogs1.txt");
But its not giving an error the driver doesnt initialize, not sure if the url is correct in that form
Update
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
//note that it the path contains browse after the repo-url
String url = "https://bitbucket.org/noting/src/master";
String user = "UN";
String pw = "PW";
File f= new
File("C:\\Users\\IdeaProjects\\filename\chromelogs1.txt");
HttpPost httpPost = new HttpPost(url);
String encoding = Base64.getEncoder().encodeToString((user
+ ":" + pw).getBytes(StandardCharsets.UTF_8));
System.out.println("URL Equals: "+ url);
httpPost.setHeader("Authorization", "Basic " + encoding);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("branch", new StringBody("master",
ContentType.TEXT_PLAIN))
.addPart("content", new StringBody("file content,
can be different than stringbody, just as example",
ContentType.TEXT_PLAIN))
.addPart("message", new StringBody("commit
message", ContentType.TEXT_PLAIN))
.addPart("file", new FileBody(f))
.build();
System.out.println(reqEntity);
httpPost.setEntity(reqEntity);
CloseableHttpResponse response =
httpclient.execute(httpPost);
System.out.println(response.toString());
} finally {
httpclient.close();
}
Trying this now but its returning a 401, any ideas?
Your link does not seem right. It should start with org and work its way back. See here for an example under PropertySourceAnnotationTests.withResolvablePlaceholder()
Or go to BitBucket to find the right link. First click clone and then either use https:// or SSH key in the setProperty call.

File attachment with REST API

The below code is working fine to attach file in JIRA, only one problem is here
I can't use MultipartEntityBuilder as it needed to add new dependency in pom and that is not permissible , can any one please suggest which basic API I can use there? thanks in advance
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost("https://xxxx.zzzz.net/rest/api/2/issue/" + issueID +"/attachments");
postRequest.setHeader("Authorization", "Basic <AUTHSTRING>");
postRequest.setHeader("X-Atlassian-Token", "nocheck");
File file = new File("C:\\Users\\MKumar\\Desktop\\Oauth_JIRA.rtf");
URL url = new URL("C:\\Users\\MKumar\\Desktop\\Oauth_JIRA.rtf");
MultipartEntityBuilder builder = MultipartBodyBuilder.create();
// This attaches the file to the POST:
builder.addBinaryBody(
"file",
new FileInputStream(file),
ContentType.MULTIPART_FORM_DATA,
file.getName()
);
HttpEntity multipart = builder.build();
postRequest.setEntity(multipart);
HttpResponse response = httpClient.execute(postRequest);
org.apache.http.entity.mime.MultipartEntity is deprecated as a result you'll have to use MultipartEntityBuilder.
For more related post please see this thread

zip file size limitation on ckan java client upload

I have created a java program that can upload a file to a ckan installation, (currently my local testing installation, haven't tested it on a live one).
The text files that i tested my application are uploaded to ckan properly. I do have a problem with some zip files.
After some test and failure attempts, i realized that the problem is in the size of the file. For zip files less than 4Kb it works, but for larger files it fails with the error "server Error".
The files failing to upload via my java application, upload just fine when using the ckan front end, so i am guessing the problem is with my java application and not the ckan installation. This is the code I am using:
StringBuilder sb = new StringBuilder();
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
File file = new File(uploadFileName);
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyyMMdd_HHmmss");
String date=dateFormatGmt.format(new Date());
HttpPost postRequest;
try {
ContentType zipType=ContentType.create("zip");
ContentBody cbFile = new FileBody(file,zipType);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("file", cbFile)
.addPart("url",new StringBody(HOST+"/files/"+date+"/"+uploadFileName,ContentType.TEXT_PLAIN))
.addPart("upload",cbFile)
.addPart("title",new StringBody(TITLE,ContentType.TEXT_PLAIN))
.addPart("description",new StringBody(DESCRIPTION+date,ContentType.TEXT_PLAIN))
.addPart("comment",new StringBody(COMMENT,ContentType.TEXT_PLAIN))
.addPart("key", new StringBody(uploadFileName+date,ContentType.TEXT_PLAIN))
.addPart("package_id",new StringBody("test2",ContentType.TEXT_PLAIN))
.addPart("notes", new StringBody("notes",ContentType.TEXT_PLAIN))
.build();
postRequest = new HttpPost(HOST+"/api/action/resource_create");
postRequest.setEntity(reqEntity);
postRequest.setHeader("X-CKAN-API-Key", myApiKey);
HttpResponse response = httpclient.execute(postRequest);
int statusCode = response.getStatusLine().getStatusCode();
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
}
catch (IOException ioe) {
System.out.println(ioe);
}
finally {
httpclient.getConnectionManager().shutdown();
}

GZip POST request with HTTPClient in Java

I need to send a POST request to a web server which includes a gzipped request parameter. I'm using Apache HttpClient and I've read that it supports Gzip out of the box, but I can't find any examples of how to do what I need. I'd appreciate it if anyone could post some examples of this.
You need to turn that String into a gzipped byte[] or (temp) File first. Let's assume that it's not an extraordinary large String value so that a byte[] is safe enough for the available JVM memory:
String foo = "value";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPOutputStream gzos = new GZIPOutputStream(baos)) {
gzos.write(foo.getBytes("UTF-8"));
}
byte[] fooGzippedBytes = baos.toByteArray();
Then, you can send it as a multipart body using HttpClient as follows:
MultipartEntity entity = new MultipartEntity();
entity.addPart("foo", new InputStreamBody(new ByteArrayInputStream(fooGzippedBytes), "foo.txt"));
HttpPost post = new HttpPost("http://example.com/some");
post.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
// ...
Note that HttpClient 4.1 supports the new ByteArrayBody which can be used as follows:
entity.addPart("foo", new ByteArrayBody(fooGzippedBytes, "foo.txt"));

InputStreamBody in HttpMime 4.0.3 settings for content-length

I am trying to send a multi part formdata post through my java code. Can someone tell me how to set Content Length in the following?? There seem to be headers involved when we use InputStreamBody which implements the ContentDescriptor interface. Doing a getContentLength on the InputStreamBody gives me -1 after i add the content. I subclassed it to give contentLength the length of my byte array but am not sure if other headers required by ContentDescriptor will be set for a proper POST.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(myURL);
ContentBody cb = new InputStreamBody(new ByteArrayInputStream(bytearray), myMimeType, filename);
//ContentBody cb = new ByteArrayBody(bytearray, myMimeType, filename);
MultipartEntity mpentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpentity.addPart("key", new StringBody("SOME_KEY"));
mpentity.addPart("output", new StringBody("SOME_NAME"));
mpentity.addPart("content", cb);
httpPost.setEntity(mpentity);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
I'm the author of the ByteArrayBody class you have commented out.
I wrote it because I faced the same issue you did. The original Jira ticket is here: https://issues.apache.org/jira/browse/HTTPCLIENT-1014
So, since you already have a byte[], either upgrade HttpMime to the latest version, 4.1-beta1, which includes this class. Or copy the code from the Jira issue into your own project.
The ByteArrayBody class will do exactly what you need.

Categories

Resources