BufferedReader for Pdf File in Java Servlet - java

My BufferedReader corrupts my Pdf file and writes everything in the first line.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
createPdf();
response.setHeader("Content-disposition","attachment; filename=\""+"myPdf.pdf"+"\"");
BufferedReader reader = null;
try {
File file = new File("myPath\\myNewPdf.pdf");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
response.getWriter().append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I just want to read the Pdf and write it in a new one to make it a download.

this did the trick thx #user207421
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
createPdf();
response.setHeader("Content-disposition","attachment; filename=\""+"myNewPdf.pdf"+"\"");
InputStream inputStream = new FileInputStream("myPath\\myPdf.pdf");
int data;
while( (data = inputStream.read()) >= 0 ) {
response.getWriter().write(data);
}
inputStream.close();
}

Related

How do I change this try-finally to try-with-resources?

This is the code.
Most of the examples do not let me to use response variable which I got with the function's parameter.
Is there anyone who can help me with this question?
Or is it better to use try-finally than try-with-resources in this case?
public void func(HttpServletResponse response) throws IOException {
OutputStream out = null;
InputStream in = null;
try {
out = response.getOutputStream();
ResponseEntity<Resource> url = getUrl();
Resource body = url.getBody();
in = body.getInputStream();
FileCopyUtils.copy(in, out);
} finally {
if (out != null) {
try {
out.close();
}catch (IOException e) {
}
}
if (in != null) {
try {
in.close();
}catch (IOException e) {
}
}
}
}
You can do it this way using try-with-resources construct
public void func(HttpServletResponse response) throws IOException {
try (OutputStream out = response.getOutputStream) {
out = response.getOutputStream();
ResponseEntity<Resource> url = getUrl();
Resource body = url.getBody();
try(InputStream in = body.getInputStream()) {
FileCopyUtils.copy(in, out);
}
}
}

java.io.IOException: Stream closed in HandlerInterceptor

I have a problem with Interceptor in SpringBoot I am trying to read the body in a request at preHandle() method.
public class LogInterceptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
System.out.println("Error reading the request body...");
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
System.out.println("Error closing bufferedReader...");
}
}
}
String body = stringBuilder.toString();
System.out.println("--Body--"+body);
}
}
This code print body correctly but when I try to made a POST petition with Postman I receive the following error.
I/O error while reading input message; nested exception is java.io.IOException: Stream closed
If I do the same petition witouth this code the petition works correctly.
Could anyone help to me ? Or said a better solution to intercept body ?

Application does not generate report on a server

