How to show a progress bar while downloading in javafx - java

I am building a desktop app using javafx, I am downloading a file around 500 MB using ftp.
I need to show the progress bar with % while downloading is in progress.
I also need to give a option to cancel a ongoing downloading process.
This is my code to download file.
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
success = ftpClient.changeWorkingDirectory(PATH + preset + "/" + file_to_download + offset);
System.out.println("Download Path:-" + PATH + preset + "/" + file_to_download + offset);
if (!success) {
System.out.println("Could not changed the directory to RIBS");
return;
} else {
System.out.println("Directory changed to RIBS");
}
FTPFile[] files = ftpClient.listFiles();
for (FTPFile file : files) {
if (file.getName().contains(".zip")) {
dfile = file.getName();
}
}
DirectoryChooser dirChooser = new DirectoryChooser();
File chosenDir = dirChooser.showDialog(tableView.getScene().getWindow());
System.out.println(chosenDir.getAbsolutePath());
OutputStream output;
output = new FileOutputStream(chosenDir.getAbsolutePath() + "/" + dfile);
int timeOut = 500;
ftpClient.setConnectTimeout(timeOut);
if (ftpClient.retrieveFile(dfile, output) == true) {
downloadButton.setDisable(true);
}
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

You should make yourself familiar with Concurrency in JavaFX.
And you can find several examples about what you need on the web, e. g. ProgressBar and Background Processes.

Related

Foreground usage for an Android app

