Am very very new to Vaadin. Am setting up the project by looking into Github and other docs, where am using Spring-security, Vaadin, Maven.
I created sample vaadin-maven with spring security project. Now am getting login page then after suucessful login, am getting some MainView.java.
Am trying to change the upload .xls file and read that file and do some functionality and then download pop-up.
I have followed http://demo.vaadin.com/sampler/#ui/data-input/other/upload , but errors. unable to reproduce my output.
For now, am able to read the file using path " final String FILE_PATH = "F://input.xls";" But, i need option to upload the file and then use that file for further functionality.
After the functionality completed, i need to download the file.
Please suggest me how can i browse the file and upload and use the uploaded file for ding some read and write operation and then download Vaadin.
Am having sleepless nights for this. Please suggest me how can i come out of this.
Here is my code:
#Component
#Scope("prototype")
#VaadinView(RoleAdminView.NAME)
#Secured("ROLE_ADMIN")
public class RoleAdminView extends Panel implements View
{
public static final String NAME = "role_admin";
#PostConstruct
public void PostConstruct()
{
LoggerFactory.getLogger(this.getClass()).debug("POST");
setSizeFull();
VerticalLayout layout = new VerticalLayout();
layout.setSpacing(true);
layout.setMargin(true);
layout.addComponent(new Button());
layout.addComponent(new Label("ROLE_ADMIN"));
layout.addComponent(new Link("Go back", new ExternalResource("#!" +
MainView.NAME)));
setContent(layout);
}
#Override
public void enter(ViewChangeListener.ViewChangeEvent event)
{
}
}
A big thank you in advance. Hope you guys sort out my issue :)
You can do,
public class RoleAdminView extends Panel implements View{
//add a button view
//
#Override
public void uploadFailed(Upload.FailedEvent event) {
Notification.show(event.getFilename() + "----" + event.getMIMEType());
//here it will show the error if upload failed
}
#Override
public void uploadSucceeded(SucceededEvent event) {
/// do your functionlity
}
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
FileOutputStream fos = null;
// do your functionality to save in any path or server path
return fos; // Return the output stream to write to
}
}
I hope this my help you :)
Related
Currently I'm developing an application with help of Vaadin framework 8.0.
I need to download generated file from server. So I'm using FileDownloader and it's quite simple:
private void createButton() {
Button downloadButton = new Button("download me)
new FileDownloader(getStreamResource().extend(downloadButton))
}
private StreamResource getStreamResource() {
StreamResource streamResource = new StreamResource(new StreamResource.StreamSource() {
#Override
public InputStream getStream() {
return new ByteArrayInputStream(generatedCode.getBytes);
}
}, "Generated.txt");
}
And all is ok when I'm using filename - "Generated.txt". But I need to save this file as a Java class. And when I'm using filename - "Generated.java" I'm just getting an empty file.
What I am doing wrong and how can I fix it? Thanks in advance.
I would like to open file specified by its path in NetBeans editor (IOProvider.getDefault().getIO(...);).
I would like the same functionality as is when some Java/C/C++ or any other programming language prints an Exception. As far as I went for now:
Write the output in console (see the example at the end)
By using OutputListener resolve what should be printed as hypertext
OutputListener.outputLineAction that defines what to do when clicked on hypertext IOColorPrint.print(InputOutput io, CharSequence text, OutputListener listener, boolean important, Color color)
Open the file on the system when clicking on
An example of error message I need to resolve:
The export was successful. The exported file can be found in: C:\Users\MY_USER\Desktop\myFile.xml
The problem that I have is that I have to print all the output in one line and the OutputEvent gives me all the line. Is there any way to get only the Highlited text (The path) ?
This call open new console output tab:
IOProvider.getDefault().getIO(...)
You should take inputStream and use class while(x=is.read()!=n ....
IOProvider.getDefault().getIO(...).getInputStream
Let me know, if this was usefull.
Here the Listener :
public class HyperlinkToFileOutputListener implements OutputListener {
private final File file;
public HyperlinkToFileOutputListener(File file) {
this.file = file;
}
#Override
public void outputLineSelected(OutputEvent oe) {
}
#Override
public void outputLineAction(OutputEvent oe) {
try {
if (file.exists()) {
Desktop.getDesktop().open(file);
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
#Override
public void outputLineCleared(OutputEvent oe) {
}
}
here the call
IOColorPrint.print(io, file.getName(), new HyperlinkToFileOutputListener(file), true, Color.BLUE);
best regards
I am able to upload a picture in my webapp with the struts2 framework, but i am not able to understand the path.
how to get the path of the image as a URL, so that i can use it for further processing in <img src="url"/>.
This is my action class source code and i have mentioned the URL returned in comments, but the URL does not make any sense to me. How can i decrypt it to actual URL ?
public class AddItemAction extends ActionSupport implements
ServletContextAware {
#Override
public void setServletContext(ServletContext arg0) {
// TODO Auto-generated method stub
}
File pic;
String picContentType;
String picFileName;
public File getPic() {
return pic;
}
public void setPic(File pic) {
this.pic = pic;
}
public String getPicContentType() {
return picContentType;
}
void setPicContentType(String picContentType) {
System.out.println("Setting conteent tuype" + picContentType);
this.picContentType = picContentType;
}
public void setPicFileName(String picFileName) {
this.picFileName = picFileName;
}
public String getPicFileName() {
return picFileName;
}
public String execute() {
File file = getPic();
String strFinalFullPathFileName = file.getAbsolutePath() + File.separator + picFileName;
System.out.println(strFinalFullPathFileName);
// This is the path returned
/*
* /Users/..../Catalina/localhost/.../upload_584d2719_13d5fdf593d__8000_00000000.tmp/IMG_20120526_083438.jpg
*
*
*/
return SUCCESS;
}
}
Uploaded artifacts should be stored outside the web app structure.
In addition, by default, the file upload interceptor deletes the temporary files created during the upload process. That should either be turned off, or the file should be copied to a known location so they can be either (a) streamed back via an action, or (b) served directly if you set up your container to serve static assets outside of the normal web structure.
seems like you are uploading your file to a temp folder, what you should do is move this file to a folder inside your web app
you case use request.getServletContext().getRealPath(YOUR_PATH) to get a path where to move the file
YOUR_PATH being something like "/uploadimage/img.png" => uploadimage being a folder directly in you webapp
I am writing a custom event and would like some help please. Most of what I am about to talk about is based on the help provided at Custom event listener on Android app
So here is my issue. I am writing an app that needs to download updated images from the web, store the images on the phone, then later display those images. Basically, I download any needed images during a splash screen. Then when the images are downloaded and stored, the splash screen clears and any necessary (newly downloaded) images are displayed on the screen. Here is the problem: the download process is done via an asynctask so the part where the images are loaded on to the screen can't be done inside the asynctask. It has to be done on the main UI thread. I would like to create an event and a custom event listener for the main thread to listen for that basically tells the main UI thread that it is safe to start loading the downloaded images from memory.
According to the discussion from the link above, I came up with this so far... a download listener interace
public interface DataDownloadListener {
void onDownloadStarted();
void onDownloadFinished();
}
an event class...
public class DataDownloadEvent {
ArrayList<DataDownloadListener> listeners = new ArrayList<DataDownloadListener>();
public void setOnDownload(DataDownloadListener listener){
this.listeners.add(listener);
}
}
My problem is that I don't understand where to put the last two steps in those instructions. I thought I would have to put the listener and event inside the class that actually initiates the downloads. But where? Here is my function that initiates the download and saves it to the device:
public String download(String sourceLocation) {
String filename = "";
String path = "";
try {
File externalStorageDirectory = Environment
.getExternalStorageDirectory();
URL urlTmp = new URL(sourceLocation);
filename = urlTmp.getFile()
.substring(filename.lastIndexOf("/") + 1);
path = externalStorageDirectory + PATH;
// check if the path exists
File f = new File(path);
if (!f.exists()) {
f.mkdirs();
}
filename = path + filename;
f = new File(filename);
//only perform the download if the file doesn't already exist
if (!f.exists()) {
Bitmap bitmap = BitmapFactory.decodeStream(urlTmp.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(
filename);
if (bitmap != null) {
bitmap.compress(getFormat(filename), 50, fileOutputStream);
Log.d(TAG, "Saved image " + filename);
return filename;
}
}
else{
Log.d(TAG, "Image already exists: " + filename + " Not re-downloading file.");
}
} catch (MalformedURLException e) {
//bad url
} catch (IOException e) {
//save error
}
return null;
}
And the last step about registering the listener, where do I put that? The instructions say to put that somewhere during initialization. Does that mean in the onCreate method of my main activity? outside the class in the import section of the main activity? Never done a custom event before, so any help would be appreciated.
According to the discussion from the link above, I came up with this so far... a download listener interace
public interface DataDownloadListener {
void onDownloadStarted();
void onDownloadFinished();
}
an event class...
public class DataDownloadEvent {
ArrayList<DataDownloadListener> listeners = new ArrayList<DataDownloadListener>();
public void setOnDownload(DataDownloadListener listener){
this.listeners.add(listener);
}
}
Ok...
Now in your download procedure, at the start of the download, cycle all the elements on the listeners ArrayList and invoke the onDownloadStarted event to inform all your listeners that the download is just started (in this event i presume you'll need to open the splashscreen).
Always in your download procedure, at the and of the download, cycle all the elements on the listeners ArrayList and invoke the onDownloadFinished event to inform all your listeners that the download is finished (now close the splashscreen).
How to cycle listeners on download completed
foreach(DataDownloadListener downloadListener: listeners){
downloadListener.onDownloadFinished();
}
How to cycle listeners on download started
foreach(DataDownloadListener downloadListener: listeners){
downloadListener.onDownloadStarted();
}
Don't make it static if possible... In the class that you'll use to download your files, simply add what you put in your DataDownloadEvent class (listeners arrayList and facility methods for adding and removing). You have no immediate need to use a class in that way (static members I mean).
Example
public class DownloadFileClassExample{
private ArrayList<DataDownloadListener> listeners = new ArrayList<DataDownloadListener>();
public DownloadFileClassExample(){
}
public void addDownloadListener(DataDownloadListener listener){
listeners.add(listener);
}
public void removeDownloadListener(DataDownloadListener listener){
listeners.remove(listener);
}
//this is your download procedure
public void downloadFile(){...}
}
Then access you class in this way
DownloadFileClassExample example = new DownloadFileClassExample();
example.addDownloadListener(this); // if your class is implementing the **DataDownloadListener**
or use
example.addDownloadListener( new DataDownloadListener{...})
I'm currently working on logging messages from my application in .log files.
This is working fine so far but now I'm trying to output the same message to a textarea.
I have been using the default logger for all this.
This so that I have one class that does all the work of logging to a .log file and writing the same output to a textarea for the admin to see.
This is a Java swing JFrame application containing just a textarea (all I need).
There is a bunch going on in the background and all of that activity has to be logged for review/debugging.
I've been having trouble finding a good example so I was wondering if you guys could help me.
In your case, since you are using JDK default logging, your option is to write your own java.util.Handler and implement the publish method. Somewhat like this:
public class TextAreaHandler extends java.util.logging.Handler {
private JTextArea textArea = new JTextArea(50, 50);
#Override
public void publish(final LogRecord record) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
StringWriter text = new StringWriter();
PrintWriter out = new PrintWriter(text);
out.println(textArea.getText());
out.printf("[%s] [Thread-%d]: %s.%s -> %s", record.getLevel(),
record.getThreadID(), record.getSourceClassName(),
record.getSourceMethodName(), record.getMessage());
textArea.setText(text.toString());
}
});
}
public JTextArea getTextArea() {
return this.textArea;
}
//...
}
Then, you can get the text area from your handler in your Swing application, somewhat like:
for(Handler handler: logger.getHandlers()){
if(handler instanceof TextAreaHandler){
TextAreaHandler textAreaHandler = (TextAreaHandler) handler;
getContentPane().add(textAreaHandler.getTextArea());
}
}
Then, you make sure your logging.properties file contains the configuration of your new handler:
hackers.logging.TestDrive.level=INFO
hackers.logging.TestDrive.handlers=hackers.logging.TextAreaHandler
And, if you are not going to put this configuration in your default logging.properties file (located in your JRE lib folder) then make sure to provide the path to your customized logging.properties file in a property at application startup:
java -Djava.util.logging.config.file=my-customized-logging.properties ...
Just extends from StreamHandler - this is how ConsoleHandler and FileHandler works. And, override the publish function:
public class TextAreaHandler extends StreamHandler {
JTextArea textArea = null;
public void setTextArea(JTextArea textArea) {
this.textArea = textArea;
}
#Override
public void publish(LogRecord record) {
super.publish(record);
flush();
if (textArea != null) {
textArea.appendText(getFormatter().format(record));
}
}
}
Set the output place first before logging message, for example:
public TextAreaHandler textAreaHandler = new TextAreaHandler();
textAreaHandler.setTextArea(<your JTextArea control>);
If it is a monolit application you can write log4j custom appender that will call update of content of textarea and add new lines there.
If there are two independent applications (one that produces logs and one that displays them) you can set up a kind of connection between them (socket/messaging etc) to notify admin application about logged lines and update them.