How to wait for user decision when downloading file - java

I want to continue with this question: How to download whole file from website. I find out that downloading a file is an automatic process and it doesn't wait for user decision cancel/save. So for example user writes url to download file and wait 1 minute. The file automatically starts downloading (I am using firefox) probably to the memory of the browser and when file is download then it continues processing code where I have logger "file successfully download" but there is still pop up window with decision cancel/save. So my question how I can wait for this decision and react on this.

Let's presume that you have an object that performs a download. You can make it implement Runnable and then make it run as a separate thread.
You can have a method called setDestination(String), and a method called cancel().
Cancel would be something like that:
public synchronized void cancel() {
this.cancelled = True;
}
And in the part where you actually perform the download you'd have a
if (this.cancelled) {
//remove downloaded data
return; //Exit from the download function
}
for the setDestination you would need to do something similar, store the download to a tempfile and at the end move it to the file indicated by destination.

Related

How to let run only one instance of application at a time?

I am working on a GUI application that uses JavaFX(not fxml) and exported as a JAR. For slow machine, impatient user click more than once on JAR, and multiple instances of application started.
I'm looking for a solution to let only one instance can be run at a time on a system and if the user clicks again while the application is running nothing happens. I think it's called singleton but don't know how to implement it.
You could try JUnique. It's an open source library doing exactly what you ask for. Import junique-1.0.4.jar to your project as a library. It's just 10kb file.
It's manual neatly describes how to implement it on a project. For a JavaFX application, implementation would look something like this:
Make sure to import these classes to your main
import it.sauronsoftware.junique.AlreadyLockedException;
import it.sauronsoftware.junique.JUnique;
public static void main(String[] args) {
String appId = "myapplicationid";
boolean alreadyRunning;
try {
JUnique.acquireLock(appId);
alreadyRunning = false;
} catch (AlreadyLockedException e) {
alreadyRunning = true;
}
if (!alreadyRunning) {
launch(args); // <-- This the your default JavaFX start sequence
}else{ //This else is optional. Just to free up memory if you're calling the program from a terminal.
System.exit(1);
}
}
One easy solution that I've used is, when you start the application, it creates a file (I named it .lock but you can call it whatever you want), unless the file already exists, in which case the application terminates its execution instead of creating the file.
You will need to bind your application with a resource. It can be a file, port etc.
You can change the code on startup to check if the file is locked. The below code will give you some idea
FileOutputStream foStream = new FileOutputStream("/tmp/testfile.txt");
FileChannel channel = fileOutputStream.getChannel();
FileLock lock = channel.lock();
If you'd properly package your JavaFX code as a real application instead of just throwing it into a jar, you might get that functionality for free and without all these hacks. If I package my JavaFX code on my Mac with the jpackage tool, the result will be a full featured macOS application. That means that when I double-click its icon somewhere several times, only one instance of the application will be started. This is the default behaviour on Macs and properly packaged JavaFX applications just stick to that rule too. I can't say however what the behaviour on Windows or Linux is because I currently don't have such a box running. Maybe someone who knows can add this as a comment.

Allow user to select music files from computer into a processing sketch?

I'm creating a music visualiser. I am stuck on the part which allows the user to upload music tracks from their music library on their computer and have the visualiser respond to the beat of the specific song they have chosen.
I have used the minim library in Processing however I have to load the file name in the coding. I would like a way to have the user click a button which will open the file browser and allow them to select a track and then input that track into the player which will play the track and have the visualiser respond to the beats of the track.
I am not asking for code; rather I am asking on a way to go about this step by step. I am stuck on how to retrieve the files from the computer. I am not very good at coding so I am looking at libraries and tutorials online however; the videos I am finding on this topic only shows how to load text files into a sketch rather than a music file.
Sounds like you're looking for the selectInput() function.
From the reference:
void setup() {
selectInput("Select a file to process:", "fileSelected");
}
void fileSelected(File selection) {
if (selection == null) {
println("Window was closed or the user hit cancel.");
} else {
println("User selected " + selection.getAbsolutePath());
}
}
Opens a platform-specific file chooser dialog to select a file for
input. After the selection is made, the selected File will be passed
to the 'callback' function. If the dialog is closed or canceled, null
will be sent to the function, so that the program is not waiting for
additional input. The callback is necessary because of how threading
works.

What is the correct way to handle the AQuery (android-query) download result?

