1   package com.frevvo.forms.cli.shell;
2   
3   import java.io.File;
4   import java.io.FileOutputStream;
5   import java.io.IOException;
6   
7   import asg.cliche.Command;
8   
9   import com.frevvo.forms.cli.ApiHelper;
10  import com.frevvo.forms.cli.core.EntryShell;
11  import com.frevvo.forms.client.ApplicationEntry;
12  import com.frevvo.forms.client.FormTypeFeed;
13  import com.frevvo.forms.client.Helper;
14  import com.frevvo.forms.client.SchemaFeed;
15  import com.google.gdata.data.MediaContent;
16  import com.google.gdata.data.media.MediaSource;
17  import com.google.gdata.util.ServiceException;
18  
19  /**
20   * Shell context for all commands related to application entries
21   */
22  public class ApplicationEntryShell extends EntryShell<ApplicationEntry> {
23  	public ApplicationEntryShell(ApplicationEntry entry) {
24  		super(entry.getTitle().getPlainText(), entry);
25  	}
26  
27  	@Command(name = "forms", description = "LIST all forms (e.g. 'forms')")
28  	public String forms() throws IOException, ServiceException {
29  
30  		ApplicationEntry app = getEntry();
31  		FormTypeFeed forms = app.getFormTypeFeed();
32  
33  		return go(new FormTypeFeedShell(forms));
34  	}
35  
36  	@Command(name = "flows", description = "LIST all flows (e.g. 'flows')")
37  	public String flows() throws IOException, ServiceException {
38  
39  		ApplicationEntry app = getEntry();
40  		FormTypeFeed flows = app.getFlowTypeFeed();
41  
42  		return go(new FormTypeFeedShell(flows));
43  	}
44  
45  	@Command(name = "schemas", description = "LIST all schemas (e.g. 'schemas')")
46  	public String schemas() throws IOException, ServiceException {
47  
48  		ApplicationEntry app = getEntry();
49  		SchemaFeed schemas = app.getSchemaFeed();
50  
51  		return go(new SchemaFeedShell(schemas));
52  	}
53  
54  	@Command(name = "down", description = "DOWNLOAD this application (e.g. 'down')")
55  	public String download() throws IOException, ServiceException {
56  		ApplicationEntry app = getEntry();
57  
58  		String fileName = ApiHelper.getName(app);
59  		fileName = ApiHelper.nameToFileName(fileName);
60  		try {
61  			File file = File.createTempFile(fileName + "_", "_app.zip");
62  			FileOutputStream fos = new FileOutputStream(file);
63  			try {
64  				MediaContent mc = (MediaContent) app.getContent();
65  				MediaSource ms = getService().getMedia(mc);
66  
67  				Helper.readStream(ms.getInputStream(), fos);
68  
69  				return "Application downloaded to: " + file;
70  			} catch (Exception e) {
71  				return "Could not download application: " + e.getMessage();
72  			} finally {
73  				fos.close();
74  			}
75  		} catch (Exception e) {
76  			return "Could not download application: " + e.getMessage();
77  		}
78  	}
79  
80  	@Override
81  	protected String print(ApplicationEntry entry) {
82  		return ApiHelper.print(getEntry());
83  	}
84  }