FIX:run() method now works on Sony Camera ADD:CaptureToFile demo application
[capturemjpeg.git] / src / it / lilik / capturemjpeg / CaptureToFile.java
blob29dfe90a97b1745bba4b4dd4ea358b2fbb13333f
1 /**
2 *
3 */
4 package it.lilik.capturemjpeg;
6 import java.io.BufferedOutputStream;
7 import java.io.ByteArrayInputStream;
8 import java.io.File;
9 import java.io.FileNotFoundException;
10 import java.io.FileOutputStream;
11 import java.io.IOException;
12 import java.io.PipedInputStream;
13 import java.io.PipedOutputStream;
15 import org.apache.commons.httpclient.methods.GetMethod;
17 /**
18 * @author Alessio Caiazza
19 * @author Cosimo Cecchi
22 public class CaptureToFile {
24 private String path;
25 private String url;
26 private AsyncProducer client;
28 /**
29 * @param args
31 public static void main(String[] args) {
32 if (args.length < 2 || args.length == 3 || args.length > 4) {
33 System.err.println("Wrong parameters");
34 System.out.println("Usage:");
35 System.exit(-1);
37 String user = null , pass = null;
38 if (args.length == 4) {
39 user = args[2];
40 pass = args[3];
42 CaptureToFile ctf = new CaptureToFile(args[0],
43 args[1], user, pass);
45 ctf.start();
46 //start capturing images from buffer
47 try {
48 ctf.capture(20);
49 } catch (FileNotFoundException e) {
50 e.printStackTrace();
52 try {
53 ctf.stop();
54 } catch (InterruptedException e) {
55 e.printStackTrace();
60 public CaptureToFile(String path, String url,
61 String user, String password) {
62 if (path.lastIndexOf('/') == path.length())
63 this.path = path;
64 else
65 this.path = path + "/";
67 this.url = url;
68 client = new AsyncProducer(new GetMethod(url),
69 user, password);
72 public void capture(int images) throws FileNotFoundException {
73 File fout;
74 FileOutputStream fos;
75 BufferedOutputStream os;
76 ByteArrayInputStream img;
77 byte buff[] = new byte[1024];
78 int readBytes;
79 for( int i = 0; i < images; i++ ) {
80 fout = new File(getPath() + String.valueOf(i) + ".jpg");
81 fos = new FileOutputStream(fout);
82 os = new BufferedOutputStream(fos);
84 //TODO: is this the better way?
85 while( !client.isImageAvailable() ) {
86 Thread.yield();
89 img = client.pop();
90 try {
91 while((readBytes = img.read(buff)) != -1) {
92 os.write(buff, 0, readBytes);
94 os.close();
95 img.close();
96 } catch (IOException e) {
97 e.printStackTrace();
103 * @return the path
105 public synchronized String getPath() {
106 return path;
109 public CaptureToFile(String path, String url) {
110 this(path, url, null, null );
113 public void start() {
114 client.start();
117 public void stop() throws InterruptedException {
118 client.setShouldStop(true);
119 client.join();