GWT RequestBuilder file download - servlets

I implemented servlet, that creates XLS file. I am making a request from UI (GWT, RequestBuilder). I get the response, but is it possible to get ready file (with auto "save as" dialog box)?
Should I somehow set headers or something?
Here is my code:
Request implementation
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, GWT.getModuleBaseURL() + "downloadLimitsFile");
try {
rb.setHeader("Content-type", "text/html");
Request response = rb.sendRequest("", new RequestCallback() {
public void onError(Request request, Throwable exception) {
Window.alert("fail");
}
public void onResponseReceived(Request request, Response response) {
Window.alert("file downloaded " + response.getText());
}
});
} catch (RequestException e) {
Window.alert("Failed to send the request: " + e.getMessage());
}
My servlet implementation
public void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setHeader("Content-Disposition", "attachment; filename=File.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
try {
workbook = fileExporter.prepareExcellFile();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
response.setStatus(HttpServletResponse.SC_OK);
OutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
response.flushBuffer();
}
It was working fine (auto file download) when I was using eg. Anchor with servlet URL, but I have to use RequestBuilder now to make a request.
Can someone help?

I am afraid it is not possible, at least you can use a third party library.
Adding the header "Content-Disposition" won't work.

Related

Reading InputStream of NANOHTTPD gives Socket TimeOut Exception

I am trying to read the InputStream from IHTTPSession.getInputStream() using the following code but its gives Socket TimeOut Exception every time.
private String readInStream(InputStream in){
StringBuffer outBuffer=new StringBuffer();
BufferedInputStream bis=new BufferedInputStream(in);
try {
while(bis.available()>0){
int ch= bis.read();
outBuffer.append((char)ch);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("DATA_Length", "outputBuffer :"+outBuffer.toString().length());
return outBuffer.toString();
}
i also tried the following Method but the same exception arises
private String readInStream(InputStream in){
String line="";
StringBuffer outBuffer=new StringBuffer();
BufferedReader rd=new BufferedReader(new InputStreamReader(in));
try {
while((line=rd.readLine()) != null){
outBuffer.append(line);
}
} catch (IOException e) {
Log.e("IOException", "IOException in readInStream:");
e.printStackTrace();
}
Log.e("DATA_Length", "outputBuffer :"+outBuffer.toString().length());
return outBuffer.toString();
}
Getting the content length from the header and reading up to it solved the problem.
Can confirm the accepted answer works (getting content length from the header and reading up to it). Here is some example code to turn the InputStream into a String:
try {
int contentLength = Integer.valueOf(session.getHeaders().get("content-length"));
String msg = new String(in.readNBytes(contentLength)); // the request body
} catch (IOException e) {
e.printStackTrace();
}
If you want to prevent a NullPointerException here, check whether the content-length header actually exists before parsing it to an integer.

Upload file from applet to servlet using apache fileupload

To accomplish:
Upload a file from my local to server using an applet and servlet using apache fileupload jar.
Tried:
I have used a simple jsp, with a browse button and posted the action to my servlet (where I used apache fileupload). I was successful in uploading the file to the server.
Issue:
I am trying to upload a file, from my local machine, using an applet. I do not want to manually select files, instead upload files that are present in a specific folder. For now I have hardcoded the folder. I am able to look at the folder and get the list of files I want to upload.
Also, I have successfully established a connection from my applet to servlet.
Issue arises at the upload.parseRequest(request) in the servlet. I'm thinking its because the applet cannot post to servlet's request object.
Also, I have set the request type to multipart/form-data in my applet.
Right now, I am trying to pass the absolute path of the file to servlet and upload.
I have seen other posts where byte stream data is passed from applet to servlet, but the servlet uses the traditional File.write.
For me, it is mandatory to achieve this using apache fileupload.
Please suggest on how to pass a file/file path from applet to servlet, where the upload is handled by apache fileupload.
Below are my FileUploadHandler (where the HTTP requests are handled) and FileUpload(which is my applet)
Below is my FileUpload Handler:
#WebServlet(name = "FileUploadHandler", urlPatterns = { "/upload" })
#MultipartConfig
public class FileUploadHandler extends HttpServlet {
String uploadFolder ="";
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost-servlet URL is: "
+ request.getRequestURL());
try {
uploadFolder = fileToUpload(request);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
uploadFolder = getServletContext().getRealPath("")+ File.separator;
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// process only if its multipart content
if (ServletFileUpload.isMultipartContent(request)) {
System.out.println("Yes, it is a multipart request...");
try {
List<FileItem> multiparts = upload.parseRequest(request);
System.out.println("Upload.parseRequest success !");
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File(uploadFolder + File.separator
+ name));
}
}
System.out.println("File uploaded to server !");
// File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to "
+ ex);
}
} if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}
doGet(request, response);
//request.getRequestDispatcher("/result.jsp").forward(request, response);
OutputStream outputStream = response.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject("Success !");
objectOutputStream.flush();
objectOutputStream.close();
}
private String fileToUpload(HttpServletRequest request) throws IOException,
ClassNotFoundException {
ServletInputStream servletIn = request.getInputStream();
ObjectInputStream in = new ObjectInputStream(servletIn);
String uploadFile = (String) in.readObject();
System.out.println("Value in uploadFolder is: " + uploadFile);
return uploadFile;
}
Below is the fileupload applet:
public class FileUpload extends Applet {
private JButton capture;
private JTextField textField;
private final String pathDirectory = "C:\\";
private final String captureConfirmMessage = "Are you sure you want to continue?";
private final String confirmDialogTitle = "Confirm upload";
final File folder = new File(pathDirectory);
public void init() {
upload= new JButton("Upload");
textField = new JTextField();
capture.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int selection = JOptionPane.showConfirmDialog(upload,
uploadConfirmMessage, confirmDialogTitle,
JOptionPane.YES_NO_OPTION);
if (selection == JOptionPane.OK_OPTION) {
listFilesForFolder(folder);
} else if (selection == JOptionPane.CANCEL_OPTION) {
JOptionPane.showMessageDialog(upload,
"You have aborted upload", "Upload Cancelled", 2);
}
}
});
add(upload);
add(textField);
}
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
try {
onSendData(fileEntry.getAbsolutePath());
System.out.println(fileEntry.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private URLConnection getServletConnection() throws MalformedURLException,
IOException {
// Open the servlet connection
URL urlServlet = new URL("http://localhost:8081/UploadFile/upload");
HttpURLConnection servletConnection = (HttpURLConnection) urlServlet
.openConnection();
// Config
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches(false);
servletConnection.setDefaultUseCaches(false);
servletConnection.setRequestProperty("Content-Type", "multipart/form-data;");
servletConnection.connect();
return servletConnection;
}
private void onSendData(String fileEntry) {
try {
// Send data to the servlet
HttpURLConnection servletConnection = (HttpURLConnection) getServletConnection();
OutputStream outstream = servletConnection.getOutputStream();
ObjectOutputStream objectOutputStream= new ObjectOutputStream(
outstream);
objectOutputStream.writeObject(fileEntry);
// Receive result from servlet
InputStream inputStream = servletconnection.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(
inputStream);
String result = (String) objectInputStream.readObject();
objectInputStream.close();
inputStream.close();
out.flush();
out.close();
// Display result on the applet
textField.setText(result);
} catch (java.net.MalformedURLException mue) {
mue.printStackTrace();
textField.setText("Invalid serlvetUrl, error: " + mue.getMessage());
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
textField.setText("Couldn't open a URLConnection, error: "
+ ioe.getMessage());
} catch (Exception e) {
e.printStackTrace();
textField.setText("Exception caught, error: " + e.getMessage());
}
}
public void paint(Graphics g) {
g.drawString("Click the button above to capture", 5, 50);
}
I could finally succeed posting the request to the servlet from the applet.
It was a simple logic that I was missing. I did not add the header and trailer while posting to the servlet, which was the key, in the servlet to identify the incoming request as a multipart data.
FileInputStream fileInputStream = new FileInputStream(new File(
fileEntry));
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream
.writeBytes("Content-Disposition: form-data; name=\"upload\";"
+ " filename=\"" + fileEntry + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
System.out.println(fileEntry + " uploaded.");
}
// send multipart form data necesssary after file data
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
I added the header and trailer and also used this to create the URL connection.
private URLConnection getServletConnection() throws MalformedURLException,
IOException {
// Open the servlet connection
URL urlServlet = new URL("http://localhost:8083/UploadFile/upload");
HttpURLConnection servletConnection = (HttpURLConnection) urlServlet
.openConnection();
// Config
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches(false);
servletConnection.setDefaultUseCaches(false);
servletConnection.setRequestMethod("POST");
servletConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + this.boundary);
servletConnection.setRequestProperty("Connection", "Keep-Alive");
servletConnection.connect();
return servletConnection;
}
Then, in the servlet, I was just reading the data using upload.ParseRequest(request).
Thank you for the help.

Upload file to my application on host by using servlet

I have a serlvet to upload file ... It work on my server, i upload to "http://localhost:8084/TestAmazon" and it work ... but we deploy my web application to host and upload file it not work ... please help me
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String relativeWebPath = "/image";
String absoluteFilePath = getServletContext().getRealPath(relativeWebPath);
if (ServletFileUpload.isMultipartContent(request)) {
try {
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File(absoluteFilePath + File.separator + name));
}
}
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception e) {
request.setAttribute("message", "File Upload Failed due to " + e);
}
} else {
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("result.jsp").forward(request, response);
}
i got an error:
exception
javax.servlet.ServletException: Servlet execution threw an exception
root cause
java.lang.NoSuchMethodError: org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload.parseRequest(Ljavax/servlet/http/HttpServletRequest;)Ljava/util/List;
sample.ProcessServlet.doPost(ProcessServlet.java:73)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

