Avevo necessita' di fare un programmino per permettere il download di un file via browser e morire una volta scaricato il file.
Ho fatto una cosa del genere e vorrei da voi commenti e consigli su cosa non va e come eventualmente migliorarlo.
Grazie
public class App {
private static Integer port = 8000;
private static String filename = "";
private static Integer count = 1;
private static Integer counter = 0;
private static String fname = null;
private static File file = null;
public static void main( String[] args ) throws IOException {
parseArgumentLine(args);
Path path = Paths.get(filename);
fname = path.getFileName().toString();
file = new File(filename);
if(!file.exists()) {
System.out.println("The file "+filename+" doesn't exists.");
exit(-1);
}
System.out.println("Now serving on http://localhost:" + port);
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/", new MyHandler());
server.start();
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
while(counter < count) {
Headers headers = t.getResponseHeaders();
headers.add("Content-Type", "application/x-download");
headers.add("Content-disposition", "attachment; filename=" + fname);
t.sendResponseHeaders(200, 0);
OutputStream outputStream = t.getResponseBody();
Files.copy(file.toPath(), outputStream);
outputStream.close();
counter++;
}
exit(0);
}
}
private static void parseArgumentLine(String[] args) {
Options opt = new Options();
opt.addOption("p", "port", true, "HTTP port");
opt.addOption("f", "file", true, "File to serve.");
opt.addOption("c", "count", true, "How many times the file can be downloaded.");
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
try {
CommandLine cmd = parser.parse(opt, args);
if (!cmd.hasOption("f")) {
throw new ParseException("A filename is required.");
}
if (cmd.hasOption("p")) {
try {
port = Integer.parseInt(cmd.getOptionValue("p"));
} catch (Exception e) {
throw new ParseException("Invalid port. This must be a number.");
}
}
if (cmd.hasOption("c")) {
try {
count = Integer.parseInt(cmd.getOptionValue("c"));
} catch (Exception e) {
throw new ParseException("Invalid port. This must be a number.");
}
}
if (cmd.hasOption("f")) {
filename = cmd.getOptionValue("f");
}
} catch (ParseException exp) {
System.out.println("Unexpected exception: " + exp.getMessage());
formatter.printHelp("Woof", opt);
exit(-1);
}
}
}