Upload file to ZenDesk using Java Jersey - java

I am attempting to replicate, using java and Jersey, uploading a file to ZenDesk, to be used as an attachment on a ticket. The example code from ZenDesk uses curl with a --data-binary parameter, referencing a file on disk.
I am using an SDK client that I found on git as my starting point, everything about this SDK works with the exception of file uploads.
Here is the code that I currently have doing the upload:
File fileToUpload = new File(attachment.getUrl());
FileDataBodyPart filePart = new FileDataBodyPart(attachment.getFilename(), fileToUpload, MediaType.APPLICATION_OCTET_STREAM_TYPE);
FormDataContentDisposition.FormDataContentDispositionBuilder builder = FormDataContentDisposition.name(filePart.getName());
builder.fileName(fileToUpload.getName());
builder.size(fileToUpload.length());
filePart.setFormDataContentDisposition(builder.build());
FormDataMultiPart multiPart = new FormDataMultiPart();
multiPart.bodyPart(filePart);
multiPart.field("filename", attachment.getFilename());
ClientResponse cr = rootResource.path("/api/v2/uploads.json")
.accept(MediaType.APPLICATION_JSON_TYPE)
.type(MediaType.MULTIPART_FORM_DATA_TYPE)
// .post(AttachmentWrapper.class, attachment);
.post(ClientResponse.class, multiPart);
This results in an internal server error 500 response from ZenDesk.
I have tried several different arrangements of the parameters, with no success.
The project that I'm using as a starting point is located here: Zendesk-API-Client
The problem with the original project is that the file being uploaded doesn't have its content available on the ZenDesk server, it is just the JSON defining the file.
Thanks,
Allen

Related

In Spring Boot Java Extracting the zip file from response without physically saving it

