summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/taskmanager/tasks/DownloadText.java
blob: b62dc122ec1944d95f21020981a74476b77dd11f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package org.openslx.taskmanager.tasks;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

import org.openslx.satserver.util.ProxyHandler;
import org.openslx.satserver.util.Util;
import org.openslx.taskmanager.api.AbstractTask;

import com.google.gson.annotations.Expose;

public class DownloadText extends AbstractTask
{

	@Expose
	private String url = null;

	private Output status = new Output();

	private static final long MAX_SIZE = 1024 * 1024;

	@Override
	protected boolean initTask()
	{
		this.setStatusObject( status );
		if ( this.url == null ) {
			status.error = "No URL given.";
			return false;
		}
		return true;
	}

	@Override
	protected boolean execute()
	{
		URLConnection connection = null;
		BufferedInputStream in = null;
		
		// Before open connection, handle proxy settings.
		ProxyHandler.configProxy();
		try {
			connection = new URL( this.url ).openConnection();
			in = new BufferedInputStream( connection.getInputStream() );
			status.size = connection.getContentLength();
			if ( status.size > MAX_SIZE ) {
				status.error = "Remote file too large: " + status.size + " bytes!";
				return false;
			}
			StringBuilder sb = new StringBuilder( Math.max( 8, status.size ) );

			final byte data[] = new byte[ 9000 ];
			int count;
			while ( ( count = in.read( data, 0, data.length ) ) != -1 ) {
				sb.append( new String( data, 0, count, StandardCharsets.UTF_8 ) );
				status.complete += count;
				if ( status.complete > MAX_SIZE ) {
					status.error = "Remote file too large: > " + status.complete + " bytes!";
					return false;
				}
			}
			status.content = sb.toString();
			return true;
		} catch ( IOException e ) {
			status.error = "Download error: " + e.toString();
			return false;
		} finally {
			Util.multiClose( in );
		}
	}

	/**
	 * Output - contains additional status data of this task
	 */
	@SuppressWarnings( "unused" )
	private static class Output
	{
		protected String error = null;
		protected String content = null;
		protected int size = -1;
		protected int complete = 0;
	}

}