PageRenderTime 22ms CodeModel.GetById 18ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/sitebricks-mail/src/main/java/com/google/sitebricks/mail/imap/OpenFolderExtractor.java

http://github.com/dhanji/sitebricks
Java | 43 lines | 33 code | 6 blank | 4 comment | 9 complexity | 8381d78d0d1619a277134bdb7c5676e7 MD5 | raw file
 1package com.google.sitebricks.mail.imap;
 2
 3import com.google.common.base.Preconditions;
 4
 5import java.util.List;
 6import java.util.regex.Matcher;
 7import java.util.regex.Pattern;
 8
 9/**
10 * @author dhanji@gmail.com (Dhanji R. Prasanna)
11 */
12class OpenFolderExtractor implements Extractor<Folder> {
13  private static final Pattern UIDNEXT_REGEX = Pattern.compile("\\s*. OK \\[UIDNEXT (\\d+)\\]\\s*", Pattern.CASE_INSENSITIVE);
14  private static final String SELECTED = "selected";
15
16  @Override
17  public Folder extract(List<String> messages) {
18    String folderName = null;
19    int count = 0, nextUid = -1;
20    for (String message : messages) {
21      String[] pieces = message.split("[ ]+", 4);
22      if (pieces.length > 1 && "EXISTS".equalsIgnoreCase(pieces[2])) {
23        count = Integer.valueOf(pieces[1]);
24      } else if (message.contains(SELECTED)) {
25        // Extract folder name as given by the server.
26        int left = message.indexOf(pieces[2]) + pieces[2].length();
27        folderName = message.substring(left, message.indexOf(SELECTED)).trim();
28      } else {
29        Matcher matcher = UIDNEXT_REGEX.matcher(message);
30        if (matcher.find()) {
31          String uidNext = matcher.group(1);
32          if (!uidNext.isEmpty())
33            nextUid = Integer.parseInt(uidNext);
34        }
35      }
36    }
37
38    Preconditions.checkState(null != folderName, "Error in IMAP protocol, " +
39        "could not detect folder name");
40
41    return new Folder(folderName, count, nextUid);
42  }
43}