Writing Wrapper for FileUpload in Spring boot : File not Present - spring-boot

Use Case
I need to write a wrapper for a FileUpload API, which takes Files from UI, and upload those to remote API. What I have chalked out so far:
Made a Controller which takes File and Content body as Request part, then I try to upload them to remote API, code snippets follow:
Controller Endpoint
ResponseEntity uploadFiles(#RequestPart("files") MultipartFile[] files, #RequestPart("someData") Metadata fileMetadata)
File Upload Code
byte[][] fileArray = Arrays.stream(files).map(multipartFile -> {
try {
return multipartFile.getBytes();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}).toArray(byte[][]::new);
//add file
LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
configuration.getDocumentCategory());
params.add(DocStorageConstants.FILE, fileArray);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
ResponseEntity<FileUploadResponse> responseEntity = restTemplate.postForEntity(configuration.getUploadEndpoint(), requestEntity, FileUploadResponse.class);
The remote API returns response as if Files never reached this API, what I need to do to avoid this? I might try writing file to a temporary file and then upload that file to remote endpoint, not sure if that is a clean approach. Thanks in advance for any suggestions!
[Update]: The cURL that I am trying to form is below:
curl --location --request POST 'http://<host>:<port>/file-endpoint' \
--header 'X-Api-Client:<api-key>' \
--header 'x-service-id: <service-id>' \
--form 'file=#"/aggregate.csv"' \
--form 'uploadRequest="{\"bn\":\"NFA\",\"dc\":\"generalDocs\",
\"tags\":[\"test\", \"test2\"]
}"'

Following snippet worked
Arrays.stream(files).forEach(multipartFile -> params.add(DocStorageConstants.FILE, multipartFile.getResource()));

Related

Zendesk file upload through Spring boot REST

I'm trying to upload an image to the zendesk through its API, Once the file is uploaded I can get the token but files seems empty,
Reference : https://support.zendesk.com/hc/en-us/community/posts/4588002835994-Uploaded-image-is-empty-or-corrupted?page=1#community_comment_4588190155802
This is how my code looks like,
fis = new FileInputStream(file);
fis.read(contents);
byte[] encoded = Base64.encodeBase64(contents);
fis.close();
body.add("file", encoded);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
UploadResponseObject result = restTemplate.postForObject(
remoteUri + "/api/v2/uploads.json?filename=" + multipartFile.getOriginalFilename(),
new HttpEntity<>(body, headers),
UploadResponseObject.class);
I have tried with several different headers,
headers.set("Content-Disposition","form-data; name=\"attachment\"; filename=\"laptop_183544.jpg\"");
headers.add("Content-Type","image/jpeg");
headers.add("Content-Type","multipart/form-data");
headers.add("Content-Type","application/binary");
But nothing seems to be working, File is uploaded but always an 1 KB empty file.
Can someone please help me on this?
Thanks.
I just tried this and have an answer to this question, I just got it too complicated early. so here is the simple solution.
//make the headers as you wish
HttpHeaders headers = new HttpHeaders();
//I have not added createHeaders method here.
HttpHeaders headers = createHeaders(username+":"+password, headers);
for (MultipartFile multipartFile : attachments) {
try {
String url = remoteUri+"/api/v2/uploads.json?filename="+multipartFile.getName();
headers.add("Content-Type","application/binary");
HttpEntity httpEntity = new HttpEntity(multipartFile.getBytes(),headers);
ResponseEntity<YourResponseObject> response = restTemplate.exchange(url, HttpMethod.POST,httpEntity, YourResponseObject.class);
} catch (IOException e) {
LOG.error("Input output error while uploading the image");
} catch (Exception e) {
LOG.error("Error while uploading the image");
}
}

How to turn this POST cURL request into a java code