In Spring Boot the zip file that comes as a response has a corrupted structure before saving, but there is no problem when I save it physically. I need to take the file in the zip file and process the information in the database, but I cannot physically download this file because I am using GCP. How can I extract the file in this zip file that comes as a response?. How can I solve this please help.
Here is what it looks like in response.body() before saving (part of it):
"PK C`iUq �=n 緰) bu_customerfile_22110703_B001_10292121141�]i��������RI%U�v��CJ� ���×��My��y/ίϹ�������=>����}����8���׿}~}~yz�������ͲL��
�o�0�fV�29f�����6΋$K�c$�F��/�8˳�L��_�QaZ-q�F�d4γE�[���(f�8�D�0��2_��P"�I�A��D��4�߂�����D��(�T�$.��<�,���i]Fe�iM�q<ʨ�Olmi�(&���?�y�y4��<��Q�X�ޘp�#�6f-.F����8����"I㢨ҤU]�E��WI� %#������(W�8*0c�p:L��:� �}�G����e<����a�"
Here is the request call:
OkHttpClient client1 = new OkHttpClient().newBuilder()
.build();
MediaType mediaType1 = MediaType.parse("text/plain");
RequestBody body1 = RequestBody.create(mediaType1, "");
Request request1 = new Request.Builder()
.url(vers)
.method("POST", body1)
.addHeader("Cookie", "ASP.NET_SessionId=44dxexdxass5mtf00udjfwns")
.build();
Response response1 = client1.newCall(request1).execute();
String data = response1.body().string();
Would it be a matter of encoding type? String is of type UTF-16 (I think). Try a different datatype that is more like an array/vector of bytes.
Try something like what is mentioned here:
Having trouble reading http response into input stream
Update: Get the response as a stream of bytes and feed it into a ZipInputStream object as shown here https://zetcode.com/java/zipinputstream/#:~:text=ZipInputStream%20is%20a%20Java%20class,both%20compressed%20and%20uncompressed%20entries.
Then iterate over the contained files to find the one you need. Then retrieve the stream associated with the zipped file. Then you can read from there. (I realize that is a bit of handwaving, but it's been a while since I used Zip files and Java.) That should get you down the correct path.

Jersey multipart file download copies MIMEXXX.tmp files in client's "java.io.tmpdir" folder

My requirement is to download large file from server using rest API, I am using java with Jersey framework and MULTIPART_FORM_DATA type for sending and receiving the file. API is working fine, but the problem is at client side when I do response.readEntity(FormDataMultiPart.class) it copies the entire multipart data in java's "java.io.tmpdir" folder. Is there any way to avoid it or any api/configuration to change jersey multipart temp directory path (other than "java.io.tmpdir").
Below is my sample client code:
Invocation.Builder invocationBuilder = webTarget.request(MediaType.MULTIPART_FORM_DATA_TYPE);
Response response = invocationBuilder.get();
FormDataMultiPart objMultiPart = response.readEntity(FormDataMultiPart.class);
List<BodyPart> listBodyPart = objMultiPart.getBodyParts();
try(FileOutputStream out = new FileOutputStream(filePath.toFile(), true)){
for(BodyPart part : listBodyPart) {
//code to process each bodypart
}
}

Can not download docx file using SharePoint file download REST API & Java

I got the attached img value as response from the SharePoint server but can not write it on the docx file. The file download API using Postman is giving same response and if I save Postman response to docx file then it is saving perfectly but not from Java side. If I write same response to a docx file using Java, the file is corrupted.
I am using this REST API to download the file from Sharepoint:
SiteURL/_api/web/getfilebyserverrelativeurl('relativeURL/Shared Documents/test.docx')/$value
Most likely server is returning the document (docx) as binary (application/octet-stream). Your code saves the document's string representation:
ResponseEntity<String> response = restTemplate.exchange(fileUrl, HttpMethod.GET, request, String.class);
String responseStrFromSharePoint = response.getBody();
That's why the file could not be decoded by application. Instead save the exact binary (bytes) returned by the server as the following snippet shows:
ResponseEntity<byte[]> response = restTemplate.exchange(fileUrl, HttpMethod.GET, request, byte[].class);
byte[] responseStrFromSharePoint = response.getBody();
Other parts of the code seems fine.

Unable to play mp4 video uploaded to AWS S3 using pre-signed URL

I'm uploading a mp4 video to AWS S3 using a pre-signed URL, the upload succeeds but when I try to download the video from S3 and play it in a media player (VLC or quickTime), it doesn't play!.
Generated pre-signed URL works fine with mp3 but the same problem as above also occurs for WAV and FLAC.
Code to generate the pre-signed url:
public String getPreSignedS3Url( final String userId, final String fileName )
{
Date expiration = new Date();
long expTimeMillis = expiration.getTime();
expTimeMillis += urlExpiry;
expiration.setTime(expTimeMillis);
String objectKey = StringUtils.getObjectKey( userId, fileName );
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
recordingBucketName, objectKey)
.withMethod(HttpMethod.PUT)
.withExpiration(expiration);
URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
return url.toString();
}
After I get the pre-signed URL from the method above, I make a HTTP PUT request from Postman with the multipart/form-data in the request body like this:
-H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
-F 'file=#/Users/john/Downloads/sampleDemo.mp4'
pre-signed url looks like this:
https://meeting-recording.s3.eu-west-2.amazonaws.com/331902257/sampleDemo.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20190720T125751Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3599&X-Amz-Credential=AKIAZDSMLZ3VDKNXQUXH%2F20190720%2Feu-west-2%2Fs3%2Faws4_request&X-Amz-Signature=dfb8054f0738e07e925e9880e4a8e5ebba0a1bd3c84a3ec78913239f65221992
I tried to set the content type to mp4 in the getPreSignedS3Url() method using generatePresignedUrlRequest.setContentType( "video/mp4" ); and add Content-Type : "video/mp4" in the HTTP PUT request header but it didn't work and it fails with an error Signature doesn't match.
I'm using S3 as my personal back-up hard-drive, I expect to upload video and audio files to S3 using a pre-signed URL, download them at some point in the future and be able to play them, but I'm unable to play them after I have downloaded them.
Does anyone know what could be causing this?
PUT requests to S3 don't support multipart/form-data. The request body needs to contain nothing but the binary object data. If you download your existing file from S3 and open it with a text editor, you'll find that S3 has preserved the multipart form structure inside the file, instead of interpreting it as a wrapper for the actual payload.
To add to the above answer (for future readers), I was using formData() like below to send the put request. Adding the file directly to the payload worked for me.
Don't do this:
var bodyData = new FormData();
bodyData.append('file', video);
axios.put(res?.data?.uploadURL, bodyData, {
Instead, do this:
axios.put(res?.data?.uploadURL, video, {

Download a PDF file via REST service with “Content-Disposition” Header in java

I am trying to download a PDF file from a response of Java REST call after custom authentication check.
I can see downloaded file but it is empty file.
Below is my code snippet.
//Custom HTTPClient
HTTPAuthClient client = new HTTPAuthClient(url,username,password)
Request request = new Request(downloadURL); //I'm downloading file content of an URL.
Response response = client.executeGet(request);
String response1 = response.getResponseBody();
InputStream is = new ByteArrayInputStream(response.getBytes());
response.setContentType("Content-type",application/pdf); //here response is //javax.servlet.HttpServletResponse
response.setHeader("Content-Disposition","attachment;filename="myfile.pdf");
IOUtils.copy(is,response.getOutPutStream());
response.flushBuffer();
With this code I could download the file but when I open the file and verified there is no data.
As part of response body also I can see some data.
Could you please help me out where I'm doing mistake I tried many options but did not find solution.
How can you use setContentType like this
response.setContentType("Content-type",application/pdf);
If only one avalible param in this method is String void setContentType(String type) so your method should be:
response.setContentType("application/pdf");
Java Doc to be sure.

Categories

Resources