I have an Android app that tracks last time an app used in the foreground. How can I count each time the app is active for an interval of time?
public static void printUsageStats(List<UsageStats> usageStatsList){
for (UsageStats u : usageStatsList){
Log.d(TAG, "Pkg: " + u.getPackageName() + "\t" + "ForegroundTime: "
+ u.getTotalTimeInForeground()) ;
}
}
log to a file!
getTotalTimeInForeground()
this method returns times and not how MANY
so create file onCreate() of main activity
and check if file exists and set new value
File f = getApplicationContext().getFileStreamPath("count");
if(!f.exists){
try {
String fileName = ".countFile";
FileOutputStream fOut = context.openFileOutput(fileName, MODE_PRIVATE);//don't use append
fOut.write((/*Count Integer*/).getBytes());
fOut.flush();
fOut.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
else{
//read file and add +1 to existing file
}

How to upload file using java ?

Hello i m trying to upload file using java file.. but i don't get it.. i get file size=0 i'm providing here my java code. tell me why i cant upload on particular folder. i want to store my file in particular folder. i am trying to get file size, file name but i got the null value where am i wrong please tell me.
public void updateTesti(ActionRequest actionRequest,ActionResponse actionResponse) throws IOException, PortletException
{
//image upload logic
String folder_for_upload =(getPortletContext().getRealPath("/"));
//String folder=actionRequest.getParameter("uploadfolder");
realPath=getPortletContext().getRealPath("/");
logger.info("RealPath is" + realPath);
logger.info("Folder is :" + folder_for_upload);
try
{
logger.info("Admin is try to upload");
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
if (uploadRequest.getSize("fileName") == 0) {
SessionErrors.add(actionRequest, "error");
}
String sourceFileName = uploadRequest.getFileName("fileName");
File uploadedFile = uploadRequest.getFile("fileName");
System.out.println("Size of uploaded file: " + uploadRequest.getSize("fileName"));
logger.info("Uploded file name is: " + uploadRequest.getFileName("fileName"));
String destiFolder=("/home/ubuntu/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/webapps/imageUpload-portlet/image");
String newsourcefilename = (uploadRequest.getFileName("fileName"));
File newFile = new File(destiFolder +"/"+ newsourcefilename);
logger.info("New file name: " + newFile.getName());
logger.info("New file path: " + newFile.getPath());
InputStream in = new BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(uploadedFile);
FileOutputStream fos = new FileOutputStream(newFile);
byte[] bytes_ = FileUtil.getBytes(in);
int i = fis.read(bytes_);
while (i != -1) {
fos.write(bytes_, 0, i);
i = fis.read(bytes_);
}
fis.close();
fos.close();
Float size = (float) newFile.length();
System.out.println("file size bytes:" + size);
System.out.println("file size Mb:" + size / 1048576);
logger.info("File created: " + newFile.getName());
SessionMessages.add(actionRequest, "success");
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (NullPointerException e)
{
System.out.println("File Not Found");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (IOException e1)
{
System.out.println("Error Reading The File.");
SessionMessages.add(actionRequest, "error");
e1.printStackTrace();
}
}
You need to do this to upload small files < 1kb
File f2 = uploadRequest.getFile("fileupload", true);
They are stored in memory only. I have it in my catch statement incase I get a null pointer - or incase my original file (f1.length) == 0
I have executed your code.It is working as per expectation.There might be something wrong in your jsp page.I am not sure but might be your name attribute is not same as the one which you are using in processAction(assuming that you are using portlet).Parameter is case sensitive,so check it again.
You will find more on below link.It has good explanation in file upload.
http://www.codeyouneed.com/liferay-portlet-file-upload-tutorial/
I went through a file upload code, and when i implement that in my local system what i got is, portlet is saving the file i upload in tomcat/webbapp/abc_portlet_project location, what i dont understand is from where portlet found
String folder = getInitParameter("uploadFolder");
String realPath = getPortletContext().getRealPath("/");
System.out.println("RealPath" + realPath +"\\" + folder); try {
UploadPortletRequest uploadRequest =
PortalUtil.getUploadPortletRequest(actionRequest);
System.out.println("Size: "+uploadRequest.getSize("fileName"));
if (uploadRequest.getSize("fileName")==0)
{SessionErrors.add(actionRequest, "error");}
String sourceFileName = uploadRequest.getFileName("fileName"); File
file = uploadRequest.getFile("fileName");
System.out.println("Nome file:" +
uploadRequest.getFileName("fileName")); File newFolder = null;
newFolder = new File(realPath +"\" + folder);
if(!newFolder.exists()){ newFolder.mkdir(); }
File newfile = null;
newfile = new File(newFolder.getAbsoluteFile()+"\"+sourceFileName);
System.out.println("New file name: " + newfile.getName());
System.out.println("New file path: " + newfile.getPath());
InputStream in = new
BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(file); FileOutputStream fos
= new FileOutputStream(newfile);

Need Realtime updating in JTextArea

I am trying to get this JTextArea, called textArea, to update while it is copying these photos but I can't quite seem to get it to work. I was using this code:
String name = "";
int numberOfPicturesCopied = 0;
while (pictures.isEmpty() == f) {
try {
File tmp = pictures.firstElement();
name = tmp.getName();
String filename = destination + Meta.date(tmp) + tmp.getName();
Path source = tmp.toPath();
File destFile = new File(filename);
Path destination = destFile.toPath();
Files.copy(source, destination,
StandardCopyOption.COPY_ATTRIBUTES);
textArea.append("Copied " + name + "\n");
pictures.removeElementAt(0);
numberOfPicturesCopied++;
} catch (FileAlreadyExistsException faee) {
textArea.append("Skipped " + name
+ ": Picture Already In Computer\n");
} catch (NoSuchFileException ncfe) {
File tmp = pictures.firstElement();
String filename = destination + Meta.date(tmp);
File newDir = new File(filename);
newDir.mkdir();
} catch (IOException ee) {
// TODO Auto-generated catch block
ee.printStackTrace();
}
}
and then I changed it to this:
public void copyPictures(){
SwingUtilities.invokeLater(new Thread(){
public void run(){
String name = "";
while(pictures.isEmpty() == f){
try {
File tmp = pictures.firstElement();
name = tmp.getName();
String filename = destination + Meta.date(tmp) + tmp.getName();
Path source = tmp.toPath();
File destFile = new File(filename);
Path destination = destFile.toPath();
Files.copy(source, destination, StandardCopyOption.COPY_ATTRIBUTES);
textArea.append("Copied " + name + "\n");
pictures.removeElementAt(0);
numberOfPicturesCopied++;
} catch(FileAlreadyExistsException faee){
textArea.append("Skipped " + name +": Picture Already In Computer\n");
} catch (NoSuchFileException ncfe){
File tmp = pictures.firstElement();
String filename = destination + Meta.date(tmp);
File newDir = new File(filename);
newDir.mkdir();
} catch (IOException ee) {
// TODO Auto-generated catch block
ee.printStackTrace();
}
}
}
});
}
with the same outcome. Any suggestions?
Also, is there any way to get the text to come in at the top of text area?
How to insert your text at the start is already answered. The other part of your question is the same as always ... you are performing heavy work on the Event Dispatch Thread, which is no longer able to perform repaints.
What you should do is perform the heavy work on a worker thread, and only update the UI on the EDT. You can for example use a SwingWorker, which is designed for this. Or even simpler, take your current code and with a few simple modifications
public void copyPictures(){
new Thread(){
public void run(){
while(pictures.isEmpty() == f){
try {
File tmp = pictures.firstElement();
final String name = tmp.getName();
String filename = destination + Meta.date(tmp) + tmp.getName();
Path source = tmp.toPath();
File destFile = new File(filename);
Path destination = destFile.toPath();
Files.copy(source, destination, StandardCopyOption.COPY_ATTRIBUTES);
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
textArea.append("Copied " + name + "\n");
}
}
);
pictures.removeElementAt(0);
numberOfPicturesCopied++;
} catch(FileAlreadyExistsException faee){
textArea.append("Skipped " + name +": Picture Already In Computer\n");
} catch (NoSuchFileException ncfe){
File tmp = pictures.firstElement();
String filename = destination + Meta.date(tmp);
File newDir = new File(filename);
newDir.mkdir();
} catch (IOException ee) {
// TODO Auto-generated catch block
ee.printStackTrace();
}
}
}
}.run();
}
See how the work is done on a separate Thread yet the UI is updated on the EDT. More information can be found in the Swing Concurrency tutorial or on SO (keyword for your search is SwingWorker, which will results in a heap of examples as this is a daily question)
Not sure what you are asking, the title seems to be saying that the text isnt updating, but your question seems to indicate that is isnt being inserted where you want it to be...
If its the latter, use the insert method instead
textArea.insert("Copied " + name + "\n",0);
to put it at the top of the text area.

Is it possible to copy database file to SD card?

I have a database on my Android phone, and I need to get the information onto an SD card.
Is it possible to save the database file onto the SD card in a readable state? I haven't been able to find any information on how to do this.
Some source code that copies the database file to an SD card would be ideal.
The database file is just like any other file, if you make a binary file copy it will work.
Java has no built in file copy method, so you can use this:
Standard concise way to copy a file in Java?
Just don't forget to add your manifest permission to write to the SD card:
Permission to write to the SD card
Here's a script I've bastardized from several other users on SO. It looks like you can tell android where to store the file, but when you go into the phone with adb shell you might have a hard time finding it!
This code (which I mapped to a temporary button in my action bar for debugging) would print something like: "database saved to: /storage/emulated/0/DB-DEBUG/todotable.db", but going into the shell on my phone I actually found my database at: "/storage/emulated/legacy/DB-DEBUG/"... not sure what's up with that, but now I can check out my database with an sqlite browser!
//db will reside in: /storage/emulated/legacy/DB_DEBUG
private void copyDatabase(Context c, String DATABASE_NAME) {
String databasePath = c.getDatabasePath(DATABASE_NAME).getPath();
File f = new File(databasePath);
OutputStream myOutput = null;
InputStream myInput = null;
Log.d("testing", " testing db path " + databasePath);
Log.d("testing", " testing db exist " + f.exists());
if (f.exists()) {
try {
File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DB-DEBUG");
if (!directory.exists()){
directory.mkdir();
}
String copyPath = directory.getAbsolutePath() + "/" + DATABASE_NAME;
myOutput = new FileOutputStream(copyPath);
myInput = new FileInputStream(databasePath);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
Toast.makeText(getBaseContext(), "Your database copied to: " + copyPath, Toast.LENGTH_LONG).show();
Log.d("testing", " database saved to: " + copyPath);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
} finally {
try {
if (myOutput != null) {
myOutput.close();
myOutput = null;
}
if (myInput != null) {
myInput.close();
myInput = null;
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}

How to deal with corrupted files that were created but IOException occured?

Could you please suggest how to deal with these situations ? I understand that in the second example, it is very rare that it would happen on unix, is it ? If access rights are alright. Also the file wouldn't be even created. I don't understand why the IOException is there, either it is created or not, why do we have to bother with IOException ?
But in the first example, there will be a corrupted zombie file. Now if you tell the user to upload it again, the same thing may happen. If you can't do that, and the inputstream has no marker. You loose your data ? I really don't like how this is done in Java, I hope the new IO in Java 7 is better
Is it usual to delete it
public void inputStreamToFile(InputStream in, File file) throws SystemException {
OutputStream out;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
throw new SystemException("Temporary file created : " + file.getAbsolutePath() + " but not found to be populated", e);
}
boolean fileCorrupted = false;
int read = 0;
byte[] bytes = new byte[1024];
try {
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
} catch (IOException e) {
fileCorrupted = true;
logger.fatal("IO went wrong for file : " + file.getAbsolutePath(), e);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
if(fileCorrupted) {
???
}
}
}
public File createTempFile(String fileId, String ext, String root) throws SystemException {
String fileName = fileId + "." + ext;
File dir = new File(root);
if (!dir.exists()) {
if (!dir.mkdirs())
throw new SystemException("Directory " + dir.getAbsolutePath() + " already exists most probably");
}
File file = new File(dir, fileName);
boolean fileCreated = false;
boolean fileCorrupted = false;
try {
fileCreated = file.createNewFile();
} catch (IOException e) {
fileCorrupted = true;
logger.error("Temp file " + file.getAbsolutePath() + " creation fail", e);
} finally {
if (fileCreated)
return file;
else if (!fileCreated && !fileCorrupted)
throw new SystemException("File " + file.getAbsolutePath() + " already exists most probably");
else if (!fileCreated && fileCorrupted) {
}
}
}
I really don't like how this is done in Java, I hope the new IO in Java 7 is better
I'm not sure how Java is different than any other programming language/environment in the way you are using it:
a client sends some data to your over the wire
as you read it, you write it to a local file
Regardless of the language/tools/environment, it's possible for the connection to be interrupted or lost, for the client to go away, for the disk to die, or for any other error to occur. I/O errors can occur in any and all environments.
What you can do in this situation is highly dependent on the situation and the error that occured. For example, is the data structured in some way where you could ask the user to resume uploading from record 1000, for example? However, there is no single solution that fits all here.

Categories

Resources