I have the following cURL request that I want to turn into java code to execute it with spring.
I use it to upload a file, the cURL request works correctly.
curl "https://mywebsite.service-now.com/api/now/attachment/file?table_name=incident&table_sys_id=fa4922f6db3ea30085a0f7871d961999&file_name=test.zip" --request POST --header "Accept:application/json" --header "Authorization:Basic cmVhbHRlc3QyOmJwb3N0QDEyMw==" --header "Content-Type: application/zip" -F "uploadFile=#test.zip"
I will use the following API:
https://docs.servicenow.com/bundle/geneva-servicenow-platform/page/integrate/inbound_rest/reference/r_AttachmentAPI-POST.html
I made a little research and found out that I have to use restTemplate to use 3rd party API.
I also wrote this:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
headers.add("Authorization", "Basic " + encodePassword());
return headers;
(I made the encodePassword method, that is correct. )
I tried a lot of other stuff but it doesn't work
You have to set the content-type header value to MediaType.MULTIPART_FORM_DATA. When this header is set, RestTemplate automatically marshals the file data along with some metadata.
//Headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
//parameter values
// the getTestFile( ) method generates a file on the fly and returns a FileSystemResource
MultiValueMap<String, Object> map= new LinkedMultiValueMap<>();
map.add("file", getTestFile();
...
//create request
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );

Invalid mimetype exception in Spring boot rest call

I am new to both Spring boot and rest calls.
I am trying to consume a rest service and I do not have any information about that rest API except URL. When I hit that URL from a browser I am getting a response as {key:value}. So, I assumed that it is a JSON response.
I am consuming it in spring boot as follows
restTemplate.getForObject(url, String.class) .
This is giving Invalid mime type "content-type: text/plain; charset=ISO-8859-1": Invalid token character ':' in token "content-type: text"
I assume that this error is because response content type is set to text/plain but it is returning JSON format.
EDIT:
Tried this way but did not work.
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters",headers);
ResponseEntity<String> result = restTemplate.exchange(url,HttpMethod.GET,
entity, String.class);
How to handle and solve it?
You might want to read about the request headers your REST API needs. Content-Type header specifies the media type of the request you're sending to the server. Because you're just getting data from the server you should set the Accept header to the kind of response you want i.e., Accept: application/json.
Unfortunately, you can't set headers using getForObject(). You could try this:
URL url = new URL("Enter the URL of the REST endpoint");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer content = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
}

RestTemplate Equivalent of cURL PUT

I can access an API with that cURL command:
curl -X PUT -H 'Content-type:application/json' --data-binary '["remaro"]' "http://localhost:4352/mypath"
I want to make it over Spring RestTemplate. My data is stored as String. I tried that but my server returns 400 bad request:
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>("\"" + dataVariable + "\"", headers);
restTemplate.put(http://localhost:4352/mypath, entity);
I've also send my variable as:
String dataVariable = "\"remaro\"";
but didn't work. I still get 400 error.
Use RestTemplate.exchange
Look at my example and change accordingly
String url = BASE_URI + "/update/{clusterId}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
ClusterDTO cluster = new ClusterDTO();
cluster.setClusterId(1L);
cluster.setClusterName("ClusterAV");
..........
HttpEntity<ClusterDTO> entity = new HttpEntity<ClusterDTO>(cluster,headers);
ResponseEntity<ClusterDTO> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, entity, ClusterDTO.class,1L);
I've just send it as:
"[\"" + dataVariable + "\"]"
and worked.

Having trouble recreating a cURL command in a Spring RestTemplate Using Headers

Here's the curl command I'm trying to recreate :
curl https://bannana-pajamas.com/services/data/v20.0/query/?q=BananaQuery -H 'Authorization: Bearer Banana_Token'
This curl command works just fine in my terminal and returns a json file.
Here's my attempt at recreating it in a Spring Rest Template:
//Create a rest template
RestTemplate rest = new RestTemplate();
System.out.println("This here is the token "+Banana_Token);
//Create the headers
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization","Bearer "+Banana_Token);
HttpEntity<String> entity = new HttpEntity<>(headers);
//Create the url
String url = "https://bannana-pajamas.com/services/data/v20.0/query/?q=BananaQuery";
String response;
try{
response = rest.exchange(url, HttpMethod.GET, entity, String.class).toString();
}catch(Exception error){
System.out.println("This still ain't working bro. Imma make this null till you get stuff right");
response = null;
}
return response;
When I run this, I get the following error:
org.springframework.web.client.HttpClientErrorException: 400 Bad Request
I've tried several of the similar answers on this site, but I keep getting that error. I probably missing something very minor.
Anybody have any ideas?
Thanks!

Resources