How to integrate signed URL in java? - java

I am trying to useDOLBY.IO's media API to transcode and save the output file to cloud. I have two URLs {URL1:input to dolby; URL2: to store output from dolby}. And both the URLs are signed URLs from the same cloud.
I tried using some java code to accomplish this but in the end I still can't get the result.
Here is the code:
#PostMapping("/transcode")
public String Video_Transcode1() throws IOException, JSONException {
OkHttpClient client = new OkHttpClient();
String data=generate_Access_token( );
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"inputs\":[{\"source\":\"https://vb-object-storage.ap-south-1.linodeobjects.com/The%20Hindu%20Daily%20News%20Analysis%20__%203rd%20July%202022%20__%20UPSC%20Current%20Affairs%20__%20Prelims%20%2722%20%26%20Mains%20%2722%28360%29.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20220707T073322Z&X-Amz-SignedHeaders=host&X-Amz-Expires=604799&X-Amz-Credential=ZVADROBVHWLK1FOYT225%2F20220707%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Signature=0aa4b388ea3197dd8a03253f5f7313b4209b8acf5e0a4308dc5e543801d22c73\"}],\"outputs\":[{\"kind\":\"mp4\",\"destination\":\"https://vb-object-storage.ap-south-1.linodeobjects.com/The%20Hindu%20Daily%20News%20Analysis%20__%203rd%20July%202022%20__%20UPSC%20Current%20Affairs%20__%20Prelims%20%2722%20%26%20Mains%20%2722%28360%29.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20220707T073322Z&X-Amz-SignedHeaders=host&X-Amz-Expires=604799&X-Amz-Credential=ZVADROBVHWLK1FOYT225%2F20220707%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Signature=0aa4b388ea3197dd8a03253f5f7313b4209b8acf5e0a4308dc5e543801d22c73\"}]}");
Request request = new Request.Builder()
.url("https://api.dolby.com/media/transcode")
.post(body)
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json")
.addHeader("Authorization","Bearer "+data)
.build();
Response response = client.newCall(request).execute();
return response.toString();
}
Here the data is generated from another function (ie:Access token)
I have encoded two URLs as json here:
RequestBody body = RequestBody.create(mediaType, "{\"inputs\":[{\"source\":\"https://vb-object-storage.ap-south-1.linodeobjects.com/The%20Hindu%20Daily%20News%20Analysis%20__%203rd%20July%202022%20__%20UPSC%20Current%20Affairs%20__%20Prelims%20%2722%20%26%20Mains%20%2722%28360%29.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20220707T073322Z&X-Amz-SignedHeaders=host&X-Amz-Expires=604799&X-Amz-Credential=ZVADROBVHWLK1FOYT225%2F20220707%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Signature=0aa4b388ea3197dd8a03253f5f7313b4209b8acf5e0a4308dc5e543801d22c73\"}],\"outputs\":[{\"kind\":\"mp4\",\"destination\":\"https://vb-object-storage.ap-south-1.linodeobjects.com/The%20Hindu%20Daily%20News%20Analysis%20__%203rd%20July%202022%20__%20UPSC%20Current%20Affairs%20__%20Prelims%20%2722%20%26%20Mains%20%2722%28360%29.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20220707T073322Z&X-Amz-SignedHeaders=host&X-Amz-Expires=604799&X-Amz-Credential=ZVADROBVHWLK1FOYT225%2F20220707%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Signature=0aa4b388ea3197dd8a03253f5f7313b4209b8acf5e0a4308dc5e543801d22c73\"}]}");
Is there any look around to bring the solution.

it looks like both signed URLs might be GET urls?
For the Dolby.io Transcode API, your inputs should be GET signed urls and your outputs should be PUT signed URLs.
Additionally, it also looks like you are using the same input path/filename and output path/filename:
https://vb-object-storage.ap-south-1.linodeobjects.com/The%20Hindu%20Daily%20News%20Analysis%20__%203rd%20July%202022%20__%20UPSC%20Current%20Affairs%20__%20Prelims%20%2722%20%26%20Mains%20%2722%28360%29.mp4
You will want to use different paths for input and output, something like:
https://vb-object-storage.ap-south-1.linodeobjects.com/output/outputfile.mp4
(note the "output" added to the path and the change of the output filename)

