diff options
Diffstat (limited to 'src/main/java/org/openslx/taskmanager/tasks/DownloadFile.java')
-rw-r--r-- | src/main/java/org/openslx/taskmanager/tasks/DownloadFile.java | 91 |
1 files changed, 91 insertions, 0 deletions
diff --git a/src/main/java/org/openslx/taskmanager/tasks/DownloadFile.java b/src/main/java/org/openslx/taskmanager/tasks/DownloadFile.java new file mode 100644 index 0000000..d901c9f --- /dev/null +++ b/src/main/java/org/openslx/taskmanager/tasks/DownloadFile.java @@ -0,0 +1,91 @@ +package org.openslx.taskmanager.tasks; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.net.URLConnection; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.FilenameUtils; +import org.openslx.satserver.util.Util; +import org.openslx.taskmanager.api.AbstractTask; + +import com.google.gson.annotations.Expose; + +public class DownloadFile extends AbstractTask +{ + + @Expose + private String url = null; + @Expose + private String destination = null; + + private Output status = new Output(); + + private static final String[] ALLOWED_DIRS = + { "/srv/openslx/www/boot/" }; + + @Override + protected boolean initTask() + { + this.setStatusObject( status ); + if ( this.url == null ) { + status.error = "No URL given."; + return false; + } + this.destination = FilenameUtils.normalize( this.destination ); + if ( this.destination == null || !Util.startsWith( this.destination, ALLOWED_DIRS ) || this.destination.endsWith( "/" ) ) { + status.error = "File not in allowed directory"; + return false; + } + return true; + } + + @Override + protected boolean execute() + { + URLConnection connection = null; + BufferedInputStream in = null; + FileOutputStream fout = null; + try { + File dest = new File( this.destination ); + FileUtils.forceMkdir( new File( dest.getParent() ) ); + FileUtils.deleteQuietly( dest ); + connection = new URL( this.url ).openConnection(); + in = new BufferedInputStream( connection.getInputStream() ); + fout = new FileOutputStream( dest ); + status.size = connection.getContentLengthLong(); + + final byte data[] = new byte[ 9000 ]; + int count; + while ( ( count = in.read( data, 0, data.length ) ) != -1 ) { + fout.write( data, 0, count ); + status.complete += count; + if ( status.size > 0 ) + status.progress = (int) ( 100l * status.complete / status.size ); + } + return true; + } catch ( IOException e ) { + status.error = "Download error: " + e.toString(); + FileUtils.deleteQuietly( new File( this.destination ) ); + return false; + } finally { + Util.multiClose( in, fout ); + } + } + + /** + * Output - contains additional status data of this task + */ + @SuppressWarnings( "unused" ) + private static class Output + { + protected String error = null; + protected long size = -1; + protected long complete = 0; + protected int progress = 0; + } + +} |