Spring boot return application/pdf with a ResponseEntity<Resource> - rest

In my springboot application, I try to return a pdf file with a ResponseEntity-Resource- to mock a service. So I can't change the return type of this method.
My code :
#RequestMapping(
value = "/pdf",
produces = MediaType.APPLICATION_PDF_VALUE,
method = RequestMethod.GET
)
public ResponseEntity<Resource> getpdf() {
try {
ClassPathResource pdfFile = new ClassPathResource("sample.pdf");
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type");
headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
headers.add(HttpHeaders.PRAGMA, "no-cache");
headers.add(HttpHeaders.EXPIRES, "0");
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + pdfFile.getFilename());
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);
log.info("pdfFile.contentLength() : " + pdfFile.contentLength());
return ResponseEntity
.ok()
.headers(headers)
//.contentLength(pdfFile.contentLength())
//.contentType(MediaType.APPLICATION_PDF)
.body(new InputStreamResource(pdfFile.getInputStream()));
} catch (IOException e) {
log.error("Couldn't serialize response for content type ", e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
When I try to call this get with postman or swagger I have a 406 with response header :
{
"date": "Fri, 02 Nov 2018 14:04:44 GMT",
"content-length": "0",
"content-type": null
}
Does anyone have an idea?
Swagger response

way too complex.. downloading a file is much more easy
#GetMapping(value="printing/",produces= MediaType.APPLICATION_PDF_VALUE)
public #ResponseBody byte[] print(#RequestParam("filterParam") String filterParam) {
try {
FileInputStream fis= new FileInputStream(new File("path to your file"));
byte[] targetArray = new byte[fis.available()];
fis.read(targetArray);
return targetArray;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

You can remove produces = MediaType.APPLICATION_PDF_VALUE.
There is no need to add produces = MediaType.APPLICATION_PDF_VALUE, in RequestMapping as it seems to try to convert the ResponeBody internally.
Below line of code is enough which you are already using.
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);

Related

Httpput from an InputStreamEntity throwing 501

I am reading from Object Storage and making a httpPut call to another target URL, but this call fails with 501 Method Not Implemented. Not sure what I am doing wrong.
import com.oracle.bmc.objectstorage.responses.GetObjectResponse;
...
...
GetObjectResponse getResponse =
client.getObject(
GetObjectRequest.builder()
.namespaceName(namespaceName)
.bucketName(bucketName)
.objectName(objectName)
.build());
try (final InputStream fileStream = getResponse.getInputStream()) {
InputStreamEntity entity = new InputStreamEntity(fileStream, -1);
entity.setContentType("text/html; charset=utf-8");
HttpPut putRequest = new HttpPut("https://MYURL");
putRequest.setEntity(entity);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse response= httpClient.execute(putRequest);
if (response != null) {
// FOR DEBUGGING System.out.println(response.getStatusLine().getStatusCode());
}
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}}

Keycloak PUT REST 415

I am getting the following error message when trying to CALL REST API of Keycloak used HttpClient.The code as following:
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
String token = request.getHeader("X-Auth-Token");
String url = authUrl + "/admin/realms/fast/users/"+userId+"/reset-password";
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
httpPut.addHeader("Authorization", token);
httpPut.addHeader("Content-Type ", "application/json");
List<NameValuePair>list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("type", "password"));
list.add(new BasicNameValuePair("value",userPassDO.getNewPassword()));
list.add(new BasicNameValuePair("temporary","true"));
UrlEncodedFormEntity entity;
try {
entity = new UrlEncodedFormEntity(list,"UTF-8");
httpPut.setEntity(entity);
CloseableHttpResponse response = closeableHttpClient.execute(httpPut);
HttpEntity et = response.getEntity();
InputStream in = et.getContent();
int stat= response.getStatusLine().getStatusCode();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The response after execute put request show an error
"HttpResponseProxy{HTTP/1.1 415 Unsupported Media Type [Server: nginx/1.15.3, Date: Tue, 30 Oct 2018 09:13:03 GMT, Content-Length: 0, Connection: keep-alive] [Content-Length: 0,Chunked: false]"
Does anyone have any ideas or encountered this problem?

How do i return a powerpoint (.pptx) file from REST response in springMVC

I am generating a powerpoint file(.pptx) and i would like to return back this file when a REST call happens. But now am able to get only .File type extension.
#RequestMapping(value = "/ImageManagerPpt/{accessionId}", method = RequestMethod.GET, produces = "application/ppt")
public ResponseEntity<InputStreamResource> createPptforAccessionId(#PathVariable("accessionId") String accessionId,HttpServletResponse response) throws IOException** {
System.out.println("Creating PPT for Patient Details with id " + accessionId);
File pptFile = imageManagerService.getPptForAccessionId(accessionId);
if (pptFile == null) {
System.out.println("Patient Id with id " + accessionId + " not found");
return new ResponseEntity<InputStreamResource>(HttpStatus.NOT_FOUND);
}
InputStream stream = null;
try {
stream = new FileInputStream(pptFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ClassPathResource classpathfile = new ClassPathResource("Titlelayout3.pptx");
InputStreamResource inputStreamResource = new InputStreamResource(stream);
return ResponseEntity.ok().contentLength(classpathfile.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(classpathfile.getInputStream()));
}
-Bharat
Have you tried, this?
InputStream stream = new InputStream(pptFile);
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
You will get file as you put into the InputStream.

Android:Restful webservice put method showing response with status 405 Method not allowed

I am getting data by http get through restful webservice hosted on IIS7 but when i am trying to put data i am having problem
MY code for put is as follows:
public Void put(String url, List<NameValuePair> data)
{
String response="";
HttpPut put = new HttpPut(url);
String dataString=data.toString();
HttpClient httpclient = new DefaultHttpClient();
try {
StringEntity entity = new StringEntity(dataString, "UTF-8");
entity.setContentType("x-www-form-urlencoded; charset=UTF-8");
put.setEntity(entity);
HttpResponse httpResponse1 = httpclient.execute(put);
StatusLine statusLine = httpResponse1.getStatusLine();
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
}
The response i am getting is 405 Method not allowed, Can anybody tell me what is the problem?
You just have to uncheck webdave feature from the IIS menu which is in the window's features

Applet: SocketException Unknown proxy type : HTTP

I have no problems running my applet in Eclipse, but if I sign and run it in browser this happend
10-abr-2013 19:54:37 org.apache.http.impl.client.DefaultHttpClient tryConnect
INFO: I/O exception (java.net.SocketException) caught when connecting to the target host: Unknown proxy type : HTTP
10-abr-2013 19:54:37 org.apache.http.impl.client.DefaultHttpClient tryConnect
INFO: Retrying connect
…
java.net.SocketException: Unknown proxy type : HTTP
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
Here im trying to upload some files using org.apache.http.client.HttpClient
public static String executeMultiPartRequest(String urlString, File file,
String fileName, String fileDescription) {
System.out.println("SET URI " + urlString);
HttpPost postRequest = new HttpPost(urlString);
try {
MultipartEntity multiPartEntity = new MultipartEntity();
// The usual form parameters can be added this way
multiPartEntity.addPart("fileDescription", new StringBody(
fileDescription != null ? fileDescription : ""));
multiPartEntity.addPart("fileName", new StringBody(
fileName != null ? fileName : file.getName()));
/*
* Need to construct a FileBody with the file that needs to be
* attached and specify the mime type of the file. Add the fileBody
* to the request as an another part. This part will be considered
* as file part and the rest of them as usual form-data parts
*/
FileBody fileBody = new FileBody(file, "application/octect-stream");
multiPartEntity.addPart("attachment", fileBody);
// multiPartEntity.addPart("path", Charset.forName("UTF-8"));
postRequest.setEntity(multiPartEntity);
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
return executeRequest(postRequest);
}
private static String executeRequest(HttpRequestBase requestBase) {
String responseString = "";
InputStream responseStream = null;
HttpClient client = new DefaultHttpClient();
try {
System.out.println("LISTO PARA ENVIAR A" + requestBase.getURI());
HttpResponse response = client.execute(requestBase);
if (response != null) {
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
responseStream = responseEntity.getContent();
if (responseStream != null) {
BufferedReader br = new BufferedReader(
new InputStreamReader(responseStream));
String responseLine = br.readLine();
String tempResponseString = "";
while (responseLine != null) {
tempResponseString = tempResponseString
+ responseLine
+ System.getProperty("line.separator");
responseLine = br.readLine();
}
br.close();
if (tempResponseString.length() > 0) {
responseString = tempResponseString;
}
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (responseStream != null) {
try {
responseStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
client.getConnectionManager().shutdown();
return responseString;
}
What its wrong?
Applet is signed and compiled with java 1.6, httpclient-4.1.3.jar
For those with this problem, the solution was here http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e571 getting the JRE Proxy.
DefaultHttpClient client = new DefaultHttpClient () ;
ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
client.getConnectionManager().getSchemeRegistry(),
ProxySelector.getDefault());
client.setRoutePlanner(routePlanner);
HttpResponse response = client.execute(requestBase) ;
Then i signed all libraries httpcore-4.2.3.jar, httpmime-4.2.3.jar and httpclient-4.2.3.jar.