Get Action Name from Servlet Request

I have ABC.action which invokes the doFilter method of Filter Class which is configured properly in web.xml
I need to find action name from request object. How can i achieve this?
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
long t1 = System.nanoTime();
filterChain.doFilter(request, response);
long t2 = System.nanoTime();
long time = t2 - t1;
// Just writing statistics to servlet's log
System.out.println("## " +
"ArriveTime ns " + t1 + " Departtime ns " + t2 + " ServiceTime : " + time);
// System.out.println("Time taken to process request to "
// + ((HttpServletRequest) request).getRequestURI()
// + ": " + totalTime + " ms.");
}
Try below code(working in JBOSS).
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain fc) throws IOException, ServletException {
System.out.println("Request");
System.out.println(req);
// req instance of HttpServletRequest
if (req instanceof HttpServletRequest) {
HttpServletRequest httpReq = (HttpServletRequest) req;
System.out.println(httpReq.getRequestURI());
} else {
// req is not instance of HTTPServletRequest then try reflection
try {
Class clazz = Class
.forName("org.apache.catalina.connector.RequestFacade");
Method method = clazz.getMethod("getContextPath", new Class[0]);
String actionName = (String) method.invoke(req, new Object[0]);
System.out.println(actionName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Tomcat returns http response code 400

I was googling for a long time, but still can't find a solution to my case.
My Tomcat sometimes returns an exception :
Error in postRequest(): Server returned HTTP response code: 400 for URL: http://localhost:80/CITIUS2/webresources/entities.personainterna/
Sometimes it works and sometimes it returns this exception, so I really don't know what is the reason...
Connection function:
public static String excutePost(String targetURL, String urlParameters) throws UnsupportedEncodingException {
URL url;
HttpURLConnection connection = null;
String responseXML = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
byte[] requestXML = urlParameters.getBytes();
connection.setRequestProperty("Content-Length", String.valueOf(requestXML.length));
connection.setRequestProperty("Content-Type", "application/xml; charset=utf-8");
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
// Send the String that was read into postByte.
OutputStream out = connection.getOutputStream();
out.write(requestXML);
out.close();
// Read the response and write it to standard out.
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader br = new BufferedReader(isr);
String temp;
String tempResponse = "";
//Create a string using response from web services
while ((temp = br.readLine()) != null) {
tempResponse = tempResponse + temp;
}
responseXML = tempResponse;
br.close();
isr.close();
} catch (java.net.MalformedURLException e) {
System.out.println("Error in postRequest(): Secure Service Required");
} catch (Exception e) {
System.out.println("Error in postRequest(): " + e.getMessage());
}
return responseXML;
}
# Edit:
In general build is successful, there are no errors, only this one in the Apache Tomcat's output window.
Rest method:
#POST
#Consumes({"application/xml", "application/json"})
public Response create(Personainterna entity) {
try {
getJpaController().create(entity);
return Response.created(URI.create(entity.getPersonaId().toString())).build();
} catch (Exception ex) {
return Response.notModified(ex.getMessage()).build();
}
}

Resources