I am new in GWT and I am working on a project where GWT is used to generate a form. In this form I have added a table in a Vertical panel. Now I want to export this table in excel or CSV. Wondering if someone can help me on this issue.
This is sample code of the entry point class:
public class ItemListEditor implements EntryPoint
{
private final Button addRow = new Button("Add Row");
private final Button save = new Button("Save");
private final Button next = new Button("Next");
private final Button upload = new Button("Upload");
private final Button export = new Button("Export");
private ItemTable table = null;
}
Again, my problem is only to export this table- like when click on export button, system will ask for the location.
I can provide more information if needed.
Please help on this issue
Create a HTTPServlet class, inside the doGet() method of the servlet create a HSSFWorbook using the Apache Poi jar, write your data in the sheet, write the workbook in the response part of servlet.
Map the servlet in your web.xml file and finally, use this servlet url inside your button handler..
EDITED ----->
button.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent arg0) {
exlGenerationServiceAsync.excelReportObjects(new AsyncCallback() {
#Override
public void onFailure(Throwable arg0) {
arg0.printStackTrace();
}
#Override
public void onSuccess(Object arg0) {
Window.open(GWT.getModuleBaseURL() + "url", "", "");
}
});
}
}
Servlet mapping inside the web.xml file----->
<servlet>
<servlet-name>excelFile</servlet-name>
<servlet-class>com.company.server.excelFileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>excelFile</servlet-name>
<url-pattern>/yourUrl</url-pattern>
</servlet-mapping>
Where excelFileServlet is my servlet class.
Inside Servlet class---->
File file = new File("Path Where you want to write your excel file");
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment; filename=" + "Excel_Report_Name.xls");
response.setContentLength((int) file.length());
FileInputStream fileInputStream = new FileInputStream(file);
try{
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
responseOutputStream.close();
}catch(Exception e){
e.printStackTrace();
System.err.println("Inside Try/catch");
If you're looking for some quick and raw exportation, you can give a try to https://code.google.com/p/gwt-table-to-excel/. The project is not very active.
Otherwise, if you want to have more control on the formatting and data you have to send the content of the table to the server side using RPC or other, and then you can use Apache POI to export it as you do usually in Java.
Related
I am trying to load images from server to my JSP
My files are:
image.jsp
<img src='servlet1' height='300px'/>
DisplayImage.java
public class DisplayImage extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
FileInputStream fin = new FileInputStream("path/to/my/img.jpg");
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0;
while((ch=bin.read())!=-1){
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
}
}
Application I'm supposed to build is a Vehicle Directory where I can upload images, and these images are stored in a folder /home/upload/ outside CATALINA
(NB: I didn't use a folder inside project directory coz I am deploying the project via *.war file, which removes every files inside when a new version needs to be deployed.)
I want to display the details and image based on search parameters.
( Edit: I have the file name stored in database when I upload them, so can get the list of image names from DB for a particular vehicle, Since it is stored in folder /home/upload/ , full path will be like /home/upload/fileName.jpg which I need to pass to servlet to load)
Problem I face is that:
image src attribute is specified as servlet1 and the servlet by default serves the image from path defined in DisplayImage.java file
Is there any way that I can pass /another/file/Path.jpg or fileName.jpg to the servlet so that I can display other image files too,
Yeah, In JSP, you can pass your search parameters in request.
Like
<input id="imageSerach" name="imageSerach"/>
<div id="ImageContent"/>
and make ajax call to servlet with imageSearch param.
$.ajax({
url: servleturl,
data: {
imageSerach : $('#imageSerach').val()
},
success: function(responseData){
$('#ImageContent').html('<img src="data:image/png;base64,' + responseData + '" />');
}
});
Servlet :-
public class DisplayImage extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
String fileName = req.getParameter("imageSerach");
response.setContentType("image/jpeg");
ServletOutputStream out;
File f = new File("path/of/file/"+fileName);
if (f.exists())
out = response.getOutputStream();
FileInputStream fin = new FileInputStream("path/of/file/"+fileName);
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0;
while((ch=bin.read())!=-1){
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
else
// no file exit
}
}
I would like to know how to get a file from a Vaadin Upload Component. Here is the example on the Vaadin Website
but it does not include how to save it other than something about OutputStreams.
Help!
To receive a file upload in Vaadin, you must implement Receiver interface, wich provides you with a receiveUpload(filename, mimeType)method, used to receive the info. The simplest code to do this would be (Taken as example from Vaadin 7 docs):
class FileUploader implements Receiver {
private File file;
private String BASE_PATH="C:\\";
public OutputStream receiveUpload(String filename,
String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
try {
// Open the file for writing.
file = new File(BASE_PATH + filename);
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
new Notification("Could not open file<br/>",
e.getMessage(),
Notification.Type.ERROR_MESSAGE)
.show(Page.getCurrent());
return null;
}
return fos; // Return the output stream to write to
}
};
With that, the Uploader will write you a file in C:\. If you wish to something after the upload has completed successfully, or not, you can implement SucceeddedListener or FailedListener. Taking the example above, the result (with a SucceededListener) could be:
class FileUploader implements Receiver {
//receiveUpload implementation
public void uploadSucceeded(SucceededEvent event) {
//Do some cool stuff here with the file
}
}
Current situation: I'm trying to create a JSF app (portlet) which should contains links to excel files (xls, xlt) stored on public network drive G: mapped for all users in our company. The main goal is to unify access to these files and save work to users in search of the reports somewhere on G drive. I hope it's clear..?
I'm using following servlet to open a file. Problem is, that it's not just opened, but downloaded by browser and after that, opened:
#WebServlet(name="fileHandler", urlPatterns={"/fileHandler/*"})
public class FileServlet extends HttpServlet
{
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
private String filePath;
public void init() throws ServletException {
this.filePath = "c:\\Export";
System.out.println("fileServlet initialized: " + this.filePath);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
String requestedFile = request.getPathInfo();
File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));
String contentType = getServletContext().getMimeType(file.getName());
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
close(output);
close(input);
}
}
private static void close(Closeable resource) {
if (resource != null) resource.close();
}
}
How to just start appropriate application (e.g. Excel, Word, etc.) clicking on link (with absolute file path) and open the file in its original location?
UPDATE: I'm trying to use <a> tag:
File // various "/" "\" "\\" combinations
File
But it doesn't work:
type Status report
message /G:/file.xls
description The requested resource is not available.
File URLs are considered as a security risk by most browsers, because they cause files to be opened on a client's machine by a web page, without the end user being aware of it. If you really want to do that, you'll have to configure the browser to allow it.
See the wikipedia article for solutions.
I have a repository storing many images somewhere on the server.
I want to be able to create a dynamic Image object with one of the images stored in my repository.
I am using wicket 1.5.7. I saw this example somewhere
1) Created the FileResource class:
public class FileResource extends WebResource {
private static final long serialVersionUID = 1L;
private File file;
public FileResource(File file) {
this.file = file;
}
#Override
public IResourceStream getResourceStream() {
return new FileResourceStream(file);
}
}
2) In MyPage.java:
File imageFile = new File("local_path_to_image");
Image myImage = new Image("myImage", new FileResource(imageFile));
add(myImage);
3) In MyPage.html:
<i-m-g wicket:id="myImage" />
But this is not working in my case because WebResource is not available in my wicket 1.5.
I have also studied this link in wicket action. But I am a wicket bignner i could not understand much.
I am making a project in which user when click on a product a modal window open with the product name. I also want to include the product image on my modal window inside a panel. Images are stored on my server in a directory.
Any help and advices appreciated! Thanks in advance.
finally i settled on this code. I am passing image file name and creating image.
add(new NonCachingImage("imgPlc", new AbstractReadOnlyModel<DynamicImageResource>(){
#Override public DynamicImageResource getObject() {
DynamicImageResource dir = new DynamicImageResource() {
#Override protected byte[] getImageData(Attributes attributes) {
StringValue name = parameters.get("name");
byte[] imageBytes = null;
if(name.isEmpty() == false)
imageBytes = getImageAsBytes(name.toString());
return imageBytes;
}
};
dir.setFormat("image/png");
return dir;
}
}));
I'm trying to figure out how to upload one file using GWTs FileUpload widget. I'm using GWT and Google AppEngine with Java but I would like to upload file to my own Linux server.
I have the following code already but now I can't figure out how to submit my file to the Google AppServer server and save it to another server:
public class FileUploader{
private ControlPanel cp;
private FormPanel form = new FormPanel();
private FileUpload fu = new FileUpload();
public FileUploader(ControlPanel cp) {
this.cp = cp;
this.cp.setPrimaryArea(getFileUploaderWidget());
}
#SuppressWarnings("deprecation")
public Widget getFileUploaderWidget() {
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
// form.setAction(/* WHAT SHOULD I PUT HERE */);
VerticalPanel holder = new VerticalPanel();
fu.setName("upload");
holder.add(fu);
holder.add(new Button("Submit", new ClickHandler() {
public void onClick(ClickEvent event) {
GWT.log("You selected: " + fu.getFilename(), null);
form.submit();
}
}));
form.addSubmitHandler(new FormPanel.SubmitHandler() {
public void onSubmit(SubmitEvent event) {
if (!"".equalsIgnoreCase(fu.getFilename())) {
GWT.log("UPLOADING FILE????", null);
// NOW WHAT????
}
else{
event.cancel(); // cancel the event
}
}
});
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
public void onSubmitComplete(SubmitCompleteEvent event) {
Window.alert(event.getResults());
}
});
form.add(holder);
return form;
}
}
Now, what do I need to do next? What do i need to put in web.xml and how do I write my servlet so i can store file and return url of that object (if possible)
Here's the code from my app:
1) I created a class to accept http request:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpload extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletFileUpload upload = new ServletFileUpload();
try{
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
// Process the input stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
int maxFileSize = 10*(1024*1024); //10 megs max
if (out.size() > maxFileSize) {
throw new RuntimeException("File is > than " + maxFileSize);
}
}
}
catch(Exception e){
throw new RuntimeException(e);
}
}
}
2) Then in my web.xml I've added these lines:
<servlet>
<servlet-name>fileUploaderServlet</servlet-name>
<servlet-class>com.testapp.server.FileUpload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileUploaderServlet</servlet-name>
<url-pattern>/testapp/fileupload</url-pattern>
</servlet-mapping>
3) And for form.action did this:
form.setAction(GWT.getModuleBaseURL()+"fileupload");
I would suggest using GWTUpload because it's dead simple to use and extend. You can add it to your project in less than 10 minutes and it supports GAE right out of the box (using GWTUpload-GAE). See the examples for some common usage scenarios.
In GWT, you can post the file to the server using http form methods, and you must use the supplied HttpServlet to accept and save the data as binary blogs in the Appengine BigTable.
Then, you need a second HttpServlet to read the file from bigtable, SET THE MIME TYPE IN THE HTTP HEADER {and caching options}, and then stream the file to the user.
Although RPC isn't NECESSARILY needed, you must let the client know what the generated fileId is so they can access it {unless you want to let user's supply the id and force them to worry about name overrides... ...ick}. Either you can use rpc to ask for a list of / single id {like "newest file id by user"}, or you can return that id in the body of the UploadServlet's response... but then you must make sure your post target is an in-page iframe, poll to make sure the iframe has a body between the submit event and the actual server response, and then parse and use that id in gwt to create an img or object tag that uses the file.
The key part is having one servlet for upload, and another to download. Remember, BigTable just stores binary blobs, so you also need your data entity to have a mime/content Type that can be read from the input file {never rely on file extensions!}. Also, there's a 1MB per entity in the BigTable, and a 10MB request limit for free accounts. You may wish to have your data entity contain a list of 1-10 blobs, each of which are a max 1024bytes.
Basically, your best bet is to find a working, free copy, like Google File Service, and extend it to learn how the system works.
If you wish, I will be posting my own open-source version of file handling, once I finish the gwt control widgets and can consider it all stable enough to be useful to anyone. Email x AT aiyx DOT info if you want me to send you a jar of betalicious code.
Here you go with a complete GWT fileupload with Progress bar
Here you can DOWNLOAD the source