Sorry if I missed something obvious, I tried really hard but didn't find any clue to answer my question.
So, my task is to download several images using their URLs and store them in some folder. I tried different approaches but for several reasons I decided I should use AQuery for this.
The download is actually done in IntentService which is started from the activity or from AlarmManager. The part where I download images is a for loop for downloading the required amount of images from the generated URLs:
for (int i=0; i < required; i++) {
url = makeURL(i);
aq.download(url, imgDir, new AjaxCallback() {
#Override
public void callback(String url, Object object, AjaxStatus status) {
super.callback(url, object, status);
File file = (File) object;
if (file.length() < 300 * 1024) { //just an example test
file.delete();
}
}
});
AQuery starts a separate thread for each download so the code continues to execute before I can get any result. The problem is that images can be broken or do not fit for other reasons so I do the test after each download in a callback method. If the image does not pass one of the tests I delete the file and need to redownload the image from another URL. But since all downloads are done in an independent threads I can't catch the result of the downloads in the same IntentService where I have all the "spare" URLs.
Since my IntentService is a background thread itself I think I can do all the downloads in that thread, check the file after each download and try another URL if it's bad.
As I understand, I have two options here:
find a way to make aq.download use the same thread
don't use AQuery and take another approach for downloading
I would be very grateful for an advice. My experience is still very limited to make the correct decision. Thanks in advance!

Take action on NetBean's editor's window closing

We are using NetBeans Platform 7.0.1, and have implemented support for a new language using this (now “obsolete”) tutorial.
Since all our contents are stored in a database, and not on files, we open them like this:
FileSystem fs = FileUtil.createMemoryFileSystem();
FileObject fo = fs.getRoot().createData(fileName, fileExtension);
… write contents from database to `fo` ….
DataObject data = MyMultiDataObject.find(fo);
EditorCookie.Observable cookie = data.getCookie(EditorCookie.Observable.class);
cookie.open();
… forces undock of editor window …
And, in our layer.xml, have added a custom button to Save that sends the content back to the database.
However, when the user closes the file (by either closing the tab or the window), we haven’t figured a way of saving it.
Adding a PropertyChangeListener to the Cookie and watching for PROP_DOCUMENT (and newValue() == null) seems to do the trick for when the window is closed. But how does one get the return value from the confirmation window (I’m referring to when the file is closed after changes, the message File xxx.xxx is modified. Save it?)?
Well, it seems we've been approaching the problem in the wrong way.
Since we are opening the file in-memory, it was suggested in the netbeans-dev list that we should listen for changes in the file itself, by using
fo.addFileChangeListener(new CustomFileChangeListener());
public class CustomFileChangeListener implements FileChangeListener {
#Override
public void fileChanged(FileEvent fe) {
... file has been saved in the editor, sync with database ...
}
}
And keep it synchronized that way, taking advantage of the built-in NetBeans Platform "save" functionality.

Why can I only upload one file using Play and uploadify?

I wrote this simple Play-uploadify demo.
I want to an upload button that automatically upload an image each time its pressed.
For some reason, only the first time the button is pressed, I get an upload. After the button has been pressed once, further presses do not cause anything unless I "cancel" the previous uploads.
(I don't understand the meaning of canceling an upload with auto mode. Perhaps the problem is that my downloads never "complete" in some sense?)
Here is my action method:
public static void upload(File file, long userId){
System.out.println("Uploaded file name " + file.getName() +
" by user " + userId);
}
And the call to uploadify:
$(function() {
$("#uploader").uploadify({
uploader : '/public/libraries/uploadify/uploadify.swf',
script : '/Application/upload',
cancelImg : '/public/libraries/uploadify/cancel.png',
folder : '/uploads',
fileExt : '*.jpg;*.gif;*.png',
fileDesc : 'Image Files',
fileDataName: 'file',
scriptData: {userId: 123},
auto: true
});
});
Also, the upload never seems to complete - when I add an onComplete handler, it does't fire.
The problem was that I was not returning a HTTP 200 status code, because I didn't call any render method or return a value at the end of my action method.
Adding renderText("OK"); resolved my problem.
ok(); is a neater way of resolving it.
try to change it to
script : '/application/upload',
(notice the lowercase a in application... play always generates lowercase urls when you use the default route.)
as for only being able to upload one file at a time:
have you tested the upload in dev or production mode?
in dev mode, the amount of threads available for processing is one,
so it will block as soon as you want to upload a second file at the same moment

Categories

Resources