Related

How to solve android retrofit post image error 500

So I tried to upload image with multipart but i received 500 error code. I've tried it on postman and it worked well and it worked too with this code but without image. Am I wrong at multipart thing?
ApiService
Filepath
MediaType
Swagger
I think Scoped storage issue. Stream the file using input stream.
Try like below
contentResolver.openInputStream(it)?.use { inputStream ->
val tempFile = createTempFile(this, fileName, extension)
copyStreamToFile(it, tempFile)
val filePath = tempFile.absolutePath
val requestFile: RequestBody = File(filePath).asRequestBody(fileType?.toMediaTypeOrNull())
val body: MultipartBody.Part = MultipartBody.Part.createFormData("file", fileName, requestFile)
}

RestAssured + Java - how can I save to string or to file the Request that sent to the server?

Using intellij, Java and restassured:
I am sending the request as needed and I added this to my code:
public static Response PostInstinctQuery() throws IOException, ParseException {
PrintStream fileOutPutStream = new PrintStream(new File("request_log.txt"));
config = config().logConfig(new LogConfig().defaultStream(fileOutPutStream));
RestAssured.baseURI = BASEURI;
RequestSpecification request = RestAssured.given();
//Headers
request.header("Key",key);
request.body(getJson());
request.log().all();
Response response = request.post(PATH);
return response;
}
That is save the request in "request_log.txt" file.
so what is the problem ? the file shows the same request over and over.
If I use TestNG diff data then I would expect that the file will contain all the diff request.
And I really want the request to be able to save in a String variable for assert / report purposes also.
Thanks!
I think you can use RequestLoggingFilter to config one time, no need log().all().
OutputStream file = new FileOutputStream("request_log.txt");
PrintStream stream = new PrintStream(file, true);
RestAssured.filters(RequestLoggingFilter.logRequestTo(stream));

How to send list parameter with HTTPDELETE as RequestBody in java

Hi i have written a rest service to delete multiple files and i am trying to access the rest service.
My input to rest service will be List values which will be id of files that needs to be deleted.
For that i have written the below code
List<Long> ids=new ArrayList<Long>();
ids.add(4l);
ids.add(5l);
boolean status = false;
String jsonResponse = null;
DefaultHttpClient httpClient = null;
HttpResponse response = null;
try {
httpClient = new DefaultHttpClient();
StringBuilder url = new StringBuilder("http://localhost:8080/api/files");
URIBuilder builder = new URIBuilder();
URI uri = builder.build();
HttpDelete deleteRequest = new HttpDelete(uri);
//how to set list as Requestbody and send
response = httpClient.execute(deleteRequest);
}
Here i dont know how to set List as entity in request body and send. Can someone help me on this
A HTTP DELETE request should delete the resource identified by the URI. The body is not relevant. To delete a single resource:
DELETE /api/files/123
If you want to delete more than one file in a single request, model a collection of files as a resource. This could be done by listing more than one ID in the URL:
GET /api/files/123,456,789
This could return a JSON array with the details of the three files.
To delete these three files, execute a DELETE request agains the same URL:
DELETE /api/files/123,456,789

Mailgun API: Sending Inline Image with Spring's RestTemplate

