01: package dalma.sample.hangman;
02:
03: import dalma.Engine;
04: import dalma.EngineFactory;
05: import dalma.Program;
06: import dalma.Resource;
07: import dalma.EndPoint;
08: import dalma.Description;
09: import dalma.endpoints.email.EmailEndPoint;
10: import dalma.endpoints.email.NewMailHandler;
11: import dalma.helpers.ThreadPoolExecutor;
12:
13: import javax.mail.internet.MimeMessage;
14: import java.io.File;
15:
16: /**
17: * Entry point to the hangman game daemon.
18: *
19: * @author Kohsuke Kawaguchi
20: */
21: @Description("This application runs a hangman game through e-mail")
22: public class Main extends Program {
23:
24: /**
25: * The {@link EndPoint} we use to connect to the e-mail system.
26: */
27: @Resource(description="e-mail configuration where hangman service is exposed")
28: public EmailEndPoint email;
29:
30: /**
31: * CLI entry point.
32: *
33: * This entry points hosts the dalma engine in itself
34: * and keeps running until the process is killed externally.
35: */
36: public static void main(String[] args) throws Exception {
37: new Main().run(args);
38: }
39:
40: private void run(String[] args) throws Exception {
41: if (args.length != 1) {
42: System.err
43: .println("Usage: java -jar hangman.jar <e-mail endpointURL>");
44: System.err.println();
45: System.err
46: .println("See https://dalma.dev.java.net/nonav/maven/dalma-endpoint-email/hangman.html for details");
47: System.exit(-1);
48: }
49:
50: // initialize the directory to which we store data
51: File root = new File("hangman-data");
52: root.mkdirs();
53:
54: // set up an engine.
55: // we'll create one e-mail endpoint from the command-line.
56: final Engine engine = EngineFactory.newEngine(root,
57: new ThreadPoolExecutor(1, true));
58: email = (EmailEndPoint) engine.addEndPoint("email", args[0]);
59: init(engine);
60:
61: // start an engine
62: engine.start();
63: System.out.println("engine started and ready for action");
64:
65: // returning from the main thread means the engine will run forever.
66: // it's somewhat like how Swing works.
67: }
68:
69: /**
70: * Performs initialization.
71: *
72: * <p>
73: * When hosted inside a container, this method is invoked by the container.
74: * See {@link Program} for more about how the container invokes this class.
75: */
76: @Override
77: public void init(final Engine engine) {
78: email.setNewMailHandler(new NewMailHandler() {
79: /**
80: * This method is invoked every time this endpoint receives a new e-mail.
81: * Start a new game.
82: */
83: public void onNewMail(MimeMessage mail) throws Exception {
84: System.out.println("Starting a new game for "
85: + mail.getFrom()[0]);
86: engine.createConversation(new HangmanWorkflow(email,
87: mail));
88: }
89: });
90: }
91: }
|