PageRenderTime 17ms CodeModel.GetById 12ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/sitebricks-mail/src/main/java/com/google/sitebricks/mail/CommandCompletion.java

http://github.com/dhanji/sitebricks
Java | 75 lines | 56 code | 10 blank | 9 comment | 3 complexity | 2e9fe164ffd5a71ab27e531ae414871d MD5 | raw file
 1package com.google.sitebricks.mail;
 2
 3import com.google.common.collect.Lists;
 4import com.google.common.util.concurrent.SettableFuture;
 5import com.google.sitebricks.mail.imap.Command;
 6import com.google.sitebricks.mail.imap.ExtractionException;
 7import org.slf4j.Logger;
 8import org.slf4j.LoggerFactory;
 9
10import java.util.List;
11
12/**
13 * A generic command completion listener that aggregates incoming messages
14 * until it forms a complete response to an issued command.
15 *
16 * @author dhanji@gmail.com (Dhanji R. Prasanna)
17 */
18class CommandCompletion {
19  private static final Logger log = LoggerFactory.getLogger(CommandCompletion.class);
20  private final SettableFuture<Object> valueFuture;
21  private final List<String> value = Lists.newArrayList();
22  private final Long sequence;
23  private final Command command;
24  private final String commandString;
25
26  @SuppressWarnings("unchecked") // Ugly gunk needed to prevent generics from spewing everywhere
27  public CommandCompletion(Command command,
28                           Long sequence,
29                           SettableFuture<?> valueFuture,
30                           String commandString) {
31    this.commandString = commandString;
32    this.valueFuture = (SettableFuture<Object>) valueFuture;
33    this.sequence = sequence;
34    this.command = command;
35  }
36
37  public void error(String message, Exception e) {
38    StringBuilder builder = new StringBuilder();
39    for (String piece : value) {
40      builder.append(piece).append('\n');
41    }
42    log.error("Exception while processing response:\n Command: {} (seq: {})\n\n--message follows--" +
43        "\n{}\n--message end--\n--context follows--\n{}\n--context end--\n\n",
44        new Object[] { commandString, sequence, message, builder.toString(), e });
45
46    // TODO Send this back to the client as an exception so it can be handled correctly.
47    valueFuture.setException(new MailHandlingException(value, message, e));
48  }
49
50  public boolean complete(String message) {
51    value.add(message);
52    // Base case (empty/newline message).
53    if (message.isEmpty()) {
54      return false;
55    }
56
57    try {
58     if (Command.isEndOfSequence(sequence, message.toLowerCase())) {
59       // Once we see the OK message, we should process the data and return.
60       valueFuture.set(command.extract(value));
61       return true;
62      }
63    }
64    catch(ExtractionException ee) {
65      valueFuture.setException(ee);
66      return true;
67    }
68
69    return false;
70  }
71
72  @Override public String toString() {
73    return commandString;
74  }
75}