The goal is to send an email with inline image. Everything is working well, except the image is not appearing in the email.
My approach is based on this Jersey-example of Mailgun's User Guide.
public static ClientResponse SendInlineImage() {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("api",
"YOUR_API_KEY"));
WebResource webResource =
client.resource("https://api.mailgun.net/v3/YOUR_DOMAIN_NAME" +
"/messages");
FormDataMultiPart form = new FormDataMultiPart();
form.field("from", "Excited User <YOU#YOUR_DOMAIN_NAME>");
form.field("to", "baz#example.com");
form.field("subject", "Hello");
form.field("text", "Testing some Mailgun awesomness!");
form.field("html", "<html>Inline image here: <img src=\"cid:test.jpg\"></html>");
File jpgFile = new File("files/test.jpg");
form.bodyPart(new FileDataBodyPart("inline",jpgFile,
MediaType.APPLICATION_OCTET_STREAM_TYPE));
return webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).
post(ClientResponse.class, form);
}
However, I need to use Spring's RestTemplate.
This is what I've got so far:
RestTemplate template = new RestTemplate();
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
// ... put all strings in map (from, to, subject, html)
HttpHeaders headers = new HttpHeaders();
// ... put auth credentials on header, and content type multipart/form-data
template.exchange(MAILGUN_API_BASE_URL + "/messages", HttpMethod.POST,
new HttpEntity<>(map, headers), String.class);
The remaining part is to put the *.png file into the map. Not sure how to do that. Have tried reading all its bytes via ServletContextResource#getInputStream, but without success: Image is not appearing in the resulting e-mail.
Am I missing something here?
This turned out to be a case where everything was set up correctly, but only a small detail prevented it from working.
map.add("inline", new ServletContextResource(this.servletContext,
"/resources/images/email-banner.png"));
For Mailgun you need to use the map-key "inline". Also, the ServletContextResource has a method getFilename(), which is used to resolve against the image tag. Thus, the image tag should have the following content id:
<img src="cid:email-banner.png"/>

Force Browser to cache JS response from Spring MVC

It seems somewhat awkward whenever I need to deal with custom responses data type on Spring MVC.
In my case, I need to return a JavaScript content. However, I want it to be cache.
So to clarify, this is not a static file case (<mvc:resources...), Instead it's a dynamic file generated on the server, that I do want to cache (i.e. HttpResponse 200 and HttpResponse 302).
In terms of code, on the client side I simply have:
<script src="<spring:url value='/some-file.js'/>"></script>
Than a SpringMVC controller:
#RequestMapping(value = "/some-file.js")
public ResponseEntity<String> resourceBundles(HttpServletRequest request, HttpServletResponse response, Locale locale) throws IOException {
responseHeaders.add("Cache-Control", "public, max-age");
responseHeaders.add("Content-Type", "text/javascript; charset=UTF-8");
responseHeaders.add("Expires", "max-age");
// Turn this into JSON response:
String someJson = "{ a:a, b;b};";
return new ResponseEntity<String>("var data = " + someJson, responseHeaders, HttpStatus.OK);
}
However, it seems that the browser is always trying to access this dynamic JS file.
Since this file is Session depended, I can not generate it and treat it as a static file.
Any suggestions?
This is the correct behavior. Most browsers will send you a GET request with a If-Modified-Since + time stamp to check whether a file has changed.
In the usual case, you'd use the time stamp to figure out whether the file has changed. But since it never changes in your case, you can reply with a 304 / HttpStatus.NOT_MODIFIED response without a response body (instead of 200 / OK).
That tells the browser that the file hasn't changed.
This should work:
#RequestMapping(value = "/some-file.js")
public ResponseEntity<String> resourceBundles(
HttpServletRequest request,
HttpServletResponse response, Locale locale) throws IOException {
Date lmod = session.getAttribute("lmod");
if( null == lmod ) {
lmod = new Date();
session.setAttribute("lmod", lmod);
}
responseHeaders.add("Last-Modified", lmod);
String ifModifiedSince = request.getHeader("If-Modified-Since");
if( null != ifModifiedSince ) { // You may want to compare lmod and ifModifiedSince here, too
return new ResponseEntity( responseHeaders, HttpStatus.NOT_MODIFIED );
}
... create first time response ...
}
Telling the browser Last-Modified will enable it to send you If-Modified-Since

Categories