I have a JasperReports report generated via a Java web application. The application located at my localhost page: 8084/app/pages.jsp (where is the form that is sending to the servlet) generates the report perfectly, the problem occurred that when I generate the report served my site.com / app / pages.jsp got this result, it seems that the server does not interpret the file. pdf or her generation.
is a linux server running apache
This comes from an old project, you addresponse.setContentType("application/pdf"); and write as output the bytes of the file..
public class ReportSintesiServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/pdf");
Lookup<IReportGeneration> l = new Lookup<IReportGeneration>(true, IReportGeneration.class);
IReportGeneration g = null;
try {
g = l.lookup();
} catch (Exception ex) {
return;
}
if (g != null) {
String param = request.getParameter("idc");
System.out.println("genero il report per idc " + param);
Integer idc = Integer.parseInt(param);
byte[] doc = (byte[]) g.generaSintesiAccordoIniziale(idc);
if (doc != null) {
FilePathManager fpm = new FilePathManager();
String pathtofile = fpm.pathToNuovaSintesi(idc);
File temp = new File(pathtofile);
FileUtil.writeBytesToFile(temp, doc);
response.addHeader("Content-Disposition", "attachment; filename=" + temp.getName());
response.setContentLength((int) temp.length());
FileInputStream fileInputStream = new FileInputStream(temp);
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
}
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
PS: I removed some pieces of code which was not helpful in this case, as you can see you miss all the part of the logic for error management.

HttpServletRequestWrapper not working as expected

I need to log request body content. So I used filter and HttpServletRequestWrapper as below for this purpose. But when I invoke request.getParameter from my servlet I'm not getting anything. Appreciate any help
RequestWrapper Code
public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
private static final Log log = LogFactory.getLog(MultiReadHttpServletRequest.class);
private ByteArrayOutputStream cachedBytes;
public MultiReadHttpServletRequest(HttpServletRequest request) throws IOException {
super(request);
cachedBytes = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int n;
while (-1 != (n = request.getInputStream().read(buffer))) {
cachedBytes.write(buffer, 0, n);
}
}
#Override
public ServletInputStream getInputStream() throws IOException {
return new CachedServletInputStream();
}
private class CachedServletInputStream extends ServletInputStream {
private ByteArrayInputStream input;
public CachedServletInputStream() {
input = new ByteArrayInputStream(cachedBytes.toByteArray());
}
#Override
public int read() throws IOException {
return input.read();
}
}
String getRequestBody() throws IOException {
StringBuilder inputBuffer = new StringBuilder();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(getInputStream()));
try {
do {
line = reader.readLine();
if (null != line) {
inputBuffer.append(line.trim());
}
} while (line != null);
} catch (IOException ex) {
log.error("Unable to get request body from request: " + ex.getMessage(), ex);
} finally {
try {
reader.close();
} catch (IOException e) {
// Just log error
log.warn("Unable to close BufferReader: " + e.getMessage(), e);
}
}
return inputBuffer.toString().trim();
}
My filter code
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
if ((servletRequest instanceof HttpServletRequest) && (messageTracerApiClient != null)) {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
MultiReadHttpServletRequest bufferedRequest = new MultiReadHttpServletRequest(httpServletRequest);
Message message = new Message();
message.setHost(bufferedRequest.getLocalAddr());
message.setPayload(bufferedRequest.getRequestBody());
messageTracerApiClient.publishMessage(message);
System.out.println("bufferedRequest param= " + bufferedRequest.getParameterMap().size());
filterChain.doFilter(bufferedRequest, servletResponse);
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
Please note bufferedRequest.getParameterMap().size() also print 0 even there are parameter.

Why do I need to catch a close() exception in BufferedReader but not in PrintWriter?

I have a simple file read and write function.
private void WriteToFile(String filename, String val) {
PrintWriter outStream = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filename);
outStream = new PrintWriter(new OutputStreamWriter(fos));
outStream.print(val);
outStream.close();
} catch (Exception e) {
if (outStream != null) {
outStream.close();
}
}
}
private String ReadFile(String filename) {
String output = "";
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
output = br.readLine();
br.close();
} catch (Exception e) {
if (br != null) {
br.close();
}
}
return output;
}
When building I get:
unreported exception java.io.IOException; must be caught or declared to be thrown
br.close();
^
Why do I need to catch br.close but it doesn't complain about WriteToFile's close()?
Taken from the source code of java.io.PrintWriter:
public void close() {
try {
synchronized (lock) {
if (out == null)
return;
out.close();
out = null;
}
}
catch (IOException x) {
trouble = true;
}
}
The IOException was eaten up within the close() method in PrintWriter
From source code of java.io.BufferedReader:
public void close() throws IOException {
synchronized (lock) {
if (in == null)
return;
in.close();
in = null;
cb = null;
}
}
BufferedReader throws the IOException.
That should answer your question.
Why do I need to catch br.close but it doesn't complain about WriteToFile's close()?
You can check the Java Docs for this. The close() method for BufferedReader :
public void close()
throws IOException
And the close() method for PrintWriter :
public void close()
That answer's your question as to why JVM doesn't complain. Because it is clear from the method signatures;
PrinterWriter.close() doesn't throw any Exception.
If you call fos.close(), it will ask you to catch/throw the exception.
In the PrintWriter.java. The exception is caught and handled. So you needn't catch it while using.
Java Source:
public void close() {
try {
synchronized (lock) {
if (out == null)
return;
out.close();
out = null;
}
}
catch (IOException x) {
trouble = true;
}
}
But in BufferedReader the exception is thrown. So you have to catch it when using.
Java Source:
public void close() throws IOException {
synchronized (lock) {
if (in == null)
return;
in.close();
in = null;
cb = null;
}
}

Categories

Resources