View Javadoc
1   /*
2    * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway
3    * Copyright (C) 2010  Mickael Guessant
4    *
5    * This program is free software; you can redistribute it and/or
6    * modify it under the terms of the GNU General Public License
7    * as published by the Free Software Foundation; either version 2
8    * of the License, or (at your option) any later version.
9    *
10   * This program is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with this program; if not, write to the Free Software
17   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18   */
19  package davmail.exchange.ews;
20  
21  import davmail.BundleMessage;
22  import davmail.Settings;
23  import davmail.exception.DavMailAuthenticationException;
24  import davmail.exception.DavMailException;
25  import davmail.exception.HttpNotFoundException;
26  import davmail.exchange.ExchangeSession;
27  import davmail.exchange.VCalendar;
28  import davmail.exchange.VObject;
29  import davmail.exchange.VProperty;
30  import davmail.exchange.auth.O365Token;
31  import davmail.http.HttpClientAdapter;
32  import davmail.http.request.GetRequest;
33  import davmail.ui.NotificationDialog;
34  import davmail.util.DateUtil;
35  import davmail.util.IOUtil;
36  import davmail.util.StringUtil;
37  import org.apache.http.HttpStatus;
38  import org.apache.http.client.methods.CloseableHttpResponse;
39  
40  import javax.mail.MessagingException;
41  import javax.mail.Session;
42  import javax.mail.internet.InternetAddress;
43  import javax.mail.internet.MimeMessage;
44  import javax.mail.internet.MimeUtility;
45  import javax.mail.util.SharedByteArrayInputStream;
46  import java.io.BufferedReader;
47  import java.io.ByteArrayInputStream;
48  import java.io.ByteArrayOutputStream;
49  import java.io.IOException;
50  import java.io.InputStream;
51  import java.io.InputStreamReader;
52  import java.net.HttpURLConnection;
53  import java.net.URI;
54  import java.nio.charset.StandardCharsets;
55  import java.text.ParseException;
56  import java.text.SimpleDateFormat;
57  import java.util.*;
58  import java.util.regex.Pattern;
59  
60  /**
61   * EWS Exchange adapter.
62   * Compatible with Exchange 2007, 2010 and 2013.
63   */
64  public class EwsExchangeSession extends ExchangeSession {
65  
66      protected static final int PAGE_SIZE = 500;
67  
68      protected static final String ARCHIVE_ROOT = "/archive/";
69  
70      public static final Map<String, String> vTodoToTaskStatusMap = new HashMap<>();
71      public static final Map<String, String> taskTovTodoStatusMap = new HashMap<>();
72      static {
73          //taskTovTodoStatusMap.put("NotStarted", null);
74          taskTovTodoStatusMap.put("InProgress", "IN-PROCESS");
75          taskTovTodoStatusMap.put("Completed", "COMPLETED");
76          taskTovTodoStatusMap.put("WaitingOnOthers", "NEEDS-ACTION");
77          taskTovTodoStatusMap.put("Deferred", "CANCELLED");
78  
79          //vTodoToTaskStatusMap.put(null, "NotStarted");
80          vTodoToTaskStatusMap.put("IN-PROCESS", "InProgress");
81          vTodoToTaskStatusMap.put("COMPLETED", "Completed");
82          vTodoToTaskStatusMap.put("NEEDS-ACTION", "WaitingOnOthers");
83          vTodoToTaskStatusMap.put("CANCELLED", "Deferred");
84  
85      }
86  
87      /**
88       * Message types.
89       *
90       * @see <a href="http://msdn.microsoft.com/en-us/library/aa565652%28v=EXCHG.140%29.aspx">
91       * http://msdn.microsoft.com/en-us/library/aa565652%28v=EXCHG.140%29.aspx</a>;
92       */
93      protected static final Set<String> MESSAGE_TYPES = new HashSet<>();
94  
95      static {
96          MESSAGE_TYPES.add("Message");
97          MESSAGE_TYPES.add("CalendarItem");
98  
99          MESSAGE_TYPES.add("MeetingMessage");
100         MESSAGE_TYPES.add("MeetingRequest");
101         MESSAGE_TYPES.add("MeetingResponse");
102         MESSAGE_TYPES.add("MeetingCancellation");
103 
104         MESSAGE_TYPES.add("Item");
105         MESSAGE_TYPES.add("PostItem");
106 
107         // exclude types from IMAP
108         //MESSAGE_TYPES.add("Contact");
109         //MESSAGE_TYPES.add("DistributionList");
110         //MESSAGE_TYPES.add("Task");
111 
112         //ReplyToItem
113         //ForwardItem
114         //ReplyAllToItem
115         //AcceptItem
116         //TentativelyAcceptItem
117         //DeclineItem
118         //CancelCalendarItem
119         //RemoveItem
120         //PostReplyItem
121         //SuppressReadReceipt
122         //AcceptSharingInvitation
123     }
124 
125     static final Map<String, String> partstatToResponseMap = new HashMap<>();
126     static final Map<String, String> responseTypeToPartstatMap = new HashMap<>();
127     static final Map<String, String> statusToBusyStatusMap = new HashMap<>();
128 
129     static {
130         partstatToResponseMap.put("ACCEPTED", "AcceptItem");
131         partstatToResponseMap.put("TENTATIVE", "TentativelyAcceptItem");
132         partstatToResponseMap.put("DECLINED", "DeclineItem");
133         partstatToResponseMap.put("NEEDS-ACTION", "ReplyToItem");
134 
135         responseTypeToPartstatMap.put("Accept", "ACCEPTED");
136         responseTypeToPartstatMap.put("Tentative", "TENTATIVE");
137         responseTypeToPartstatMap.put("Decline", "DECLINED");
138         responseTypeToPartstatMap.put("NoResponseReceived", "NEEDS-ACTION");
139         responseTypeToPartstatMap.put("Unknown", "NEEDS-ACTION");
140 
141         statusToBusyStatusMap.put("TENTATIVE", "Tentative");
142         statusToBusyStatusMap.put("CONFIRMED", "Busy");
143         // Unable to map CANCELLED: cancelled events are directly deleted on Exchange
144     }
145 
146     static final String UTC_TIMEZONE = "UTC";
147 
148     static String resolveCalendarTimezone(VObject vEvent, String propertyName) {
149         VProperty property = vEvent.getProperty(propertyName);
150         String timezone = null;
151         if (property != null) {
152             String value = property.getValue();
153             if (value != null && value.endsWith("Z")) {
154                 return UTC_TIMEZONE;
155             }
156             timezone = property.getParamValue("TZID");
157         }
158         if (timezone != null && timezone.isEmpty()) {
159             timezone = null;
160         }
161         return timezone;
162     }
163 
164     protected HttpClientAdapter httpClient;
165 
166     protected Map<String, String> folderIdMap;
167     protected boolean directEws;
168 
169     /**
170      * Oauth2 token
171      */
172     private O365Token token;
173 
174     protected class Folder extends ExchangeSession.Folder {
175         public FolderId folderId;
176     }
177 
178     protected static class FolderPath {
179         protected final String parentPath;
180         protected final String folderName;
181 
182         protected FolderPath(String folderPath) {
183             int slashIndex = folderPath.lastIndexOf('/');
184             if (slashIndex < 0) {
185                 parentPath = "";
186                 folderName = folderPath;
187             } else {
188                 parentPath = folderPath.substring(0, slashIndex);
189                 folderName = folderPath.substring(slashIndex + 1);
190             }
191         }
192     }
193 
194     public EwsExchangeSession(HttpClientAdapter httpClient, String userName) throws IOException {
195         this.httpClient = httpClient;
196         this.userName = userName;
197         if (userName.contains("@")) {
198             this.email = userName;
199         }
200         buildSessionInfo(null);
201     }
202 
203     public EwsExchangeSession(HttpClientAdapter httpClient, URI uri, String userName) throws IOException {
204         this.httpClient = httpClient;
205         this.userName = userName;
206         if (userName.contains("@")) {
207             this.email = userName;
208             this.alias = userName.substring(0, userName.indexOf('@'));
209         }
210         buildSessionInfo(uri);
211     }
212 
213     public EwsExchangeSession(HttpClientAdapter httpClient, O365Token token, String userName) throws IOException {
214         this.httpClient = httpClient;
215         this.userName = userName;
216         if (userName.contains("@")) {
217             this.email = userName;
218             this.alias = userName.substring(0, userName.indexOf('@'));
219         }
220         this.token = token;
221         buildSessionInfo(null);
222     }
223 
224     public EwsExchangeSession(URI uri, O365Token token, String userName) throws IOException {
225         this(new HttpClientAdapter(uri, true), token, userName);
226     }
227 
228     public EwsExchangeSession(String url, String userName, String password) throws IOException {
229         this(new HttpClientAdapter(url, userName, password, true), userName);
230     }
231 
232     /**
233      * EWS fetch page size.
234      *
235      * @return page size
236      */
237     private static int getPageSize() {
238         return Settings.getIntProperty("davmail.folderFetchPageSize", PAGE_SIZE);
239     }
240 
241     /**
242      * Check endpoint url.
243      *
244      * @throws IOException on error
245      */
246     protected void checkEndPointUrl() throws IOException {
247         GetFolderMethod checkMethod = new GetFolderMethod(BaseShape.ID_ONLY,
248                 DistinguishedFolderId.getInstance(null, DistinguishedFolderId.Name.root), null);
249         int status = executeMethod(checkMethod);
250 
251         if (status == HttpStatus.SC_UNAUTHORIZED) {
252             throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
253         } else if (status != HttpStatus.SC_OK) {
254             throw new IOException("Ews endpoint not available at " + checkMethod.getURI().toString() + " status " + status);
255         }
256     }
257 
258     @Override
259     public void buildSessionInfo(java.net.URI uri) throws IOException {
260         // send a first request to get server version
261         checkEndPointUrl();
262 
263         // new approach based on ConvertId to find primary email address
264         if (email == null || alias == null) {
265             try {
266                 GetFolderMethod getFolderMethod = new GetFolderMethod(BaseShape.ID_ONLY,
267                         DistinguishedFolderId.getInstance(null, DistinguishedFolderId.Name.root),
268                         null);
269                 executeMethod(getFolderMethod);
270                 EWSMethod.Item item = getFolderMethod.getResponseItem();
271                 String folderId = item.get("FolderId");
272 
273                 ConvertIdMethod convertIdMethod = new ConvertIdMethod(folderId);
274                 executeMethod(convertIdMethod);
275                 EWSMethod.Item convertIdItem = convertIdMethod.getResponseItem();
276                 if (convertIdItem != null && !convertIdItem.isEmpty()) {
277                     email = convertIdItem.get("Mailbox");
278                     alias = email.substring(0, email.indexOf('@'));
279                 } else {
280                     LOGGER.error("Unable to resolve email from root folder");
281                     throw new IOException();
282                 }
283 
284             } catch (IOException e) {
285                 throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
286             }
287         }
288 
289         directEws = uri == null
290                 || "/ews/services.wsdl".equalsIgnoreCase(uri.getPath())
291                 || "/ews/exchange.asmx".equalsIgnoreCase(uri.getPath());
292 
293         currentMailboxPath = "/users/" + email.toLowerCase();
294 
295         try {
296             folderIdMap = new HashMap<>();
297             // load actual well-known folder ids
298             folderIdMap.put(internalGetFolder(INBOX).folderId.value, INBOX);
299             folderIdMap.put(internalGetFolder(CALENDAR).folderId.value, CALENDAR);
300             folderIdMap.put(internalGetFolder(CONTACTS).folderId.value, CONTACTS);
301             folderIdMap.put(internalGetFolder(SENT).folderId.value, SENT);
302             folderIdMap.put(internalGetFolder(DRAFTS).folderId.value, DRAFTS);
303             folderIdMap.put(internalGetFolder(TRASH).folderId.value, TRASH);
304             folderIdMap.put(internalGetFolder(JUNK).folderId.value, JUNK);
305             folderIdMap.put(internalGetFolder(UNSENT).folderId.value, UNSENT);
306         } catch (IOException e) {
307             LOGGER.error(e.getMessage(), e);
308             throw new DavMailAuthenticationException("EXCEPTION_EWS_NOT_AVAILABLE");
309         }
310         LOGGER.debug("Current user email is " + email + ", alias is " + alias + " on " + serverVersion);
311     }
312 
313     protected String getEmailSuffixFromHostname() {
314         String domain = httpClient.getHost();
315         int start = domain.lastIndexOf('.', domain.lastIndexOf('.') - 1);
316         if (start >= 0) {
317             return '@' + domain.substring(start + 1);
318         } else {
319             return '@' + domain;
320         }
321     }
322 
323     protected void resolveEmailAddress(String userName) {
324         String searchValue = userName;
325         int index = searchValue.indexOf('\\');
326         if (index >= 0) {
327             searchValue = searchValue.substring(index + 1);
328         }
329         ResolveNamesMethod resolveNamesMethod = new ResolveNamesMethod(searchValue);
330         try {
331             // send a fake request to get server version
332             internalGetFolder("");
333             executeMethod(resolveNamesMethod);
334             List<EWSMethod.Item> responses = resolveNamesMethod.getResponseItems();
335             if (responses.size() == 1) {
336                 email = responses.get(0).get("EmailAddress");
337             }
338 
339         } catch (IOException e) {
340             // ignore
341         }
342     }
343 
344     class Message extends ExchangeSession.Message {
345         // message item id
346         ItemId itemId;
347 
348         @Override
349         public String getPermanentId() {
350             return itemId.id;
351         }
352 
353         @Override
354         protected InputStream getMimeHeaders() {
355             InputStream result = null;
356             try {
357                 GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, false);
358                 getItemMethod.addAdditionalProperty(Field.get("messageheaders"));
359                 getItemMethod.addAdditionalProperty(Field.get("from"));
360                 executeMethod(getItemMethod);
361                 EWSMethod.Item item = getItemMethod.getResponseItem();
362 
363                 String messageHeaders = item.get(Field.get("messageheaders").getResponseName());
364                 if (messageHeaders != null
365                         // workaround for broken message headers on Exchange 2010
366                         && messageHeaders.toLowerCase().contains("message-id:")) {
367                     // workaround for messages in Sent folder
368                     if (!messageHeaders.contains("From:")) {
369                         String from = item.get(Field.get("from").getResponseName());
370                         if (from != null) {
371                             messageHeaders = "From: " + MimeUtility.encodeText(from, "UTF-8", null) + '\r' + '\n' + messageHeaders;
372                         }
373                     }
374 
375                     result = new ByteArrayInputStream(messageHeaders.getBytes(StandardCharsets.UTF_8));
376                 }
377             } catch (Exception e) {
378                 LOGGER.warn(e.getMessage());
379             }
380 
381             return result;
382         }
383     }
384 
385     /**
386      * Message create/update properties
387      *
388      * @param properties flag values map
389      * @return field values
390      */
391     protected List<FieldUpdate> buildProperties(Map<String, String> properties) {
392         ArrayList<FieldUpdate> list = new ArrayList<>();
393         for (Map.Entry<String, String> entry : properties.entrySet()) {
394             if ("read".equals(entry.getKey())) {
395                 list.add(Field.createFieldUpdate("read", Boolean.toString("1".equals(entry.getValue()))));
396             } else if ("junk".equals(entry.getKey())) {
397                 list.add(Field.createFieldUpdate("junk", entry.getValue()));
398             } else if ("flagged".equals(entry.getKey())) {
399                 list.add(Field.createFieldUpdate("flagStatus", entry.getValue()));
400             } else if ("answered".equals(entry.getKey())) {
401                 list.add(Field.createFieldUpdate("lastVerbExecuted", entry.getValue()));
402                 if ("102".equals(entry.getValue())) {
403                     list.add(Field.createFieldUpdate("iconIndex", "261"));
404                 }
405             } else if ("forwarded".equals(entry.getKey())) {
406                 list.add(Field.createFieldUpdate("lastVerbExecuted", entry.getValue()));
407                 if ("104".equals(entry.getValue())) {
408                     list.add(Field.createFieldUpdate("iconIndex", "262"));
409                 }
410             } else if ("draft".equals(entry.getKey())) {
411                 // note: draft is readonly after creation
412                 list.add(Field.createFieldUpdate("messageFlags", entry.getValue()));
413             } else if ("deleted".equals(entry.getKey())) {
414                 list.add(Field.createFieldUpdate("deleted", entry.getValue()));
415             } else if ("datereceived".equals(entry.getKey())) {
416                 list.add(Field.createFieldUpdate("datereceived", entry.getValue()));
417             } else if ("keywords".equals(entry.getKey())) {
418                 list.add(Field.createFieldUpdate("keywords", entry.getValue()));
419             }
420         }
421         return list;
422     }
423 
424     @Override
425     public ExchangeSession.Message createMessage(String folderPath, String messageName, HashMap<String, String> properties, MimeMessage mimeMessage) throws IOException {
426         EWSMethod.Item item = new EWSMethod.Item();
427         item.type = "Message";
428         ByteArrayOutputStream baos = new ByteArrayOutputStream();
429         try {
430             mimeMessage.writeTo(baos);
431         } catch (MessagingException e) {
432             throw new IOException(e.getMessage());
433         }
434         baos.close();
435         item.mimeContent = IOUtil.encodeBase64(baos.toByteArray());
436 
437         List<FieldUpdate> fieldUpdates = buildProperties(properties);
438         if (!properties.containsKey("draft")) {
439             // need to force draft flag to false
440             if (properties.containsKey("read")) {
441                 fieldUpdates.add(Field.createFieldUpdate("messageFlags", "1"));
442             } else {
443                 fieldUpdates.add(Field.createFieldUpdate("messageFlags", "0"));
444             }
445         }
446         fieldUpdates.add(Field.createFieldUpdate("urlcompname", messageName));
447         item.setFieldUpdates(fieldUpdates);
448         CreateItemMethod createItemMethod = new CreateItemMethod(MessageDisposition.SaveOnly, getFolderId(folderPath), item);
449         executeMethod(createItemMethod);
450 
451         ItemId newItemId = new ItemId(createItemMethod.getResponseItem());
452         GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, newItemId, false);
453         for (String attribute : IMAP_MESSAGE_ATTRIBUTES) {
454             getItemMethod.addAdditionalProperty(Field.get(attribute));
455         }
456         executeMethod(getItemMethod);
457 
458         return buildMessage(getItemMethod.getResponseItem());
459 
460     }
461 
462     @Override
463     public void updateMessage(ExchangeSession.Message message, Map<String, String> properties) throws IOException {
464         if (properties.containsKey("read") && "urn:content-classes:appointment".equals(message.contentClass)) {
465             properties.remove("read");
466         }
467         if (!properties.isEmpty()) {
468             UpdateItemMethod updateItemMethod = new UpdateItemMethod(MessageDisposition.SaveOnly,
469                     ConflictResolution.AlwaysOverwrite,
470                     SendMeetingInvitationsOrCancellations.SendToNone,
471                     ((EwsExchangeSession.Message) message).itemId, buildProperties(properties));
472             executeMethod(updateItemMethod);
473         }
474     }
475 
476     @Override
477     public void deleteMessage(ExchangeSession.Message message) throws IOException {
478         LOGGER.debug("Delete " + message.imapUid);
479         DeleteItemMethod deleteItemMethod = new DeleteItemMethod(((EwsExchangeSession.Message) message).itemId, DeleteType.HardDelete, SendMeetingCancellations.SendToNone);
480         executeMethod(deleteItemMethod);
481     }
482 
483 
484     protected void sendMessage(String itemClass, byte[] messageBody) throws IOException {
485         EWSMethod.Item item = new EWSMethod.Item();
486         item.type = "Message";
487         item.mimeContent = IOUtil.encodeBase64(messageBody);
488         if (itemClass != null) {
489             item.put("ItemClass", itemClass);
490         }
491 
492         MessageDisposition messageDisposition;
493         if (Settings.getBooleanProperty("davmail.smtpSaveInSent", true)) {
494             messageDisposition = MessageDisposition.SendAndSaveCopy;
495         } else {
496             messageDisposition = MessageDisposition.SendOnly;
497         }
498 
499         CreateItemMethod createItemMethod = new CreateItemMethod(messageDisposition, getFolderId(SENT), item);
500         executeMethod(createItemMethod);
501     }
502 
503     @Override
504     public void sendMessage(MimeMessage mimeMessage) throws IOException, MessagingException {
505         String itemClass = null;
506         if (mimeMessage.getContentType().startsWith("multipart/report")) {
507             itemClass = "REPORT.IPM.Note.IPNRN";
508         }
509 
510         ByteArrayOutputStream baos = new ByteArrayOutputStream();
511         try {
512             mimeMessage.writeTo(baos);
513         } catch (MessagingException e) {
514             throw new IOException(e.getMessage());
515         }
516         sendMessage(itemClass, baos.toByteArray());
517     }
518 
519     /**
520      * @inheritDoc
521      */
522     @Override
523     protected byte[] getContent(ExchangeSession.Message message) throws IOException {
524         return getContent(((EwsExchangeSession.Message) message).itemId);
525     }
526 
527     /**
528      * Get item content.
529      *
530      * @param itemId EWS item id
531      * @return item content as a byte array
532      * @throws IOException on error
533      */
534     protected byte[] getContent(ItemId itemId) throws IOException {
535         GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, true);
536         byte[] mimeContent = null;
537         try {
538             executeMethod(getItemMethod);
539             mimeContent = getItemMethod.getMimeContent();
540         } catch (EWSException e) {
541             LOGGER.warn("GetItem with MimeContent failed: " + e.getMessage());
542         }
543         if (getItemMethod.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
544             throw new HttpNotFoundException("Item " + itemId + " not found");
545         }
546         if (mimeContent == null) {
547             LOGGER.warn("MimeContent not available, trying to rebuild from properties");
548             try {
549                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
550                 getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, false);
551                 getItemMethod.addAdditionalProperty(Field.get("contentclass"));
552                 getItemMethod.addAdditionalProperty(Field.get("message-id"));
553                 getItemMethod.addAdditionalProperty(Field.get("from"));
554                 getItemMethod.addAdditionalProperty(Field.get("to"));
555                 getItemMethod.addAdditionalProperty(Field.get("cc"));
556                 getItemMethod.addAdditionalProperty(Field.get("subject"));
557                 getItemMethod.addAdditionalProperty(Field.get("date"));
558                 getItemMethod.addAdditionalProperty(Field.get("body"));
559                 executeMethod(getItemMethod);
560                 EWSMethod.Item item = getItemMethod.getResponseItem();
561 
562                 if (item == null) {
563                     throw new HttpNotFoundException("Item " + itemId + " not found");
564                 }
565 
566                 MimeMessage mimeMessage = new MimeMessage((Session) null);
567                 mimeMessage.addHeader("Content-class", item.get(Field.get("contentclass").getResponseName()));
568                 mimeMessage.setSentDate(parseDateFromExchange(item.get(Field.get("date").getResponseName())));
569                 mimeMessage.addHeader("From", item.get(Field.get("from").getResponseName()));
570                 mimeMessage.addHeader("To", item.get(Field.get("to").getResponseName()));
571                 mimeMessage.addHeader("Cc", item.get(Field.get("cc").getResponseName()));
572                 mimeMessage.setSubject(item.get(Field.get("subject").getResponseName()));
573                 String propertyValue = item.get(Field.get("body").getResponseName());
574                 if (propertyValue == null) {
575                     propertyValue = "";
576                 }
577                 mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8");
578 
579                 mimeMessage.writeTo(baos);
580                 if (LOGGER.isDebugEnabled()) {
581                     LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray(), StandardCharsets.UTF_8));
582                 }
583                 mimeContent = baos.toByteArray();
584 
585             } catch (IOException | MessagingException e2) {
586                 LOGGER.warn(e2);
587             }
588             if (mimeContent == null) {
589                 throw new IOException("GetItem returned null MimeContent");
590             }
591         }
592         return mimeContent;
593     }
594 
595     protected ExchangeSession.Message buildMessage(EWSMethod.Item response) throws DavMailException {
596         Message message = new Message();
597 
598         // get item id
599         message.itemId = new ItemId(response);
600 
601         message.permanentUrl = response.get(Field.get("permanenturl").getResponseName());
602 
603         message.size = response.getInt(Field.get("messageSize").getResponseName());
604         message.uid = response.get(Field.get("uid").getResponseName());
605         message.contentClass = response.get(Field.get("contentclass").getResponseName());
606         message.imapUid = response.getLong(Field.get("imapUid").getResponseName());
607         message.read = response.getBoolean(Field.get("read").getResponseName());
608         message.junk = response.getBoolean(Field.get("junk").getResponseName());
609         message.flagged = "2".equals(response.get(Field.get("flagStatus").getResponseName()));
610         message.draft = (response.getInt(Field.get("messageFlags").getResponseName()) & 8) != 0;
611         String lastVerbExecuted = response.get(Field.get("lastVerbExecuted").getResponseName());
612         message.answered = "102".equals(lastVerbExecuted) || "103".equals(lastVerbExecuted);
613         message.forwarded = "104".equals(lastVerbExecuted);
614         message.date = convertDateFromExchange(response.get(Field.get("date").getResponseName()));
615         message.deleted = "1".equals(response.get(Field.get("deleted").getResponseName()));
616 
617         String lastmodified = convertDateFromExchange(response.get(Field.get("lastmodified").getResponseName()));
618         message.recent = !message.read && lastmodified != null && lastmodified.equals(message.date);
619 
620         message.keywords = response.get(Field.get("keywords").getResponseName());
621 
622         if (LOGGER.isDebugEnabled()) {
623             StringBuilder buffer = new StringBuilder();
624             buffer.append("Message");
625             if (message.imapUid != 0) {
626                 buffer.append(" IMAP uid: ").append(message.imapUid);
627             }
628             if (message.uid != null) {
629                 buffer.append(" uid: ").append(message.uid);
630             }
631             buffer.append(" ItemId: ").append(message.itemId.id);
632             buffer.append(" ChangeKey: ").append(message.itemId.changeKey);
633             LOGGER.debug(buffer.toString());
634         }
635         return message;
636     }
637 
638     @Override
639     public MessageList searchMessages(String folderPath, Set<String> attributes, Condition condition) throws IOException {
640         MessageList messages = new MessageList();
641         int maxCount = Settings.getIntProperty("davmail.folderSizeLimit", 0);
642         List<EWSMethod.Item> responses = searchItems(folderPath, attributes, condition, FolderQueryTraversal.SHALLOW, maxCount);
643 
644         for (EWSMethod.Item response : responses) {
645             if (MESSAGE_TYPES.contains(response.type)) {
646                 messages.add(buildMessage(response));
647             }
648         }
649         Collections.sort(messages);
650         return messages;
651     }
652 
653     protected List<EWSMethod.Item> searchItems(String folderPath, Set<String> attributes, Condition condition, FolderQueryTraversal folderQueryTraversal, int maxCount) throws IOException {
654         if (maxCount == 0) {
655             // unlimited search
656             return searchItems(folderPath, attributes, condition, folderQueryTraversal);
657         }
658         // limited search, do not use paged search, limit with maxCount, sort by imapUid descending to get latest items
659         int resultCount;
660         FindItemMethod findItemMethod;
661 
662         // search items in folder, do not retrieve all properties
663         findItemMethod = new FindItemMethod(folderQueryTraversal, BaseShape.ID_ONLY, getFolderId(folderPath), 0, maxCount);
664         for (String attribute : attributes) {
665             findItemMethod.addAdditionalProperty(Field.get(attribute));
666         }
667         // make sure imapUid is available
668         if (!attributes.contains("imapUid")) {
669             findItemMethod.addAdditionalProperty(Field.get("imapUid"));
670         }
671 
672         // always sort items by imapUid descending to retrieve recent messages first
673         findItemMethod.setFieldOrder(new FieldOrder(Field.get("imapUid"), FieldOrder.Order.Descending));
674 
675         if (condition != null && !condition.isEmpty()) {
676             findItemMethod.setSearchExpression((SearchExpression) condition);
677         }
678         executeMethod(findItemMethod);
679         List<EWSMethod.Item> results = new ArrayList<>(findItemMethod.getResponseItems());
680         resultCount = results.size();
681         if (resultCount > 0 && LOGGER.isDebugEnabled()) {
682             LOGGER.debug("Folder " + folderPath + " - Search items count: " + resultCount + " maxCount: " + maxCount
683                     + " highest uid: " + results.get(0).getLong(Field.get("imapUid").getResponseName())
684                     + " lowest uid: " + results.get(resultCount - 1).getLong(Field.get("imapUid").getResponseName()));
685         }
686 
687 
688         return results;
689     }
690 
691     /**
692      * Paged search, retrieve all items.
693      *
694      * @param folderPath           folder path
695      * @param attributes           attributes
696      * @param condition            search condition
697      * @param folderQueryTraversal search mode
698      * @return items
699      * @throws IOException on error
700      */
701     protected List<EWSMethod.Item> searchItems(String folderPath, Set<String> attributes, Condition condition, FolderQueryTraversal folderQueryTraversal) throws IOException {
702         int resultCount = 0;
703         List<EWSMethod.Item> results = new ArrayList<>();
704         FolderId folderId = getFolderId(folderPath);
705         FindItemMethod findItemMethod;
706         do {
707             // search items in folder, do not retrieve all properties
708             findItemMethod = new FindItemMethod(folderQueryTraversal, BaseShape.ID_ONLY, folderId, resultCount, getPageSize());
709             for (String attribute : attributes) {
710                 findItemMethod.addAdditionalProperty(Field.get(attribute));
711             }
712             // make sure imapUid is available
713             if (!attributes.contains("imapUid")) {
714                 findItemMethod.addAdditionalProperty(Field.get("imapUid"));
715             }
716 
717             // always sort items by imapUid ascending to retrieve pages in creation order
718             findItemMethod.setFieldOrder(new FieldOrder(Field.get("imapUid"), FieldOrder.Order.Ascending));
719 
720             if (condition != null && !condition.isEmpty()) {
721                 findItemMethod.setSearchExpression((SearchExpression) condition);
722             }
723             executeMethod(findItemMethod);
724             if (findItemMethod.getStatusCode() == HttpStatus.SC_FORBIDDEN) {
725                 throw new EWSException(findItemMethod.errorDetail);
726             }
727 
728             long highestUid = 0;
729             if (resultCount > 0) {
730                 highestUid = results.get(resultCount - 1).getLong(Field.get("imapUid").getResponseName());
731             }
732             // Only add new result if not already available (concurrent folder changes issue)
733             for (EWSMethod.Item item : findItemMethod.getResponseItems()) {
734                 long imapUid = item.getLong(Field.get("imapUid").getResponseName());
735                 if (imapUid > highestUid) {
736                     results.add(item);
737                 }
738             }
739             resultCount = results.size();
740             if (resultCount > 0 && LOGGER.isDebugEnabled()) {
741                 LOGGER.debug("Folder " + folderPath + " - Search items current count: " + resultCount + " fetchCount: " + getPageSize()
742                         + " highest uid: " + results.get(resultCount - 1).getLong(Field.get("imapUid").getResponseName())
743                         + " lowest uid: " + results.get(0).getLong(Field.get("imapUid").getResponseName()));
744             }
745             if (Thread.interrupted()) {
746                 LOGGER.debug("Folder " + folderPath + " - Search items failed: Interrupted by client");
747                 throw new IOException("Search items failed: Interrupted by client");
748             }
749         } while (!(findItemMethod.includesLastItemInRange));
750         return results;
751     }
752 
753     protected static class MultiCondition extends ExchangeSession.MultiCondition implements SearchExpression {
754         protected MultiCondition(Operator operator, Condition... condition) {
755             super(operator, condition);
756         }
757 
758         public void appendTo(StringBuilder buffer) {
759             int actualConditionCount = getActualConditionCount();
760             if (actualConditionCount > 0) {
761                 if (actualConditionCount > 1) {
762                     buffer.append("<t:").append(operator.toString()).append('>');
763                 }
764 
765                 for (Condition condition : conditions) {
766                     condition.appendTo(buffer);
767                 }
768 
769                 if (actualConditionCount > 1) {
770                     buffer.append("</t:").append(operator).append('>');
771                 }
772             }
773         }
774     }
775 
776     protected static class NotCondition extends ExchangeSession.NotCondition implements SearchExpression {
777         protected NotCondition(Condition condition) {
778             super(condition);
779         }
780 
781         public void appendTo(StringBuilder buffer) {
782             buffer.append("<t:Not>");
783             condition.appendTo(buffer);
784             buffer.append("</t:Not>");
785         }
786     }
787 
788 
789     protected static class AttributeCondition extends ExchangeSession.AttributeCondition implements SearchExpression {
790         protected ContainmentMode containmentMode;
791         protected ContainmentComparison containmentComparison;
792 
793         protected AttributeCondition(String attributeName, Operator operator, String value) {
794             super(attributeName, operator, value);
795         }
796 
797         protected AttributeCondition(String attributeName, Operator operator, String value,
798                                      ContainmentMode containmentMode, ContainmentComparison containmentComparison) {
799             super(attributeName, operator, value);
800             this.containmentMode = containmentMode;
801             this.containmentComparison = containmentComparison;
802         }
803 
804         protected FieldURI getFieldURI() {
805             FieldURI fieldURI = Field.get(attributeName);
806             // check to detect broken field mapping
807             //noinspection ConstantConditions
808             if (fieldURI == null) {
809                 throw new IllegalArgumentException("Unknown field: " + attributeName);
810             }
811             return fieldURI;
812         }
813 
814         protected Operator getOperator() {
815             return operator;
816         }
817 
818         public void appendTo(StringBuilder buffer) {
819             buffer.append("<t:").append(operator.toString());
820             if (containmentMode != null) {
821                 containmentMode.appendTo(buffer);
822             }
823             if (containmentComparison != null) {
824                 containmentComparison.appendTo(buffer);
825             }
826             buffer.append('>');
827             FieldURI fieldURI = getFieldURI();
828             fieldURI.appendTo(buffer);
829 
830             if (operator != Operator.Contains) {
831                 buffer.append("<t:FieldURIOrConstant>");
832             }
833             buffer.append("<t:Constant Value=\"");
834             // encode urlcompname
835             if (fieldURI instanceof ExtendedFieldURI && "0x10f3".equals(((ExtendedFieldURI) fieldURI).propertyTag)) {
836                 buffer.append(StringUtil.xmlEncodeAttribute(StringUtil.encodeUrlcompname(value)));
837             } else if (fieldURI instanceof ExtendedFieldURI
838                     && ((ExtendedFieldURI) fieldURI).propertyType == ExtendedFieldURI.PropertyType.Integer) {
839                 // check value
840                 try {
841                     Integer.parseInt(value);
842                     buffer.append(value);
843                 } catch (NumberFormatException e) {
844                     // invalid value, replace value with 0
845                     buffer.append('0');
846                 }
847             } else {
848                 buffer.append(StringUtil.xmlEncodeAttribute(value));
849             }
850             buffer.append("\"/>");
851             if (operator != Operator.Contains) {
852                 buffer.append("</t:FieldURIOrConstant>");
853             }
854 
855             buffer.append("</t:").append(operator).append('>');
856         }
857 
858         public boolean isMatch(ExchangeSession.Contact contact) {
859             String lowerCaseValue = value.toLowerCase();
860 
861             String actualValue = contact.get(attributeName);
862             if (actualValue == null) {
863                 return false;
864             }
865             actualValue = actualValue.toLowerCase();
866             if (operator == Operator.IsEqualTo) {
867                 return lowerCaseValue.equals(actualValue);
868             } else {
869                 return operator == Operator.Contains && ((containmentMode.equals(ContainmentMode.Substring) && actualValue.contains(lowerCaseValue)) ||
870                         (containmentMode.equals(ContainmentMode.Prefixed) && actualValue.startsWith(lowerCaseValue)));
871             }
872         }
873 
874     }
875 
876     protected static class HeaderCondition extends AttributeCondition {
877 
878         protected HeaderCondition(String attributeName, String value) {
879             super(attributeName, Operator.Contains, value);
880             containmentMode = ContainmentMode.Substring;
881             containmentComparison = ContainmentComparison.IgnoreCase;
882         }
883 
884         @Override
885         protected FieldURI getFieldURI() {
886             return new ExtendedFieldURI(ExtendedFieldURI.DistinguishedPropertySetType.InternetHeaders, attributeName);
887         }
888 
889     }
890 
891     protected static class IsNullCondition implements ExchangeSession.Condition, SearchExpression {
892         protected final String attributeName;
893 
894         protected IsNullCondition(String attributeName) {
895             this.attributeName = attributeName;
896         }
897 
898         public void appendTo(StringBuilder buffer) {
899             buffer.append("<t:Not><t:Exists>");
900             Field.get(attributeName).appendTo(buffer);
901             buffer.append("</t:Exists></t:Not>");
902         }
903 
904         public boolean isEmpty() {
905             return false;
906         }
907 
908         public boolean isMatch(ExchangeSession.Contact contact) {
909             String actualValue = contact.get(attributeName);
910             return actualValue == null;
911         }
912 
913     }
914 
915     protected static class ExistsCondition implements ExchangeSession.Condition, SearchExpression {
916         protected final String attributeName;
917 
918         protected ExistsCondition(String attributeName) {
919             this.attributeName = attributeName;
920         }
921 
922         public void appendTo(StringBuilder buffer) {
923             buffer.append("<t:Exists>");
924             Field.get(attributeName).appendTo(buffer);
925             buffer.append("</t:Exists>");
926         }
927 
928         public boolean isEmpty() {
929             return false;
930         }
931 
932         public boolean isMatch(ExchangeSession.Contact contact) {
933             String actualValue = contact.get(attributeName);
934             return actualValue != null;
935         }
936 
937     }
938 
939     @Override
940     public ExchangeSession.MultiCondition and(Condition... condition) {
941         return new MultiCondition(Operator.And, condition);
942     }
943 
944     @Override
945     public ExchangeSession.MultiCondition or(Condition... condition) {
946         return new MultiCondition(Operator.Or, condition);
947     }
948 
949     @Override
950     public Condition not(Condition condition) {
951         return new NotCondition(condition);
952     }
953 
954     @Override
955     public Condition isEqualTo(String attributeName, String value) {
956         return new AttributeCondition(attributeName, Operator.IsEqualTo, value);
957     }
958 
959     @Override
960     public Condition isEqualTo(String attributeName, int value) {
961         return new AttributeCondition(attributeName, Operator.IsEqualTo, String.valueOf(value));
962     }
963 
964     @Override
965     public Condition headerIsEqualTo(String headerName, String value) {
966         if (serverVersion.startsWith("Exchange201")) {
967             if ("from".equals(headerName)
968                     || "to".equals(headerName)
969                     || "cc".equals(headerName)) {
970                 return new AttributeCondition("msg" + headerName, Operator.Contains, value, ContainmentMode.Substring, ContainmentComparison.IgnoreCase);
971             } else if ("message-id".equals(headerName)
972                     || "bcc".equals(headerName)) {
973                 return new AttributeCondition(headerName, Operator.Contains, value, ContainmentMode.Substring, ContainmentComparison.IgnoreCase);
974             } else {
975                 // Exchange 2010 does not support header search, use PR_TRANSPORT_MESSAGE_HEADERS instead
976                 return new AttributeCondition("messageheaders", Operator.Contains, headerName + ": " + value, ContainmentMode.Substring, ContainmentComparison.IgnoreCase);
977             }
978         } else {
979             return new HeaderCondition(headerName, value);
980         }
981     }
982 
983     @Override
984     public Condition gte(String attributeName, String value) {
985         return new AttributeCondition(attributeName, Operator.IsGreaterThanOrEqualTo, value);
986     }
987 
988     @Override
989     public Condition lte(String attributeName, String value) {
990         return new AttributeCondition(attributeName, Operator.IsLessThanOrEqualTo, value);
991     }
992 
993     @Override
994     public Condition lt(String attributeName, String value) {
995         return new AttributeCondition(attributeName, Operator.IsLessThan, value);
996     }
997 
998     @Override
999     public Condition gt(String attributeName, String value) {
1000         return new AttributeCondition(attributeName, Operator.IsGreaterThan, value);
1001     }
1002 
1003     @Override
1004     public Condition contains(String attributeName, String value) {
1005         // workaround for from: and to: headers not searchable over EWS
1006         if ("from".equals(attributeName)) {
1007             attributeName = "msgfrom";
1008         } else if ("to".equals(attributeName)) {
1009             attributeName = "displayto";
1010         } else if ("cc".equals(attributeName)) {
1011             attributeName = "displaycc";
1012         }
1013         return new AttributeCondition(attributeName, Operator.Contains, value, ContainmentMode.Substring, ContainmentComparison.IgnoreCase);
1014     }
1015 
1016     @Override
1017     public Condition startsWith(String attributeName, String value) {
1018         return new AttributeCondition(attributeName, Operator.Contains, value, ContainmentMode.Prefixed, ContainmentComparison.IgnoreCase);
1019     }
1020 
1021     @Override
1022     public Condition isNull(String attributeName) {
1023         return new IsNullCondition(attributeName);
1024     }
1025 
1026     @Override
1027     public Condition exists(String attributeName) {
1028         return new ExistsCondition(attributeName);
1029     }
1030 
1031     @Override
1032     public Condition isTrue(String attributeName) {
1033         return new AttributeCondition(attributeName, Operator.IsEqualTo, "true");
1034     }
1035 
1036     @Override
1037     public Condition isFalse(String attributeName) {
1038         return new AttributeCondition(attributeName, Operator.IsEqualTo, "false");
1039     }
1040 
1041     protected static final HashSet<FieldURI> FOLDER_PROPERTIES = new HashSet<>();
1042 
1043     static {
1044         FOLDER_PROPERTIES.add(Field.get("urlcompname"));
1045         FOLDER_PROPERTIES.add(Field.get("parentfolderid"));
1046         FOLDER_PROPERTIES.add(Field.get("folderDisplayName"));
1047         FOLDER_PROPERTIES.add(Field.get("lastmodified"));
1048         FOLDER_PROPERTIES.add(Field.get("folderclass"));
1049         FOLDER_PROPERTIES.add(Field.get("ctag"));
1050         FOLDER_PROPERTIES.add(Field.get("count"));
1051         FOLDER_PROPERTIES.add(Field.get("unread"));
1052         FOLDER_PROPERTIES.add(Field.get("hassubs"));
1053         FOLDER_PROPERTIES.add(Field.get("uidNext"));
1054         FOLDER_PROPERTIES.add(Field.get("highestUid"));
1055     }
1056 
1057     protected Folder buildFolder(EWSMethod.Item item) {
1058         Folder folder = new Folder();
1059         folder.folderId = new FolderId(item);
1060         folder.displayName = encodeFolderName(item.get(Field.get("folderDisplayName").getResponseName()));
1061         folder.folderClass = item.get(Field.get("folderclass").getResponseName());
1062         folder.etag = item.get(Field.get("lastmodified").getResponseName());
1063         folder.ctag = item.get(Field.get("ctag").getResponseName());
1064         folder.messageCount = item.getInt(Field.get("count").getResponseName());
1065         folder.unreadCount = item.getInt(Field.get("unread").getResponseName());
1066         // fake recent value
1067         folder.recent = folder.unreadCount;
1068         folder.hasChildren = item.getBoolean(Field.get("hassubs").getResponseName());
1069         // noInferiors not implemented
1070         folder.uidNext = item.getInt(Field.get("uidNext").getResponseName());
1071         return folder;
1072     }
1073 
1074     /**
1075      * @inheritDoc
1076      */
1077     @Override
1078     public List<ExchangeSession.Folder> getSubFolders(String folderPath, Condition condition, boolean recursive) throws IOException {
1079         String baseFolderPath = folderPath;
1080         if (baseFolderPath.startsWith("/users/")) {
1081             int index = baseFolderPath.indexOf('/', "/users/".length());
1082             if (index >= 0) {
1083                 baseFolderPath = baseFolderPath.substring(index + 1);
1084             }
1085         }
1086         List<ExchangeSession.Folder> folders = new ArrayList<>();
1087         appendSubFolders(folders, baseFolderPath, getFolderId(folderPath), condition, recursive);
1088         return folders;
1089     }
1090 
1091     protected void appendSubFolders(List<ExchangeSession.Folder> folders,
1092                                     String parentFolderPath, FolderId parentFolderId,
1093                                     Condition condition, boolean recursive) throws IOException {
1094         if (recursive) {
1095             appendSubFoldersDeep(folders, parentFolderPath, parentFolderId, condition);
1096         } else {
1097             appendSubFoldersShallow(folders, parentFolderPath, parentFolderId, condition);
1098         }
1099     }
1100 
1101     protected void appendSubFoldersShallow(List<ExchangeSession.Folder> folders,
1102                                            String parentFolderPath, FolderId parentFolderId,
1103                                            Condition condition) throws IOException {
1104         int resultCount = 0;
1105         FindFolderMethod findFolderMethod;
1106         do {
1107             findFolderMethod = new FindFolderMethod(FolderQueryTraversal.SHALLOW,
1108                     BaseShape.ID_ONLY, parentFolderId, FOLDER_PROPERTIES, (SearchExpression) condition, resultCount, getPageSize());
1109             executeMethod(findFolderMethod);
1110             for (EWSMethod.Item item : findFolderMethod.getResponseItems()) {
1111                 resultCount++;
1112                 Folder folder = buildFolder(item);
1113                 if (!parentFolderPath.isEmpty()) {
1114                     if (parentFolderPath.endsWith("/")) {
1115                         folder.folderPath = parentFolderPath + folder.displayName;
1116                     } else {
1117                         folder.folderPath = parentFolderPath + '/' + folder.displayName;
1118                     }
1119                 } else if (folderIdMap.get(folder.folderId.value) != null) {
1120                     folder.folderPath = folderIdMap.get(folder.folderId.value);
1121                 } else {
1122                     folder.folderPath = folder.displayName;
1123                 }
1124                 folders.add(folder);
1125             }
1126         } while (!(findFolderMethod.includesLastItemInRange));
1127     }
1128 
1129     protected void appendSubFoldersDeep(List<ExchangeSession.Folder> folders,
1130                                         String parentFolderPath, FolderId parentFolderId,
1131                                         Condition condition) throws IOException {
1132         Map<String, String> parentByFolderId = new HashMap<>();
1133         List<Folder> deepFolders = new ArrayList<>();
1134         int resultCount = 0;
1135         FindFolderMethod findFolderMethod;
1136         do {
1137             findFolderMethod = new FindFolderMethod(FolderQueryTraversal.DEEP,
1138                     BaseShape.ID_ONLY, parentFolderId, FOLDER_PROPERTIES, (SearchExpression) condition, resultCount, getPageSize());
1139             executeMethod(findFolderMethod);
1140             for (EWSMethod.Item item : findFolderMethod.getResponseItems()) {
1141                 resultCount++;
1142                 Folder folder = buildFolder(item);
1143                 deepFolders.add(folder);
1144                 parentByFolderId.put(folder.folderId.value, item.get("ParentFolderId"));
1145             }
1146         } while (!(findFolderMethod.includesLastItemInRange));
1147 
1148         // Build a map of parent -> children for top-down traversal
1149         Map<String, List<Folder>> childrenByParentId = new HashMap<>();
1150         for (Folder folder : deepFolders) {
1151             String parentId = parentByFolderId.get(folder.folderId.value);
1152             childrenByParentId.computeIfAbsent(parentId, k -> new ArrayList<>()).add(folder);
1153         }
1154 
1155         // Iterate from root, assigning paths top-down
1156         String rootId = parentFolderId.value;
1157         // if root is a DistinguishedFolderId, need to fetch actual id for parent id mapping
1158         if (parentFolderId instanceof DistinguishedFolderId) {
1159             rootId = internalGetFolder(parentFolderId, parentFolderPath).folderId.value;
1160         }
1161 
1162         Deque<Map.Entry<String, String>> queue = new ArrayDeque<>();
1163         // Seed: children of the root folder
1164         queue.add(new AbstractMap.SimpleEntry<>(rootId, parentFolderPath));
1165 
1166         while (!queue.isEmpty()) {
1167             Map.Entry<String, String> entry = queue.poll();
1168             String currentParentId = entry.getKey();
1169             String currentParentPath = entry.getValue();
1170 
1171             List<Folder> children = childrenByParentId.get(currentParentId);
1172             if (children != null) {
1173                 for (Folder childFolder : children) {
1174                     String childFolderId = childFolder.folderId.value;
1175 
1176                     // Determine child folder path
1177                     if (folderIdMap.get(childFolderId) != null) {
1178                         // use special foldes name
1179                         childFolder.folderPath = folderIdMap.get(childFolderId);
1180                     } else if (currentParentPath.isEmpty()) {
1181                         childFolder.folderPath = childFolder.displayName;
1182                     } else if (currentParentPath.endsWith("/")) {
1183                         childFolder.folderPath = currentParentPath + childFolder.displayName;
1184                     } else {
1185                         childFolder.folderPath = currentParentPath + '/' + childFolder.displayName;
1186                     }
1187                     folders.add(childFolder);
1188 
1189                     // Enqueue this folder so its children get the correct prefix
1190                     queue.add(new AbstractMap.SimpleEntry<>(childFolderId, childFolder.folderPath));
1191                 }
1192             }
1193         }
1194 
1195     }
1196 
1197     /**
1198      * Get folder by path.
1199      *
1200      * @param folderPath folder path
1201      * @return folder object
1202      * @throws IOException on error
1203      */
1204     @Override
1205     protected EwsExchangeSession.Folder internalGetFolder(String folderPath) throws IOException {
1206         FolderId folderId = getFolderId(folderPath);
1207         return internalGetFolder(folderId, folderPath);
1208     }
1209 
1210     protected EwsExchangeSession.Folder internalGetFolder(FolderId folderId, String folderPath) throws IOException {
1211         GetFolderMethod getFolderMethod = new GetFolderMethod(BaseShape.ID_ONLY, folderId, FOLDER_PROPERTIES);
1212         executeMethod(getFolderMethod);
1213         EWSMethod.Item item = getFolderMethod.getResponseItem();
1214         Folder folder;
1215         if (item != null) {
1216             folder = buildFolder(item);
1217             folder.folderPath = folderPath;
1218         } else {
1219             throw new HttpNotFoundException("Folder " + folderPath + " not found");
1220         }
1221         return folder;
1222     }
1223 
1224     /**
1225      * @inheritDoc
1226      */
1227     @Override
1228     public int createFolder(String folderPath, String folderClass, Map<String, String> properties) throws IOException {
1229         FolderPath path = new FolderPath(folderPath);
1230         EWSMethod.Item folder = new EWSMethod.Item();
1231         if ("IPF.Contact".equals(folderClass)) {
1232             folder.type = "ContactsFolder";
1233         } else if ("IPF.Appointment".equals(folderClass)) {
1234             folder.type = "CalendarFolder";
1235         } else if ("IPF.Task".equals(folderClass)) {
1236             folder.type = "TasksFolder";
1237         } else {
1238             folder.put("FolderClass", folderClass);
1239             folder.type = "Folder";
1240         }
1241         folder.put("DisplayName", decodeFolderName(path.folderName));
1242 
1243         CreateFolderMethod createFolderMethod = new CreateFolderMethod(getFolderId(path.parentPath), folder);
1244         executeMethod(createFolderMethod);
1245         return HttpStatus.SC_CREATED;
1246     }
1247 
1248     /**
1249      * @inheritDoc
1250      */
1251     @Override
1252     public int updateFolder(String folderPath, Map<String, String> properties) throws IOException {
1253         ArrayList<FieldUpdate> updates = new ArrayList<>();
1254         for (Map.Entry<String, String> entry : properties.entrySet()) {
1255             updates.add(new FieldUpdate(Field.get(entry.getKey()), entry.getValue()));
1256         }
1257         UpdateFolderMethod updateFolderMethod = new UpdateFolderMethod(internalGetFolder(folderPath).folderId, updates);
1258 
1259         executeMethod(updateFolderMethod);
1260         return HttpStatus.SC_CREATED;
1261     }
1262 
1263     /**
1264      * @inheritDoc
1265      */
1266     @Override
1267     public void deleteFolder(String folderPath) throws IOException {
1268         FolderId folderId = getFolderIdIfExists(folderPath);
1269         if (folderId != null) {
1270             DeleteFolderMethod deleteFolderMethod = new DeleteFolderMethod(folderId);
1271             executeMethod(deleteFolderMethod);
1272         } else {
1273             LOGGER.debug("Folder " + folderPath + " not found");
1274         }
1275     }
1276 
1277     /**
1278      * @inheritDoc
1279      */
1280     @Override
1281     public void moveMessage(ExchangeSession.Message message, String targetFolder) throws IOException {
1282         MoveItemMethod moveItemMethod = new MoveItemMethod(((EwsExchangeSession.Message) message).itemId, getFolderId(targetFolder));
1283         executeMethod(moveItemMethod);
1284     }
1285 
1286     /**
1287      * @inheritDoc
1288      */
1289     @Override
1290     public void moveMessages(List<ExchangeSession.Message> messages, String targetFolder) throws IOException {
1291         ArrayList<ItemId> itemIds = new ArrayList<>();
1292         for (ExchangeSession.Message message : messages) {
1293             itemIds.add(((EwsExchangeSession.Message) message).itemId);
1294         }
1295 
1296         MoveItemMethod moveItemMethod = new MoveItemMethod(itemIds, getFolderId(targetFolder));
1297         executeMethod(moveItemMethod);
1298     }
1299 
1300     /**
1301      * @inheritDoc
1302      */
1303     @Override
1304     public void copyMessage(ExchangeSession.Message message, String targetFolder) throws IOException {
1305         CopyItemMethod copyItemMethod = new CopyItemMethod(((EwsExchangeSession.Message) message).itemId, getFolderId(targetFolder));
1306         executeMethod(copyItemMethod);
1307     }
1308 
1309     /**
1310      * @inheritDoc
1311      */
1312     @Override
1313     public void copyMessages(List<ExchangeSession.Message> messages, String targetFolder) throws IOException {
1314         ArrayList<ItemId> itemIds = new ArrayList<>();
1315         for (ExchangeSession.Message message : messages) {
1316             itemIds.add(((EwsExchangeSession.Message) message).itemId);
1317         }
1318 
1319         CopyItemMethod copyItemMethod = new CopyItemMethod(itemIds, getFolderId(targetFolder));
1320         executeMethod(copyItemMethod);
1321     }
1322 
1323     /**
1324      * @inheritDoc
1325      */
1326     @Override
1327     public void moveFolder(String folderPath, String targetFolderPath) throws IOException {
1328         FolderPath path = new FolderPath(folderPath);
1329         FolderPath targetPath = new FolderPath(targetFolderPath);
1330         FolderId folderId = getFolderId(folderPath);
1331         FolderId toFolderId = getFolderId(targetPath.parentPath);
1332         toFolderId.changeKey = null;
1333         // move folder
1334         if (!path.parentPath.equals(targetPath.parentPath)) {
1335             MoveFolderMethod moveFolderMethod = new MoveFolderMethod(folderId, toFolderId);
1336             executeMethod(moveFolderMethod);
1337         }
1338         // rename folder
1339         if (!path.folderName.equals(targetPath.folderName)) {
1340             ArrayList<FieldUpdate> updates = new ArrayList<>();
1341             updates.add(new FieldUpdate(Field.get("folderDisplayName"), targetPath.folderName));
1342             UpdateFolderMethod updateFolderMethod = new UpdateFolderMethod(folderId, updates);
1343             executeMethod(updateFolderMethod);
1344         }
1345     }
1346 
1347     @Override
1348     public void moveItem(String sourcePath, String targetPath) throws IOException {
1349         FolderPath sourceFolderPath = new FolderPath(sourcePath);
1350         Item item = getItem(sourceFolderPath.parentPath, sourceFolderPath.folderName);
1351         FolderPath targetFolderPath = new FolderPath(targetPath);
1352         FolderId toFolderId = getFolderId(targetFolderPath.parentPath);
1353         MoveItemMethod moveItemMethod = new MoveItemMethod(((Event) item).itemId, toFolderId);
1354         executeMethod(moveItemMethod);
1355     }
1356 
1357     /**
1358      * @inheritDoc
1359      */
1360     @Override
1361     protected void moveToTrash(ExchangeSession.Message message) throws IOException {
1362         MoveItemMethod moveItemMethod = new MoveItemMethod(((EwsExchangeSession.Message) message).itemId, getFolderId(TRASH));
1363         executeMethod(moveItemMethod);
1364     }
1365 
1366     protected class Contact extends ExchangeSession.Contact {
1367         // item id
1368         ItemId itemId;
1369 
1370         protected Contact(EWSMethod.Item response) throws DavMailException {
1371             itemId = new ItemId(response);
1372 
1373             permanentUrl = response.get(Field.get("permanenturl").getResponseName());
1374             etag = response.get(Field.get("etag").getResponseName());
1375             displayName = response.get(Field.get("displayname").getResponseName());
1376             // drop urlcompname (client provided item name) for contacts, prefer more reliable id
1377             itemName = StringUtil.base64ToUrl(itemId.id) + ".EML";
1378             for (String attributeName : CONTACT_ATTRIBUTES) {
1379                 String value = response.get(Field.get(attributeName).getResponseName());
1380                 if (value != null && !value.isEmpty()) {
1381                     if ("bday".equals(attributeName) || "anniversary".equals(attributeName) || "lastmodified".equals(attributeName) || "datereceived".equals(attributeName)) {
1382                         value = convertDateFromExchange(value);
1383                     }
1384                     put(attributeName, value);
1385                 }
1386             }
1387 
1388             if (response.getMembers() != null) {
1389                 for (String member : response.getMembers()) {
1390                     addMember(member);
1391                 }
1392             }
1393         }
1394 
1395         protected Contact(String folderPath, String itemName, Map<String, String> properties, String etag, String noneMatch) {
1396             super(folderPath, itemName, properties, etag, noneMatch);
1397         }
1398 
1399         /**
1400          * Empty constructor for GalFind
1401          */
1402         protected Contact() {
1403         }
1404 
1405         protected void buildFieldUpdates(List<FieldUpdate> updates, boolean create) {
1406             for (Map.Entry<String, String> entry : entrySet()) {
1407                 if ("photo".equals(entry.getKey())) {
1408                     updates.add(Field.createFieldUpdate("haspicture", "true"));
1409                 } else if (!entry.getKey().startsWith("email") && !entry.getKey().startsWith("smtpemail")
1410                         && !"fileas".equals(entry.getKey())) {
1411                     updates.add(Field.createFieldUpdate(entry.getKey(), entry.getValue()));
1412                 }
1413             }
1414             if (create && get("fileas") != null) {
1415                 updates.add(Field.createFieldUpdate("fileas", get("fileas")));
1416             }
1417             // handle email addresses
1418             IndexedFieldUpdate emailFieldUpdate = null;
1419             for (Map.Entry<String, String> entry : entrySet()) {
1420                 if (entry.getKey().startsWith("smtpemail")) {
1421                     if (emailFieldUpdate == null) {
1422                         emailFieldUpdate = new IndexedFieldUpdate("EmailAddresses");
1423                     }
1424                     emailFieldUpdate.addFieldValue(Field.createFieldUpdate(entry.getKey(), entry.getValue()));
1425                 }
1426             }
1427             if (emailFieldUpdate != null) {
1428                 updates.add(emailFieldUpdate);
1429             }
1430             // handle list members
1431             MultiValuedFieldUpdate memberFieldUpdate = null;
1432             if (distributionListMembers != null) {
1433                 for (String member : distributionListMembers) {
1434                     if (memberFieldUpdate == null) {
1435                         memberFieldUpdate = new MultiValuedFieldUpdate(Field.get("members"));
1436                     }
1437                     memberFieldUpdate.addValue(member);
1438                 }
1439             }
1440             if (memberFieldUpdate != null) {
1441                 updates.add(memberFieldUpdate);
1442             }
1443         }
1444 
1445 
1446         /**
1447          * Create or update contact
1448          *
1449          * @return action result
1450          * @throws IOException on error
1451          */
1452         @Override
1453         public ItemResult createOrUpdate() throws IOException {
1454             String photo = get("photo");
1455 
1456             ItemResult itemResult = new ItemResult();
1457             EWSMethod createOrUpdateItemMethod;
1458 
1459             // first try to load existing event
1460             String currentEtag = null;
1461             ItemId currentItemId = null;
1462             FileAttachment currentFileAttachment = null;
1463             EWSMethod.Item currentItem = getEwsItem(folderPath, itemName, ITEM_PROPERTIES);
1464             if (currentItem != null) {
1465                 currentItemId = new ItemId(currentItem);
1466                 currentEtag = currentItem.get(Field.get("etag").getResponseName());
1467 
1468                 // load current picture
1469                 GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, currentItemId, false);
1470                 getItemMethod.addAdditionalProperty(Field.get("attachments"));
1471                 executeMethod(getItemMethod);
1472                 EWSMethod.Item item = getItemMethod.getResponseItem();
1473                 if (item != null) {
1474                     currentFileAttachment = item.getAttachmentByName("ContactPicture.jpg");
1475                 }
1476             }
1477             if ("*".equals(noneMatch)) {
1478                 // create requested
1479                 //noinspection VariableNotUsedInsideIf
1480                 if (currentItemId != null) {
1481                     itemResult.status = HttpStatus.SC_PRECONDITION_FAILED;
1482                     return itemResult;
1483                 }
1484             } else if (etag != null) {
1485                 // update requested
1486                 if (currentItemId == null || !etag.equals(currentEtag)) {
1487                     itemResult.status = HttpStatus.SC_PRECONDITION_FAILED;
1488                     return itemResult;
1489                 }
1490             }
1491 
1492             List<FieldUpdate> fieldUpdates = new ArrayList<>();
1493             if (currentItemId != null) {
1494                 buildFieldUpdates(fieldUpdates, false);
1495                 // update
1496                 createOrUpdateItemMethod = new UpdateItemMethod(MessageDisposition.SaveOnly,
1497                         ConflictResolution.AlwaysOverwrite,
1498                         SendMeetingInvitationsOrCancellations.SendToNone,
1499                         currentItemId, fieldUpdates);
1500             } else {
1501                 // create
1502                 EWSMethod.Item newItem = new EWSMethod.Item();
1503                 if ("IPM.DistList".equals(get("outlookmessageclass"))) {
1504                     newItem.type = "DistributionList";
1505                 } else {
1506                     newItem.type = "Contact";
1507                 }
1508                 // force urlcompname on creation
1509                 fieldUpdates.add(Field.createFieldUpdate("urlcompname", convertItemNameToEML(itemName)));
1510                 buildFieldUpdates(fieldUpdates, true);
1511                 newItem.setFieldUpdates(fieldUpdates);
1512                 createOrUpdateItemMethod = new CreateItemMethod(MessageDisposition.SaveOnly, getFolderId(folderPath), newItem);
1513             }
1514             executeMethod(createOrUpdateItemMethod);
1515 
1516             itemResult.status = createOrUpdateItemMethod.getStatusCode();
1517             if (itemResult.status == HttpURLConnection.HTTP_OK) {
1518                 //noinspection VariableNotUsedInsideIf
1519                 if (currentItemId == null) {
1520                     itemResult.status = HttpStatus.SC_CREATED;
1521                     LOGGER.debug("Created contact " + getHref());
1522                 } else {
1523                     LOGGER.debug("Updated contact " + getHref());
1524                 }
1525             } else {
1526                 return itemResult;
1527             }
1528 
1529             ItemId newItemId = new ItemId(createOrUpdateItemMethod.getResponseItem());
1530 
1531             // disable contact picture handling on Exchange 2007
1532             if (!"Exchange2007_SP1".equals(serverVersion)
1533                     // prefer the user provided photo
1534                     && getADPhoto(get("smtpemail1")) == null) {
1535                 // first delete current picture
1536                 if (currentFileAttachment != null) {
1537                     DeleteAttachmentMethod deleteAttachmentMethod = new DeleteAttachmentMethod(currentFileAttachment.attachmentId);
1538                     executeMethod(deleteAttachmentMethod);
1539                 }
1540 
1541                 if (photo != null) {
1542                     // convert image to jpeg
1543                     byte[] resizedImageBytes = IOUtil.resizeImage(IOUtil.decodeBase64(photo), 90);
1544 
1545                     FileAttachment attachment = new FileAttachment("ContactPicture.jpg", "image/jpeg", IOUtil.encodeBase64AsString(resizedImageBytes));
1546                     attachment.setIsContactPhoto(true);
1547 
1548                     // update photo attachment
1549                     CreateAttachmentMethod createAttachmentMethod = new CreateAttachmentMethod(newItemId, attachment);
1550                     executeMethod(createAttachmentMethod);
1551                 }
1552             }
1553 
1554             GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, newItemId, false);
1555             getItemMethod.addAdditionalProperty(Field.get("etag"));
1556             executeMethod(getItemMethod);
1557             itemResult.etag = getItemMethod.getResponseItem().get(Field.get("etag").getResponseName());
1558 
1559             return itemResult;
1560         }
1561     }
1562 
1563     protected class Event extends ExchangeSession.Event {
1564         // item id
1565         ItemId itemId;
1566         String type;
1567         boolean isException;
1568 
1569         protected Event(String folderPath, EWSMethod.Item response) {
1570             this.folderPath = folderPath;
1571             itemId = new ItemId(response);
1572 
1573             type = response.type;
1574 
1575             permanentUrl = response.get(Field.get("permanenturl").getResponseName());
1576             etag = response.get(Field.get("etag").getResponseName());
1577             displayName = response.get(Field.get("displayname").getResponseName());
1578             subject = response.get(Field.get("subject").getResponseName());
1579             // ignore urlcompname and use item id
1580             itemName = StringUtil.base64ToUrl(itemId.id) + ".EML";
1581             String instancetype = response.get(Field.get("instancetype").getResponseName());
1582             isException = "3".equals(instancetype);
1583         }
1584 
1585         protected Event(String folderPath, String itemName, String contentClass, String itemBody, String etag, String noneMatch) throws IOException {
1586             super(folderPath, itemName, contentClass, itemBody, etag, noneMatch);
1587         }
1588 
1589         /**
1590          * Handle excluded dates (deleted occurrences).
1591          *
1592          * @param currentItemId the current item id to iterate over occurrences
1593          * @param vCalendar     vCalendar object
1594          * @throws DavMailException on error
1595          */
1596         protected void handleExcludedDates(ItemId currentItemId, VCalendar vCalendar) throws DavMailException {
1597             List<VProperty> excludedDates = vCalendar.getFirstVeventProperties("EXDATE");
1598             if (excludedDates != null) {
1599                 for (VProperty property : excludedDates) {
1600                     List<String> values = property.getValues();
1601                     for (String value : values) {
1602                         String convertedValue;
1603                         try {
1604                             convertedValue = vCalendar.convertCalendarDateToExchangeZulu(value, property.getParamValue("TZID"));
1605                         } catch (IOException e) {
1606                             throw new DavMailException("EXCEPTION_INVALID_DATE", value);
1607                         }
1608                         LOGGER.debug("Looking for occurrence " + convertedValue);
1609 
1610                         int instanceIndex = 0;
1611 
1612                         // let's try to find occurrence
1613                         while (true) {
1614                             instanceIndex++;
1615                             try {
1616                                 GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY,
1617                                         new OccurrenceItemId(currentItemId.id, instanceIndex)
1618                                         , false);
1619                                 getItemMethod.addAdditionalProperty(Field.get("originalstart"));
1620                                 executeMethod(getItemMethod);
1621                                 if (getItemMethod.getResponseItem() != null) {
1622                                     String itemOriginalStart = getItemMethod.getResponseItem().get(Field.get("originalstart").getResponseName());
1623                                         LOGGER.debug("Occurrence " + instanceIndex + " itemOriginalStart " + itemOriginalStart + " looking for " + convertedValue);
1624                                     if (convertedValue.equals(itemOriginalStart)) {
1625                                         // found item, delete it
1626                                         DeleteItemMethod deleteItemMethod = new DeleteItemMethod(new ItemId(getItemMethod.getResponseItem()),
1627                                                 DeleteType.HardDelete, SendMeetingCancellations.SendToAllAndSaveCopy);
1628                                         executeMethod(deleteItemMethod);
1629                                         break;
1630                                     } else if (convertedValue.compareTo(itemOriginalStart) < 0) {
1631                                         // current item is after searched item => probably already deleted
1632                                         break;
1633                                     }
1634                                 }
1635                             } catch (IOException e) {
1636                                 LOGGER.warn("Error looking for occurrence " + convertedValue + ": " + e.getMessage());
1637                                 // after end of recurrence
1638                                 break;
1639                             }
1640                         }
1641                     }
1642                 }
1643             }
1644 
1645 
1646         }
1647 
1648         /**
1649          * Handle modified occurrences.
1650          *
1651          * @param currentItemId the current item id to iterate over occurrences
1652          * @param vCalendar     vCalendar object
1653          * @throws DavMailException on error
1654          */
1655         protected void handleModifiedOccurrences(ItemId currentItemId, VCalendar vCalendar, SendMeetingInvitationsOrCancellations sendMeetingInvitationsOrCancellations) throws DavMailException {
1656             for (VObject modifiedOccurrence : vCalendar.getModifiedOccurrences()) {
1657                 VProperty originalDateProperty = modifiedOccurrence.getProperty("RECURRENCE-ID");
1658                 String convertedValue;
1659                 try {
1660                     convertedValue = vCalendar.convertCalendarDateToExchangeZulu(originalDateProperty.getValue(), originalDateProperty.getParamValue("TZID"));
1661                 } catch (IOException e) {
1662                     throw new DavMailException("EXCEPTION_INVALID_DATE", originalDateProperty.getValue());
1663                 }
1664                 LOGGER.debug("Looking for occurrence " + convertedValue);
1665                 int instanceIndex = 0;
1666 
1667                 // let's try to find occurrence
1668                 while (true) {
1669                     instanceIndex++;
1670                     try {
1671                         GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY,
1672                                 new OccurrenceItemId(currentItemId.id, instanceIndex)
1673                                 , false);
1674                         getItemMethod.addAdditionalProperty(Field.get("originalstart"));
1675                         executeMethod(getItemMethod);
1676                         if (getItemMethod.getResponseItem() != null) {
1677                             String itemOriginalStart = getItemMethod.getResponseItem().get(Field.get("originalstart").getResponseName());
1678                             if (convertedValue.equals(itemOriginalStart)) {
1679                                 // found item, update it
1680                                 UpdateItemMethod updateItemMethod = new UpdateItemMethod(MessageDisposition.SaveOnly,
1681                                         ConflictResolution.AutoResolve,
1682                                         sendMeetingInvitationsOrCancellations,
1683                                         new ItemId(getItemMethod.getResponseItem()), buildFieldUpdates(vCalendar, modifiedOccurrence, false));
1684                                 // force context Timezone on Exchange 2010 and 2013
1685                                 if (serverVersion != null && serverVersion.startsWith("Exchange201")) {
1686                                     updateItemMethod.setTimezoneContext(EwsExchangeSession.this.getVTimezone().getPropertyValue("TZID"));
1687                                 }
1688                                 executeMethod(updateItemMethod);
1689 
1690                                 break;
1691                             } else if (convertedValue.compareTo(itemOriginalStart) < 0) {
1692                                 // current item is after searched item => probably already deleted
1693                                 break;
1694                             }
1695                         }
1696                     } catch (IOException e) {
1697                         LOGGER.warn("Error looking for occurrence " + convertedValue + ": " + e.getMessage());
1698                         // after end of recurrence
1699                         break;
1700                     }
1701                 }
1702             }
1703         }
1704 
1705         protected List<FieldUpdate> buildFieldUpdates(VCalendar vCalendar, VObject vEvent, boolean isMozDismiss) throws DavMailException {
1706             List<FieldUpdate> updates = new ArrayList<>();
1707 
1708             if (isMozDismiss || "1".equals(vEvent.getPropertyValue("X-MOZ-FAKED-MASTER"))) {
1709                 String xMozLastack = vCalendar.getFirstVeventPropertyValue("X-MOZ-LASTACK");
1710                 if (xMozLastack != null) {
1711                     updates.add(Field.createFieldUpdate("xmozlastack", xMozLastack));
1712                 }
1713                 String xMozSnoozeTime = vCalendar.getFirstVeventPropertyValue("X-MOZ-SNOOZE-TIME");
1714                 if (xMozSnoozeTime != null) {
1715                     updates.add(Field.createFieldUpdate("xmozsnoozetime", xMozSnoozeTime));
1716                 }
1717                 return updates;
1718             }
1719 
1720             // if we are not organizer, update only reminder info
1721             if (!vCalendar.isMeeting() || vCalendar.isMeetingOrganizer()) {
1722                 // TODO: update all event fields and handle other occurrences
1723                 updates.add(Field.createFieldUpdate("dtstart", convertCalendarDateToExchange(vEvent.getPropertyValue("DTSTART"))));
1724                 updates.add(Field.createFieldUpdate("dtend", convertCalendarDateToExchange(vEvent.getPropertyValue("DTEND"))));
1725                 if ("Exchange2007_SP1".equals(serverVersion)) {
1726                     String meetingtimezone = resolveCalendarTimezone(vEvent, "DTSTART");
1727                     if (meetingtimezone != null) {
1728                         updates.add(Field.createFieldUpdate("meetingtimezone", meetingtimezone));
1729                     }
1730                 } else {
1731                     String starttimezone = resolveCalendarTimezone(vEvent, "DTSTART");
1732                     String endtimezone = starttimezone;
1733                     if (vEvent.getProperty("DTEND") != null) {
1734                         endtimezone = resolveCalendarTimezone(vEvent, "DTEND");
1735                     }
1736                     if (starttimezone != null) {
1737                         updates.add(Field.createFieldUpdate("starttimezone", starttimezone));
1738                     }
1739                     if (endtimezone != null) {
1740                         updates.add(Field.createFieldUpdate("endtimezone", endtimezone));
1741                     }
1742                 }
1743 
1744                 String status = statusToBusyStatusMap.get(vEvent.getPropertyValue("STATUS"));
1745                 if (status != null) {
1746                     updates.add(Field.createFieldUpdate("busystatus", status));
1747                 }
1748 
1749                 updates.add(Field.createFieldUpdate("isalldayevent", Boolean.toString(vCalendar.isCdoAllDay())));
1750 
1751                 String eventClass = vEvent.getPropertyValue("CLASS");
1752                 if ("PRIVATE".equals(eventClass)) {
1753                     eventClass = "Private";
1754                 } else if ("CONFIDENTIAL".equals(eventClass)) {
1755                     eventClass = "Confidential";
1756                 } else {
1757                     // PUBLIC
1758                     eventClass = "Normal";
1759                 }
1760                 updates.add(Field.createFieldUpdate("itemsensitivity", eventClass));
1761 
1762                 updates.add(Field.createFieldUpdate("description", vEvent.getPropertyValue("DESCRIPTION")));
1763                 updates.add(Field.createFieldUpdate("subject", vEvent.getPropertyValue("SUMMARY")));
1764                 updates.add(Field.createFieldUpdate("location", vEvent.getPropertyValue("LOCATION")));
1765                 // Collect categories on multiple lines
1766                 List<VProperty> categories = vEvent.getProperties("CATEGORIES");
1767                 if (categories != null) {
1768                     HashSet<String> categoryValues = new HashSet<>();
1769                     for (VProperty category : categories) {
1770                         categoryValues.add(category.getValue());
1771                     }
1772                     updates.add(Field.createFieldUpdate("keywords", StringUtil.join(categoryValues, ",")));
1773                 }
1774 
1775                 convertRruleToRecurrenceFieldUpdate(vEvent, updates);
1776 
1777                 MultiValuedFieldUpdate requiredAttendees = new MultiValuedFieldUpdate(Field.get("requiredattendees"));
1778                 MultiValuedFieldUpdate optionalAttendees = new MultiValuedFieldUpdate(Field.get("optionalattendees"));
1779                 MultiValuedFieldUpdate resourceAttendees = new MultiValuedFieldUpdate(Field.get("resources"));
1780 
1781                 updates.add(requiredAttendees);
1782                 updates.add(optionalAttendees);
1783                 updates.add(resourceAttendees);
1784 
1785                 List<VProperty> attendees = vEvent.getProperties("ATTENDEE");
1786                 if (attendees != null) {
1787                     for (VProperty property : attendees) {
1788                         String attendeeEmail = vCalendar.getEmailValue(property);
1789                         if (attendeeEmail != null && attendeeEmail.indexOf('@') >= 0) {
1790                             if (!vCalendar.getCalendarEmail().equals(attendeeEmail)) {
1791                                 String cutype = property.getParamValue("CUTYPE");
1792                                 if ("ROOM".equals(cutype) || "RESOURCE".equals(cutype)) {
1793                                     resourceAttendees.addValue(attendeeEmail);
1794                                 } else {
1795                                     String attendeeRole = property.getParamValue("ROLE");
1796                                     if ("OPT-PARTICIPANT".equals(attendeeRole) || "NON-PARTICIPANT".equals(attendeeRole)) {
1797                                         optionalAttendees.addValue(attendeeEmail);
1798                                     } else {
1799                                         // default to required per RFC 5545 section 3.2.16
1800                                         requiredAttendees.addValue(attendeeEmail);
1801                                     }
1802                                 }
1803                             }
1804                         }
1805                     }
1806                 }
1807 
1808                 // store mozilla invitations option
1809                 String xMozSendInvitations = vCalendar.getFirstVeventPropertyValue("X-MOZ-SEND-INVITATIONS");
1810                 if (xMozSendInvitations != null) {
1811                     updates.add(Field.createFieldUpdate("xmozsendinvitations", xMozSendInvitations));
1812                 }
1813             }
1814 
1815             // TODO: check with recurrence
1816             updates.add(Field.createFieldUpdate("reminderset", String.valueOf(vCalendar.hasVAlarm())));
1817             if (vCalendar.hasVAlarm()) {
1818                 updates.add(Field.createFieldUpdate("reminderminutesbeforestart", vCalendar.getReminderMinutesBeforeStart()));
1819             }
1820 
1821             // handle mozilla alarm
1822             String xMozLastack = vCalendar.getFirstVeventPropertyValue("X-MOZ-LASTACK");
1823             if (xMozLastack != null) {
1824                 updates.add(Field.createFieldUpdate("xmozlastack", xMozLastack));
1825             }
1826             String xMozSnoozeTime = vCalendar.getFirstVeventPropertyValue("X-MOZ-SNOOZE-TIME");
1827             if (xMozSnoozeTime != null) {
1828                 updates.add(Field.createFieldUpdate("xmozsnoozetime", xMozSnoozeTime));
1829             }
1830 
1831             return updates;
1832         }
1833 
1834         private void convertRruleToRecurrenceFieldUpdate(VObject vEvent, List<FieldUpdate> updates) throws DavMailException {
1835             VProperty rrule = vEvent.getProperty("RRULE");
1836             if (rrule != null) {
1837                 RecurrenceFieldUpdate recurrenceFieldUpdate = new RecurrenceFieldUpdate();
1838                 String freq = null;
1839                 String byDay = null;
1840                 String byMonthDay = null;
1841                 String byMonth = null;
1842                 List<String> rruleValues = rrule.getValues();
1843                 for (String rruleValue : rruleValues) {
1844                     int index = rruleValue.indexOf("=");
1845                     if (index >= 0) {
1846                         String key = rruleValue.substring(0, index);
1847                         String value = rruleValue.substring(index + 1);
1848                         switch (key) {
1849                             case "FREQ":
1850                                 freq = value;
1851                                 break;
1852                             case "UNTIL":
1853                                 String untilValue = value.endsWith("Z") ? value.substring(0, value.length() - 1) : value;
1854                                 recurrenceFieldUpdate.setEndDate(parseDateFromExchange(convertCalendarDateToExchange(untilValue) + "Z"));
1855                                 break;
1856                             case "COUNT":
1857                                 recurrenceFieldUpdate.setCount(value);
1858                                 break;
1859                             case "BYDAY":
1860                                 byDay = value;
1861                                 break;
1862                             case "BYMONTHDAY":
1863                                 byMonthDay = value;
1864                                 break;
1865                             case "BYMONTH":
1866                                 byMonth = value;
1867                                 break;
1868                             case "INTERVAL":
1869                                 recurrenceFieldUpdate.setRecurrenceInterval(value);
1870                                 break;
1871                             case "WKST":
1872                                 String wkstDay = RecurrenceFieldUpdate.calDayToDayOfWeek.get(value);
1873                                 if (wkstDay != null) {
1874                                     recurrenceFieldUpdate.setFirstDayOfWeek(wkstDay);
1875                                 }
1876                                 break;
1877                         }
1878                     }
1879                 }
1880                 // determine if BYDAY contains a positional prefix (relative pattern, e.g. "2MO", "-1FR")
1881                 boolean isRelative = byDay != null && Character.isDigit(byDay.charAt(0)) ||
1882                         byDay != null && byDay.charAt(0) == '-';
1883                 if ("MONTHLY".equals(freq)) {
1884                     if (isRelative) {
1885                         recurrenceFieldUpdate.setRecurrencePattern(RecurrenceFieldUpdate.RecurrencePattern.RelativeMonthlyRecurrence);
1886                         recurrenceFieldUpdate.setDayOfWeekIndexFromByDay(byDay);
1887                     } else {
1888                         recurrenceFieldUpdate.setRecurrencePattern(RecurrenceFieldUpdate.RecurrencePattern.AbsoluteMonthlyRecurrence);
1889                         if (byMonthDay != null) recurrenceFieldUpdate.setDayOfMonth(byMonthDay);
1890                     }
1891                 } else if ("YEARLY".equals(freq)) {
1892                     if (isRelative) {
1893                         recurrenceFieldUpdate.setRecurrencePattern(RecurrenceFieldUpdate.RecurrencePattern.RelativeYearlyRecurrence);
1894                         recurrenceFieldUpdate.setDayOfWeekIndexFromByDay(byDay);
1895                     } else {
1896                         recurrenceFieldUpdate.setRecurrencePattern(RecurrenceFieldUpdate.RecurrencePattern.AbsoluteYearlyRecurrence);
1897                         if (byMonthDay != null) recurrenceFieldUpdate.setDayOfMonth(byMonthDay);
1898                     }
1899                     if (byMonth != null) recurrenceFieldUpdate.setMonthFromByMonth(byMonth);
1900                 } else if (freq != null) {
1901                     recurrenceFieldUpdate.setRecurrencePattern(freq);
1902                 }
1903                 if (byDay != null && (isRelative || "WEEKLY".equals(freq) || "DAILY".equals(freq))) {
1904                     recurrenceFieldUpdate.setByDay(byDay.split(","));
1905                 }
1906                 recurrenceFieldUpdate.setStartDate(parseDateFromExchange(convertCalendarDateToExchange(vEvent.getPropertyValue("DTSTART")) + "Z"));
1907                 updates.add(recurrenceFieldUpdate);
1908             }
1909         }
1910 
1911         @Override
1912         public ItemResult createOrUpdate() throws IOException {
1913             if (vCalendar.isTodo() && isMainCalendar(folderPath)) {
1914                 // task item, move to tasks folder
1915                 folderPath = TASKS;
1916             }
1917 
1918             ItemResult itemResult = new ItemResult();
1919             EWSMethod createOrUpdateItemMethod = null;
1920 
1921             // first try to load existing event
1922             String currentEtag = null;
1923             ItemId currentItemId = null;
1924             boolean isMeetingResponse = false;
1925             boolean isMozSendInvitations = true;
1926             boolean isMozDismiss = false;
1927 
1928             HashMap<ItemId, String> responseStatusUpdates = null;
1929 
1930             HashSet<String> itemRequestProperties = CALENDAR_ITEM_REQUEST_PROPERTIES;
1931             if (vCalendar.isTodo()) {
1932                 itemRequestProperties = EVENT_REQUEST_PROPERTIES;
1933             }
1934 
1935             boolean isOrganizer = vCalendar.isOrganizer();
1936             if (isOrganizer) {
1937                 LOGGER.debug(vCalendar.getCalendarEmail() +" is meeting organizer");
1938             }
1939 
1940             EWSMethod.Item currentItem = getEwsItem(folderPath, itemName, itemRequestProperties);
1941             if (currentItem == null) {
1942                 boolean isMeeting = vCalendar.isMeeting();
1943                 if (isMeeting && !isOrganizer) {
1944                     throw new IOException("Detected meeting response, but event does not exist, aborting");
1945                 }
1946             } else {
1947                 currentItemId = new ItemId(currentItem);
1948                 currentEtag = currentItem.get(Field.get("etag").getResponseName());
1949 
1950                 responseStatusUpdates = buildResponseStatusUpdates(currentItem, vCalendar);
1951 
1952                 isMeetingResponse = vCalendar.isMeeting() && !isOrganizer && !responseStatusUpdates.isEmpty();
1953 
1954 
1955                 // Check mozilla last ack and snooze
1956                 String newmozlastack = vCalendar.getFirstVeventPropertyValue("X-MOZ-LASTACK");
1957                 String currentmozlastack = currentItem.get(Field.get("xmozlastack").getResponseName());
1958                 boolean ismozack = newmozlastack != null && !newmozlastack.equals(currentmozlastack);
1959 
1960                 String newmozsnoozetime = vCalendar.getFirstVeventPropertyValue("X-MOZ-SNOOZE-TIME");
1961                 String currentmozsnoozetime = currentItem.get(Field.get("xmozsnoozetime").getResponseName());
1962                 boolean ismozsnooze = newmozsnoozetime != null && !newmozsnoozetime.equals(currentmozsnoozetime);
1963 
1964                 isMozSendInvitations = (newmozlastack == null && newmozsnoozetime == null) // not thunderbird
1965                         || !(ismozack || ismozsnooze);
1966                 isMozDismiss = ismozack || ismozsnooze;
1967 
1968                 LOGGER.debug("Existing item found with etag: " + currentEtag + " client etag: " + etag + " id: " + currentItemId.id);
1969             }
1970             if (isMeetingResponse) {
1971                 LOGGER.debug("Ignore etag check, meeting response");
1972             } else if ("*".equals(noneMatch) && !Settings.getBooleanProperty("davmail.ignoreNoneMatchStar", true)) {
1973                 // create requested
1974                 //noinspection VariableNotUsedInsideIf
1975                 if (currentItemId != null) {
1976                     itemResult.status = HttpStatus.SC_PRECONDITION_FAILED;
1977                     return itemResult;
1978                 }
1979             } else if (etag != null) {
1980                 // update requested
1981                 if (currentItemId == null || !etag.equals(currentEtag)) {
1982                     itemResult.status = HttpStatus.SC_PRECONDITION_FAILED;
1983                     return itemResult;
1984                 }
1985             }
1986 
1987             // by default no notifications
1988             SendMeetingInvitationsOrCancellations sendMeetingInvitationsOrCancellations = SendMeetingInvitationsOrCancellations.SendToNone;
1989 
1990             if (vCalendar.isTodo()) {
1991                 // create or update task method
1992                 EWSMethod.Item newItem = new EWSMethod.Item();
1993                 newItem.type = "Task";
1994                 List<FieldUpdate> updates = new ArrayList<>();
1995                 updates.add(Field.createFieldUpdate("importance", convertPriorityToExchange(vCalendar.getFirstVeventPropertyValue("PRIORITY"))));
1996                 updates.add(Field.createFieldUpdate("calendaruid", vCalendar.getFirstVeventPropertyValue("UID")));
1997                 // force urlcompname
1998                 updates.add(Field.createFieldUpdate("urlcompname", convertItemNameToEML(itemName)));
1999                 updates.add(Field.createFieldUpdate("subject", vCalendar.getFirstVeventPropertyValue("SUMMARY")));
2000                 updates.add(Field.createFieldUpdate("description", vCalendar.getFirstVeventPropertyValue("DESCRIPTION")));
2001 
2002                 // handle multiple keywords/categories
2003                 List<VProperty> categories = vCalendar.getFirstVeventProperties("CATEGORIES");
2004                 if (categories != null) {
2005                     HashSet<String> categoryValues = new HashSet<>();
2006                     for (VProperty category : categories) {
2007                         categoryValues.add(category.getValue());
2008                     }
2009                     updates.add(Field.createFieldUpdate("keywords", StringUtil.join(categoryValues, ",")));
2010                 }
2011 
2012                 updates.add(Field.createFieldUpdate("startdate", convertTaskDateToZulu(vCalendar.getFirstVeventPropertyValue("DTSTART"))));
2013                 updates.add(Field.createFieldUpdate("duedate", convertTaskDateToZulu(vCalendar.getFirstVeventPropertyValue("DUE"))));
2014                 updates.add(Field.createFieldUpdate("datecompleted", convertTaskDateToZulu(vCalendar.getFirstVeventPropertyValue("COMPLETED"))));
2015 
2016                 updates.add(Field.createFieldUpdate("commonstart", convertTaskDateToZulu(vCalendar.getFirstVeventPropertyValue("DTSTART"))));
2017                 updates.add(Field.createFieldUpdate("commonend", convertTaskDateToZulu(vCalendar.getFirstVeventPropertyValue("DUE"))));
2018 
2019                 String percentComplete = vCalendar.getFirstVeventPropertyValue("PERCENT-COMPLETE");
2020                 if (percentComplete == null) {
2021                     percentComplete = "0";
2022                 }
2023                 updates.add(Field.createFieldUpdate("percentcomplete", percentComplete));
2024                 String vTodoStatus = vCalendar.getFirstVeventPropertyValue("STATUS");
2025                 if (vTodoStatus == null) {
2026                     updates.add(Field.createFieldUpdate("taskstatus", "NotStarted"));
2027                 } else {
2028                     updates.add(Field.createFieldUpdate("taskstatus", vTodoToTaskStatusMap.get(vTodoStatus)));
2029                 }
2030 
2031                 //updates.add(Field.createFieldUpdate("iscomplete", "COMPLETED".equals(vTodoStatus)?"True":"False"));
2032 
2033                 if (currentItemId != null) {
2034                     // update
2035                     createOrUpdateItemMethod = new UpdateItemMethod(MessageDisposition.SaveOnly,
2036                             ConflictResolution.AutoResolve,
2037                             SendMeetingInvitationsOrCancellations.SendToNone,
2038                             currentItemId, updates);
2039                 } else {
2040                     newItem.setFieldUpdates(updates);
2041                     // create
2042                     createOrUpdateItemMethod = new CreateItemMethod(MessageDisposition.SaveOnly, SendMeetingInvitations.SendToNone, getFolderId(folderPath), newItem);
2043                 }
2044 
2045             } else {
2046 
2047                 // update existing item
2048                 if (currentItemId != null) {
2049                     if (isMeetingResponse) {
2050                         // meeting response with server managed notifications
2051                         SendMeetingInvitations sendMeetingInvitations = SendMeetingInvitations.SendToAllAndSaveCopy;
2052                         MessageDisposition messageDisposition = MessageDisposition.SendAndSaveCopy;
2053 
2054                         if (responseStatusUpdates.isEmpty()) {
2055                             throw new IOException("No response status updates found");
2056                         }
2057                         // assume a single meeting response
2058                         Map.Entry<ItemId, String> responseStatusUpdate = responseStatusUpdates.entrySet().iterator().next();
2059                         String attendeeStatus = responseStatusUpdate.getValue();
2060                         ItemId instanceItemId = responseStatusUpdate.getKey();
2061 
2062                         String body = null;
2063                         // This is a meeting response, let user edit notification message
2064                         if (Settings.getBooleanProperty("davmail.caldavEditNotifications")) {
2065                             String vEventSubject = vCalendar.getFirstVeventPropertyValue("SUMMARY");
2066                             if (vEventSubject == null) {
2067                                 vEventSubject = BundleMessage.format("MEETING_REQUEST");
2068                             }
2069 
2070                             String notificationSubject = (attendeeStatus != null) ? (BundleMessage.format(attendeeStatus) + vEventSubject) : subject;
2071 
2072                             NotificationDialog notificationDialog = new NotificationDialog(notificationSubject, "");
2073                             if (!notificationDialog.getSendNotification()) {
2074                                 LOGGER.debug("Notification canceled by user");
2075                                 sendMeetingInvitations = SendMeetingInvitations.SendToNone;
2076                                 messageDisposition = MessageDisposition.SaveOnly;
2077                             }
2078                             // get description from dialog
2079                             body = notificationDialog.getBody();
2080                         }
2081                         EWSMethod.Item item = new EWSMethod.Item();
2082 
2083                         item.type = partstatToResponseMap.get(attendeeStatus);
2084                         item.referenceItemId = new ItemId("ReferenceItemId", instanceItemId.id, instanceItemId.changeKey);
2085                         if (body != null && !body.isEmpty()) {
2086                             item.put("Body", body);
2087                         }
2088                         createOrUpdateItemMethod = new CreateItemMethod(messageDisposition,
2089                                 sendMeetingInvitations,
2090                                 getFolderId(SENT),
2091                                 item
2092                         );
2093 
2094                     } else {
2095                         // other changes with server side managed notifications
2096                         MessageDisposition messageDisposition = MessageDisposition.SaveOnly;
2097 
2098                         if (vCalendar.isMeeting() && vCalendar.isMeetingOrganizer() && isMozSendInvitations) {
2099                             messageDisposition = MessageDisposition.SendAndSaveCopy;
2100                             sendMeetingInvitationsOrCancellations = SendMeetingInvitationsOrCancellations.SendToAllAndSaveCopy;
2101                         }
2102                         createOrUpdateItemMethod = new UpdateItemMethod(messageDisposition,
2103                                 ConflictResolution.AutoResolve,
2104                                 sendMeetingInvitationsOrCancellations,
2105                                 currentItemId, buildFieldUpdates(vCalendar, vCalendar.getFirstVevent(), isMozDismiss));
2106 
2107                         // force context Timezone on Exchange 2010 and 2013
2108                         if (serverVersion != null && serverVersion.startsWith("Exchange201")) {
2109                             createOrUpdateItemMethod.setTimezoneContext(EwsExchangeSession.this.getVTimezone().getPropertyValue("TZID"));
2110                         }
2111                     }
2112                 }
2113 
2114                 if (createOrUpdateItemMethod == null) {
2115                     // create item from VCALENDAR content, set additional properties as workaround to Exchange handling issues
2116                     EWSMethod.Item newItem = new EWSMethod.Item();
2117                     newItem.type = "CalendarItem";
2118                     newItem.mimeContent = IOUtil.encodeBase64(vCalendar.toString());
2119                     ArrayList<FieldUpdate> updates = new ArrayList<>();
2120                     if (!vCalendar.hasVAlarm()) {
2121                         updates.add(Field.createFieldUpdate("reminderset", "false"));
2122                     }
2123                     //updates.add(Field.createFieldUpdate("outlookmessageclass", "IPM.Appointment"));
2124                     // force urlcompname
2125                     updates.add(Field.createFieldUpdate("urlcompname", convertItemNameToEML(itemName)));
2126                     if (vCalendar.isMeeting()) {
2127                         if (vCalendar.isMeetingOrganizer()) {
2128                             updates.add(Field.createFieldUpdate("apptstateflags", "1"));
2129                         } else {
2130                             updates.add(Field.createFieldUpdate("apptstateflags", "3"));
2131                         }
2132                     } else {
2133                         updates.add(Field.createFieldUpdate("apptstateflags", "0"));
2134                     }
2135                     // store mozilla invitations option
2136                     String xMozSendInvitations = vCalendar.getFirstVeventPropertyValue("X-MOZ-SEND-INVITATIONS");
2137                     if (xMozSendInvitations != null) {
2138                         updates.add(Field.createFieldUpdate("xmozsendinvitations", xMozSendInvitations));
2139                     }
2140                     // handle mozilla alarm
2141                     String xMozLastack = vCalendar.getFirstVeventPropertyValue("X-MOZ-LASTACK");
2142                     if (xMozLastack != null) {
2143                         updates.add(Field.createFieldUpdate("xmozlastack", xMozLastack));
2144                     }
2145                     String xMozSnoozeTime = vCalendar.getFirstVeventPropertyValue("X-MOZ-SNOOZE-TIME");
2146                     if (xMozSnoozeTime != null) {
2147                         updates.add(Field.createFieldUpdate("xmozsnoozetime", xMozSnoozeTime));
2148                     }
2149 
2150                     if (vCalendar.isMeeting() && "Exchange2007_SP1".equals(serverVersion)) {
2151                         // Exchange 2007 does not properly handle attendees
2152                         Set<String> requiredAttendees = new HashSet<>();
2153                         Set<String> optionalAttendees = new HashSet<>();
2154                         List<VProperty> attendeeProperties = vCalendar.getFirstVeventProperties("ATTENDEE");
2155                         if (attendeeProperties != null) {
2156                             for (VProperty property : attendeeProperties) {
2157                                 String attendeeEmail = vCalendar.getEmailValue(property);
2158                                 if (attendeeEmail != null && attendeeEmail.indexOf('@') >= 0) {
2159                                     InternetAddress internetAddress = new InternetAddress(attendeeEmail, property.getParamValue("CN"));
2160                                     String attendeeRole = property.getParamValue("ROLE");
2161                                     if ("OPT-PARTICIPANT".equals(attendeeRole) || "NON-PARTICIPANT".equals(attendeeRole)) {
2162                                         optionalAttendees.add(internetAddress.toString());
2163                                     } else {
2164                                         // default to required per RFC 5545 section 3.2.16
2165                                         requiredAttendees.add(internetAddress.toString());
2166                                     }
2167                                 }
2168                             }
2169                         }
2170                         // add organizer as FROM recipient
2171                         List<VProperty> organizerProperties = vCalendar.getFirstVeventProperties("ORGANIZER");
2172                         if (organizerProperties != null) {
2173                             VProperty property = organizerProperties.get(0);
2174                             String organizerEmail = vCalendar.getEmailValue(property);
2175                             if (organizerEmail != null && organizerEmail.indexOf('@') >= 0) {
2176                                 updates.add(Field.createFieldUpdate("from", organizerEmail));
2177                             }
2178                         }
2179 
2180                         // add required attendes as TO recipients
2181                         if (!requiredAttendees.isEmpty()) {
2182                             updates.add(Field.createFieldUpdate("to", StringUtil.join(requiredAttendees, ", ")));
2183                         }
2184                         // add optional attendees as CC recipients
2185                         if (!optionalAttendees.isEmpty()) {
2186                             updates.add(Field.createFieldUpdate("cc", StringUtil.join(optionalAttendees, ", ")));
2187                         }
2188                     }
2189 
2190                     // patch allday date values, only on 2007
2191                     if ("Exchange2007_SP1".equals(serverVersion) && vCalendar.isCdoAllDay()) {
2192                         updates.add(Field.createFieldUpdate("dtstart", convertCalendarDateToExchange(vCalendar.getFirstVeventPropertyValue("DTSTART"))));
2193                         updates.add(Field.createFieldUpdate("dtend", convertCalendarDateToExchange(vCalendar.getFirstVeventPropertyValue("DTEND"))));
2194                     }
2195 
2196                     String status = vCalendar.getFirstVeventPropertyValue("STATUS");
2197                     if ("TENTATIVE".equals(status)) {
2198                         // this is a tentative event
2199                         updates.add(Field.createFieldUpdate("busystatus", "Tentative"));
2200                     } else {
2201                         // otherwise, we use the same value as before, as received from the server
2202                         // however, the case matters, so we still have to transform it "BUSY" -> "Busy"
2203                         updates.add(Field.createFieldUpdate("busystatus", "BUSY".equals(vCalendar.getFirstVeventPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS")) ? "Busy" : "Free"));
2204                     }
2205 
2206                     if ("Exchange2007_SP1".equals(serverVersion) && vCalendar.isCdoAllDay()) {
2207                         updates.add(Field.createFieldUpdate("meetingtimezone", vCalendar.getVTimezone().getPropertyValue("TZID")));
2208                     }
2209 
2210                     newItem.setFieldUpdates(updates);
2211                     MessageDisposition messageDisposition = MessageDisposition.SaveOnly;
2212                     SendMeetingInvitations sendMeetingInvitations = SendMeetingInvitations.SendToNone;
2213                     if (vCalendar.isMeeting() && vCalendar.isMeetingOrganizer() && isMozSendInvitations) {
2214                         // meeting request creation, send notifications to attendees
2215                         messageDisposition = MessageDisposition.SendAndSaveCopy;
2216                         sendMeetingInvitations = SendMeetingInvitations.SendToAllAndSaveCopy;
2217                     }
2218                     createOrUpdateItemMethod = new CreateItemMethod(messageDisposition, sendMeetingInvitations, getFolderId(folderPath), newItem);
2219                     // force context Timezone on Exchange 2010 and 2013
2220                     if (serverVersion != null && serverVersion.startsWith("Exchange201")) {
2221                         createOrUpdateItemMethod.setTimezoneContext(EwsExchangeSession.this.getVTimezone().getPropertyValue("TZID"));
2222                     }
2223                 }
2224             }
2225 
2226             executeMethod(createOrUpdateItemMethod);
2227 
2228             itemResult.status = createOrUpdateItemMethod.getStatusCode();
2229             if (itemResult.status == HttpURLConnection.HTTP_OK) {
2230                 //noinspection VariableNotUsedInsideIf
2231                 if (currentItemId == null) {
2232                     itemResult.status = HttpStatus.SC_CREATED;
2233                     LOGGER.debug("Created event " + getHref());
2234                 } else if (isMeetingResponse) {
2235                     LOGGER.debug("Sent meeting response for event " + getHref());
2236                 } else {
2237                     LOGGER.debug("Updated event " + getHref());
2238                 }
2239             }
2240 
2241             // handle deleted occurrences
2242             if (!vCalendar.isTodo() && currentItemId != null && !isMeetingResponse && !isMozDismiss) {
2243                 handleExcludedDates(currentItemId, vCalendar);
2244                 handleModifiedOccurrences(currentItemId, vCalendar, sendMeetingInvitationsOrCancellations);
2245             }
2246 
2247 
2248             // update etag
2249             if (createOrUpdateItemMethod.getResponseItem() != null) {
2250                 ItemId newItemId = new ItemId(createOrUpdateItemMethod.getResponseItem());
2251                 GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, newItemId, false);
2252                 getItemMethod.addAdditionalProperty(Field.get("etag"));
2253                 executeMethod(getItemMethod);
2254                 itemResult.etag = getItemMethod.getResponseItem().get(Field.get("etag").getResponseName());
2255                 itemResult.itemName = StringUtil.base64ToUrl(newItemId.id) + ".EML";
2256             }
2257 
2258             return itemResult;
2259 
2260         }
2261 
2262         private HashMap<ItemId, String> buildResponseStatusUpdates(EWSMethod.Item masterEvent, VCalendar vCalendar) throws IOException {
2263             HashMap<String, String> attendeeOccurrenceStatusMap = vCalendar.getAttendeeOccurrenceStatusMap();
2264             HashMap<ItemId, String> responseStatusUpdates = new HashMap<>();
2265 
2266             if (!attendeeOccurrenceStatusMap.isEmpty()) {
2267                 for (Map.Entry<String, String> entry : attendeeOccurrenceStatusMap.entrySet()) {
2268                     String instanceId = entry.getKey();
2269                     String attendeeStatus = entry.getValue();
2270                     EWSMethod.Item occurrence;
2271                     if ("master".equals(instanceId)) {
2272                         occurrence = masterEvent;
2273                     } else {
2274                         occurrence = findOccurrenceItemId(new ItemId(masterEvent), instanceId);
2275                     }
2276                     if (occurrence != null) {
2277                         ItemId occurrenceId = new ItemId(occurrence);
2278                         String currentAttendeeStatus = responseTypeToPartstatMap.get(occurrence.get("MyResponseType"));
2279                         if (!attendeeStatus.equals(currentAttendeeStatus)) {
2280                             LOGGER.debug("Attendee " + vCalendar.getCalendarEmail() + " status " + currentAttendeeStatus + " => " + attendeeStatus + " on instance " + instanceId);
2281                             responseStatusUpdates.put(occurrenceId, attendeeStatus);
2282                         } else {
2283                             LOGGER.debug("Attendee " + vCalendar.getCalendarEmail() + " status unchanged " + currentAttendeeStatus + " on instance " + instanceId);
2284                         }
2285                     } else {
2286                         LOGGER.debug("Client sent instanceId " + instanceId + " with attendee status " + attendeeStatus + " not found");
2287                     }
2288                 }
2289             }
2290             return responseStatusUpdates;
2291         }
2292 
2293         @Override
2294         public byte[] getEventContent() throws IOException {
2295             byte[] content;
2296             if (LOGGER.isDebugEnabled()) {
2297                 LOGGER.debug("Get event: " + itemName);
2298             }
2299             try {
2300                 GetItemMethod getItemMethod;
2301                 if ("Task".equals(type)) {
2302                     getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, false);
2303                     getItemMethod.addAdditionalProperty(Field.get("importance"));
2304                     getItemMethod.addAdditionalProperty(Field.get("subject"));
2305                     getItemMethod.addAdditionalProperty(Field.get("created"));
2306                     getItemMethod.addAdditionalProperty(Field.get("lastmodified"));
2307                     getItemMethod.addAdditionalProperty(Field.get("calendaruid"));
2308                     getItemMethod.addAdditionalProperty(Field.get("description"));
2309                     if (isExchange2013OrLater()) {
2310                         getItemMethod.addAdditionalProperty(Field.get("textbody"));
2311                     }
2312                     getItemMethod.addAdditionalProperty(Field.get("percentcomplete"));
2313                     getItemMethod.addAdditionalProperty(Field.get("taskstatus"));
2314                     getItemMethod.addAdditionalProperty(Field.get("startdate"));
2315                     getItemMethod.addAdditionalProperty(Field.get("duedate"));
2316                     getItemMethod.addAdditionalProperty(Field.get("datecompleted"));
2317                     getItemMethod.addAdditionalProperty(Field.get("keywords"));
2318 
2319                 } else if (!"Message".equals(type)
2320                         && !"MeetingCancellation".equals(type)
2321                         && !"MeetingResponse".equals(type)) {
2322                     getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, true);
2323                     getItemMethod.addAdditionalProperty(Field.get("lastmodified"));
2324                     getItemMethod.addAdditionalProperty(Field.get("reminderset"));
2325                     getItemMethod.addAdditionalProperty(Field.get("calendaruid"));
2326                     getItemMethod.addAdditionalProperty(Field.get("myresponsetype"));
2327                     getItemMethod.addAdditionalProperty(Field.get("organizer"));
2328                     getItemMethod.addAdditionalProperty(Field.get("requiredattendees"));
2329                     getItemMethod.addAdditionalProperty(Field.get("optionalattendees"));
2330                     getItemMethod.addAdditionalProperty(Field.get("resources"));
2331                     getItemMethod.addAdditionalProperty(Field.get("modifiedoccurrences"));
2332                     getItemMethod.addAdditionalProperty(Field.get("starttimezone"));
2333                     getItemMethod.addAdditionalProperty(Field.get("xmozlastack"));
2334                     getItemMethod.addAdditionalProperty(Field.get("xmozsnoozetime"));
2335                     getItemMethod.addAdditionalProperty(Field.get("xmozsendinvitations"));
2336 
2337                     getItemMethod.enableNullFiltering(true);
2338                 } else {
2339                     getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, true);
2340                 }
2341 
2342                 executeMethod(getItemMethod);
2343 
2344                 // retrieve starttimezone as a failover for tzid
2345                 if (getItemMethod.getResponseItem() != null) {
2346                     startTimeZone = getItemMethod.getResponseItem().get("StartTimeZone");
2347                 }
2348 
2349                 if ("Task".equals(type)) {
2350                     VCalendar localVCalendar = new VCalendar();
2351                     localVCalendar.setPropertyValue("VERSION", "2.0");
2352                     VObject vTodo = new VObject();
2353                     vTodo.type = "VTODO";
2354                     localVCalendar.setTimezone(getVTimezone());
2355                     vTodo.setPropertyValue("LAST-MODIFIED", convertDateFromExchange(getItemMethod.getResponseItem().get(Field.get("lastmodified").getResponseName())));
2356                     vTodo.setPropertyValue("CREATED", convertDateFromExchange(getItemMethod.getResponseItem().get(Field.get("created").getResponseName())));
2357                     String calendarUid = getItemMethod.getResponseItem().get(Field.get("calendaruid").getResponseName());
2358                     if (calendarUid == null) {
2359                         // use item id as uid for Exchange created tasks
2360                         calendarUid = itemId.id;
2361                     }
2362                     vTodo.setPropertyValue("UID", calendarUid);
2363                     vTodo.setPropertyValue("SUMMARY", getItemMethod.getResponseItem().get(Field.get("subject").getResponseName()));
2364                     String description = getItemMethod.getResponseItem().get(Field.get("description").getResponseName());
2365                     if (description == null) {
2366                         // Exchange 2013: try to get description from body
2367                         description = getItemMethod.getResponseItem().get(Field.get("textbody").getResponseName());
2368                     }
2369                     vTodo.setPropertyValue("DESCRIPTION", description);
2370                     vTodo.setPropertyValue("PRIORITY", convertPriorityFromExchange(getItemMethod.getResponseItem().get(Field.get("importance").getResponseName())));
2371                     vTodo.setPropertyValue("PERCENT-COMPLETE", getItemMethod.getResponseItem().get(Field.get("percentcomplete").getResponseName()));
2372                     vTodo.setPropertyValue("STATUS", taskTovTodoStatusMap.get(getItemMethod.getResponseItem().get(Field.get("taskstatus").getResponseName())));
2373 
2374                     String taskDueDate = convertDateFromExchangeToTaskDate(getItemMethod.getResponseItem().get(Field.get("duedate").getResponseName()));
2375                     String taskStartDate = convertDateFromExchangeToTaskDate(getItemMethod.getResponseItem().get(Field.get("startdate").getResponseName()));
2376 
2377                     vTodo.setPropertyValue("DUE;VALUE=DATE", taskDueDate);
2378 
2379                     if (taskDueDate != null && taskStartDate != null && taskStartDate.compareTo(taskDueDate) > 0) {
2380                         LOGGER.warn("Task start date " + taskStartDate + " is after due date " + taskDueDate);
2381                     } else {
2382                         vTodo.setPropertyValue("DTSTART;VALUE=DATE", taskStartDate);
2383                     }
2384                     vTodo.setPropertyValue("COMPLETED;VALUE=DATE", convertDateFromExchangeToTaskDate(getItemMethod.getResponseItem().get(Field.get("datecompleted").getResponseName())));
2385 
2386                     vTodo.setPropertyValue("CATEGORIES", getItemMethod.getResponseItem().get(Field.get("keywords").getResponseName()));
2387 
2388                     localVCalendar.addVObject(vTodo);
2389                     content = localVCalendar.toString().getBytes(StandardCharsets.UTF_8);
2390                 } else {
2391                     content = getItemMethod.getMimeContent();
2392                     if (content == null) {
2393                         throw new IOException("empty event body");
2394                     }
2395                     if (!"CalendarItem".equals(type)) {
2396                         content = getICS(new SharedByteArrayInputStream(content));
2397                     }
2398                     VCalendar localVCalendar = new VCalendar(content, getCalendarEmail(folderPath), getVTimezone());
2399 
2400                     String calendaruid = getItemMethod.getResponseItem().get(Field.get("calendaruid").getResponseName());
2401 
2402                     if ("Exchange2007_SP1".equals(serverVersion)) {
2403                         // remove additional reminder
2404                         if (!"true".equals(getItemMethod.getResponseItem().get(Field.get("reminderset").getResponseName()))) {
2405                             localVCalendar.removeVAlarm();
2406                         }
2407                         if (calendaruid != null) {
2408                             localVCalendar.setFirstVeventPropertyValue("UID", calendaruid);
2409                         }
2410                     }
2411                     // Exchange does not always set organizer property properly
2412                     VProperty organizerProperty = fixOrganizer(getItemMethod, localVCalendar.getFirstVevent());
2413 
2414                     fixAttendees(getItemMethod, localVCalendar.getFirstVevent());
2415                     // fix UID and RECURRENCE-ID, broken at least on Exchange 2007
2416                     List<EWSMethod.Occurrence> occurrences = getItemMethod.getResponseItem().getOccurrences();
2417                     if (occurrences != null) {
2418                         String masterUid = localVCalendar.getFirstVevent().getPropertyValue("UID");
2419                         // Exchange does not properly update occurrences, rebuild them from occurrence items
2420                         LOGGER.debug("Rebuilding " + occurrences.size() + " modified occurrences of " + masterUid);
2421                         localVCalendar.removeModifiedOccurrences();
2422                         for (EWSMethod.Occurrence occurrence : occurrences) {
2423                             GetItemMethod getOccurrenceMethod = getOccurrence(occurrence, true);
2424                             byte[] occurrenceContent = getOccurrenceMethod.getMimeContent();
2425                             VObject modifiedOccurrence = occurrenceContent == null ? null
2426                                     : new VCalendar(occurrenceContent, getCalendarEmail(folderPath), getVTimezone()).getFirstVevent();
2427                             if (modifiedOccurrence == null) {
2428                                 LOGGER.warn("Unable to retrieve modified occurrence " + occurrence.originalStart + " of " + masterUid);
2429                             } else {
2430                                 modifiedOccurrence.removeProperty("RRULE");
2431                                 modifiedOccurrence.removeProperty("EXDATE");
2432                                 fixModifiedOccurrence(modifiedOccurrence, getOccurrenceMethod, occurrence, masterUid, organizerProperty);
2433                                 localVCalendar.addVObject(modifiedOccurrence);
2434                             }
2435                         }
2436 
2437                     }
2438                     // LAST-MODIFIED is missing in event content
2439                     localVCalendar.setFirstVeventPropertyValue("LAST-MODIFIED", convertDateFromExchange(getItemMethod.getResponseItem().get(Field.get("lastmodified").getResponseName())));
2440 
2441                     // restore mozilla invitations option
2442                     localVCalendar.setFirstVeventPropertyValue("X-MOZ-SEND-INVITATIONS",
2443                             getItemMethod.getResponseItem().get(Field.get("xmozsendinvitations").getResponseName()));
2444                     // restore mozilla alarm status
2445                     localVCalendar.setFirstVeventPropertyValue("X-MOZ-LASTACK",
2446                             getItemMethod.getResponseItem().get(Field.get("xmozlastack").getResponseName()));
2447                     localVCalendar.setFirstVeventPropertyValue("X-MOZ-SNOOZE-TIME",
2448                             getItemMethod.getResponseItem().get(Field.get("xmozsnoozetime").getResponseName()));
2449                     // overwrite method
2450                     // localVCalendar.setPropertyValue("METHOD", "REQUEST");
2451                     content = localVCalendar.toString().getBytes(StandardCharsets.UTF_8);
2452                 }
2453             } catch (IOException | MessagingException e) {
2454                 throw buildHttpNotFoundException(e);
2455             }
2456             return content;
2457         }
2458 
2459         protected VProperty fixOrganizer(GetItemMethod getItemMethod, VObject vEvent) throws IOException {
2460             VProperty organizerProperty = null;
2461             if (getItemMethod.getResponseItem() != null) {
2462                 String myResponseType = getItemMethod.getResponseItem().get("MyResponseType");
2463                 if ("Organizer".equals(myResponseType) && vEvent.getProperties("ORGANIZER") == null) {
2464                     // user is organizer on event, but Organizer property is missing from event
2465                     String calendarEmail = getCalendarEmail(folderPath);
2466                     String organizerName = getItemMethod.getResponseItem().get("Organizer");
2467                     organizerProperty = new VProperty("ORGANIZER", "mailto:" + calendarEmail);
2468                     organizerProperty.addParam("CN", organizerName);
2469                     vEvent.addProperty(organizerProperty);
2470                 }
2471             }
2472             return organizerProperty;
2473         }
2474 
2475         protected GetItemMethod getOccurrence(EWSMethod.Occurrence occurrence, boolean includeMimeContent) throws IOException {
2476             GetItemMethod getOccurrenceMethod = new GetItemMethod(BaseShape.ID_ONLY, occurrence.itemId, includeMimeContent);
2477             getOccurrenceMethod.addAdditionalProperty(Field.get("requiredattendees"));
2478             getOccurrenceMethod.addAdditionalProperty(Field.get("optionalattendees"));
2479             getOccurrenceMethod.addAdditionalProperty(Field.get("resources"));
2480             getOccurrenceMethod.addAdditionalProperty(Field.get("modifiedoccurrences"));
2481             getOccurrenceMethod.addAdditionalProperty(Field.get("starttimezone"));
2482             getOccurrenceMethod.addAdditionalProperty(Field.get("lastmodified"));
2483             getOccurrenceMethod.addAdditionalProperty(Field.get("organizer"));
2484             getOccurrenceMethod.enableNullFiltering(true);
2485             executeMethod(getOccurrenceMethod);
2486             return getOccurrenceMethod;
2487         }
2488 
2489         protected void fixModifiedOccurrence(VObject modifiedOccurrence, GetItemMethod getOccurrenceMethod, EWSMethod.Occurrence occurrence,
2490                                               String masterUid, VProperty organizerProperty) throws IOException {
2491             if (organizerProperty != null && modifiedOccurrence.getProperties("ORGANIZER") == null) {
2492                 // ensure organizer is set on all occurrences
2493                 modifiedOccurrence.addProperty(organizerProperty);
2494             }
2495             fixAttendees(getOccurrenceMethod, modifiedOccurrence);
2496             // LAST-MODIFIED is missing in event content
2497             modifiedOccurrence.setPropertyValue("LAST-MODIFIED", convertDateFromExchange(getOccurrenceMethod.getResponseItem().get(Field.get("lastmodified").getResponseName())));
2498 
2499             // fix caldav uid, should be the same as main VEVENT
2500             if (masterUid != null) {
2501                 modifiedOccurrence.setPropertyValue("UID", masterUid);
2502             }
2503 
2504             VProperty recurrenceId = modifiedOccurrence.getProperty("RECURRENCE-ID");
2505             if (recurrenceId != null) {
2506                 recurrenceId.removeParam("TZID");
2507                 recurrenceId.getValues().set(0, convertDateFromExchange(occurrence.originalStart));
2508             } else {
2509                 modifiedOccurrence.setPropertyValue("RECURRENCE-ID", convertDateFromExchange(occurrence.originalStart));
2510             }
2511         }
2512 
2513         protected void fixAttendees(GetItemMethod getItemMethod, VObject vEvent) throws IOException {
2514             if (getItemMethod.getResponseItem() != null) {
2515                 List<EWSMethod.Attendee> attendees = getItemMethod.getResponseItem().getAttendees();
2516                 if (attendees != null) {
2517                     if (vEvent.getProperties("ATTENDEE") != null) {
2518                         // clear Exchange created attendees
2519                         for (VProperty vAttendee : vEvent.getProperties("ATTENDEE")) {
2520                             vEvent.removeProperty(vAttendee);
2521                         }
2522                     }
2523                     // rebuild attendees from EWS information
2524                     String organizerEmail = getItemMethod.getResponseItem().get("EmailAddress");
2525                     String organizerName = getItemMethod.getResponseItem().get("Organizer");
2526                     if (vEvent.getProperties("ORGANIZER") == null && organizerEmail != null) {
2527                         // organizer is missing from event master or instance, rebuild
2528                         VProperty organizerProperty = new VProperty("ORGANIZER", "mailto:" + organizerEmail);
2529                         organizerProperty.addParam("CN", organizerName);
2530                         vEvent.addProperty(organizerProperty);
2531                     }
2532 
2533                     // rebuild attendees from item attendees (includes Resources with cutype)
2534                     for (EWSMethod.Attendee attendee : attendees) {
2535                         VProperty attendeeProperty = new VProperty("ATTENDEE", "mailto:" + attendee.email);
2536                         attendeeProperty.addParam("CN", attendee.name);
2537                         attendeeProperty.addParam("PARTSTAT", attendee.partstat);
2538                         attendeeProperty.addParam("ROLE", attendee.role);
2539                         if (attendee.cutype != null) {
2540                             attendeeProperty.addParam("CUTYPE", attendee.cutype);
2541                         }
2542                         vEvent.addProperty(attendeeProperty);
2543                     }
2544                 }
2545             }
2546         }
2547     }
2548 
2549     private boolean isExchange2013OrLater() {
2550         return "Exchange2013".compareTo(serverVersion) <= 0;
2551     }
2552 
2553     private EWSMethod.Item findOccurrenceItemId(ItemId masterItemId, String originalDateZulu) {
2554         int instanceIndex = 0;
2555         while (true) {
2556             instanceIndex++;
2557             try {
2558                 GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY,
2559                         new OccurrenceItemId(masterItemId.id, instanceIndex), false);
2560                 getItemMethod.addAdditionalProperty(Field.get("originalstart"));
2561                 getItemMethod.addAdditionalProperty(Field.get("myresponsetype"));
2562                 executeMethod(getItemMethod);
2563                 if (getItemMethod.getResponseItem() != null) {
2564                     String itemOriginalStart = getItemMethod.getResponseItem().get(
2565                             Field.get("originalstart").getResponseName());
2566                     if (originalDateZulu.equals(itemOriginalStart)) {
2567                         return getItemMethod.getResponseItem();
2568                     } else if (originalDateZulu.compareTo(itemOriginalStart) < 0) {
2569                         break; // past the target date
2570                     }
2571                 }
2572             } catch (IOException e) {
2573                 break; // beyond recurrence end
2574             }
2575         }
2576         return null;
2577     }
2578 
2579     /**
2580      * Get all contacts and distribution lists in the provided folder.
2581      *
2582      * @param folderPath Exchange folder path
2583      * @return list of contacts
2584      * @throws IOException on error
2585      */
2586     @Override
2587     public List<ExchangeSession.Contact> getAllContacts(String folderPath, boolean includeDistList) throws IOException {
2588         Condition condition;
2589         if (includeDistList) {
2590             condition = or(isEqualTo("outlookmessageclass", "IPM.Contact"), isEqualTo("outlookmessageclass", "IPM.DistList"));
2591         } else {
2592             condition = isEqualTo("outlookmessageclass", "IPM.Contact");
2593         }
2594         return searchContacts(folderPath, ExchangeSession.CONTACT_ATTRIBUTES, condition, 0);
2595     }
2596 
2597     @Override
2598     public List<ExchangeSession.Contact> searchContacts(String folderPath, Set<String> attributes, Condition condition, int maxCount) throws IOException {
2599         List<ExchangeSession.Contact> contacts = new ArrayList<>();
2600         List<EWSMethod.Item> responses = searchItems(folderPath, attributes, condition,
2601                 FolderQueryTraversal.SHALLOW, maxCount);
2602 
2603         for (EWSMethod.Item response : responses) {
2604             contacts.add(new Contact(response));
2605         }
2606         return contacts;
2607     }
2608 
2609     @Override
2610     protected Condition getCalendarItemCondition(Condition dateCondition) {
2611         // tasks in calendar not supported over EWS => do not look for instancetype null
2612         return or(
2613                 // Exchange 2010
2614                 or(isTrue("isrecurring"),
2615                         and(isFalse("isrecurring"), dateCondition)),
2616                 // Exchange 2007
2617                 or(isEqualTo("instancetype", 1),
2618                         and(isEqualTo("instancetype", 0), dateCondition))
2619         );
2620     }
2621 
2622     @Override
2623     public List<ExchangeSession.Event> getEventMessages(String folderPath) throws IOException {
2624         return searchEvents(folderPath, ITEM_PROPERTIES,
2625                 and(startsWith("outlookmessageclass", "IPM.Schedule.Meeting."),
2626                         or(isNull("processed"), isFalse("processed"))));
2627     }
2628 
2629     @Override
2630     public List<ExchangeSession.Event> searchEvents(String folderPath, Set<String> attributes, Condition condition) throws IOException {
2631         List<ExchangeSession.Event> events = new ArrayList<>();
2632         List<EWSMethod.Item> responses = searchItems(folderPath, attributes,
2633                 condition,
2634                 FolderQueryTraversal.SHALLOW, 0);
2635         for (EWSMethod.Item response : responses) {
2636             Event event = new Event(folderPath, response);
2637             if ("Message".equals(event.type)) {
2638                 // TODO: just exclude
2639                 // need to check body
2640                 try {
2641                     event.getEventContent();
2642                     events.add(event);
2643                 } catch (HttpNotFoundException e) {
2644                     LOGGER.warn("Ignore invalid event " + event.getHref());
2645                 }
2646                 // exclude exceptions
2647             } else if (event.isException) {
2648                 LOGGER.debug("Exclude recurrence exception " + event.getHref());
2649             } else {
2650                 events.add(event);
2651             }
2652 
2653         }
2654 
2655         return events;
2656     }
2657 
2658     /**
2659      * Common item properties
2660      */
2661     protected static final Set<String> ITEM_PROPERTIES = new HashSet<>();
2662 
2663     static {
2664         ITEM_PROPERTIES.add("etag");
2665         ITEM_PROPERTIES.add("displayname");
2666         // calendar CdoInstanceType
2667         ITEM_PROPERTIES.add("instancetype");
2668         ITEM_PROPERTIES.add("urlcompname");
2669         ITEM_PROPERTIES.add("subject");
2670     }
2671 
2672     protected static final HashSet<String> EVENT_REQUEST_PROPERTIES = new HashSet<>();
2673 
2674     static {
2675         EVENT_REQUEST_PROPERTIES.add("permanenturl");
2676         EVENT_REQUEST_PROPERTIES.add("etag");
2677         EVENT_REQUEST_PROPERTIES.add("displayname");
2678         EVENT_REQUEST_PROPERTIES.add("subject");
2679         EVENT_REQUEST_PROPERTIES.add("urlcompname");
2680         EVENT_REQUEST_PROPERTIES.add("displayto");
2681         EVENT_REQUEST_PROPERTIES.add("displaycc");
2682 
2683         EVENT_REQUEST_PROPERTIES.add("xmozlastack");
2684         EVENT_REQUEST_PROPERTIES.add("xmozsnoozetime");
2685     }
2686 
2687     protected static final HashSet<String> CALENDAR_ITEM_REQUEST_PROPERTIES = new HashSet<>();
2688 
2689     static {
2690         CALENDAR_ITEM_REQUEST_PROPERTIES.addAll(EVENT_REQUEST_PROPERTIES);
2691         CALENDAR_ITEM_REQUEST_PROPERTIES.add("ismeeting");
2692         CALENDAR_ITEM_REQUEST_PROPERTIES.add("myresponsetype");
2693     }
2694 
2695     @Override
2696     protected Set<String> getItemProperties() {
2697         return ITEM_PROPERTIES;
2698     }
2699 
2700     protected EWSMethod.Item getEwsItem(String folderPath, String itemName, Set<String> itemProperties) throws IOException {
2701         EWSMethod.Item item = null;
2702         String urlcompname = convertItemNameToEML(itemName);
2703         // workaround for missing urlcompname in Exchange 2010
2704         if (isItemId(urlcompname)) {
2705             ItemId itemId = new ItemId(StringUtil.urlToBase64(urlcompname.substring(0, urlcompname.indexOf('.'))));
2706             GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, false);
2707             for (String attribute : itemProperties) {
2708                 getItemMethod.addAdditionalProperty(Field.get(attribute));
2709             }
2710             executeMethod(getItemMethod);
2711             item = getItemMethod.getResponseItem();
2712         }
2713         // find item by urlcompname
2714         if (item == null) {
2715             List<EWSMethod.Item> responses = searchItems(folderPath, itemProperties, isEqualTo("urlcompname", urlcompname), FolderQueryTraversal.SHALLOW, 0);
2716             if (!responses.isEmpty()) {
2717                 item = responses.get(0);
2718             }
2719         }
2720         return item;
2721     }
2722 
2723 
2724     @Override
2725     public Item getItem(String folderPath, String itemName) throws IOException {
2726         EWSMethod.Item item = getEwsItem(folderPath, itemName, EVENT_REQUEST_PROPERTIES);
2727         if (item == null && isMainCalendar(folderPath)) {
2728             // look for item in task folder, replace extension first
2729             if (itemName.endsWith(".ics")) {
2730                 item = getEwsItem(TASKS, itemName.substring(0, itemName.length() - 3) + "EML", EVENT_REQUEST_PROPERTIES);
2731             } else {
2732                 item = getEwsItem(TASKS, itemName, EVENT_REQUEST_PROPERTIES);
2733             }
2734         }
2735 
2736         if (item == null) {
2737             throw new HttpNotFoundException(itemName + " not found in " + folderPath);
2738         }
2739 
2740         String itemType = item.type;
2741         if ("Contact".equals(itemType) || "DistributionList".equals(itemType)) {
2742             // retrieve Contact properties
2743             ItemId itemId = new ItemId(item);
2744             GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, false);
2745             Set<String> attributes = CONTACT_ATTRIBUTES;
2746             if ("DistributionList".equals(itemType)) {
2747                 attributes = DISTRIBUTION_LIST_ATTRIBUTES;
2748             }
2749             for (String attribute : attributes) {
2750                 getItemMethod.addAdditionalProperty(Field.get(attribute));
2751             }
2752             executeMethod(getItemMethod);
2753             item = getItemMethod.getResponseItem();
2754             if (item == null) {
2755                 throw new HttpNotFoundException(itemName + " not found in " + folderPath);
2756             }
2757             Contact contact = new Contact(item);
2758             contact.folderPath = folderPath;
2759             return contact;
2760         } else if ("CalendarItem".equals(itemType)
2761                 || "MeetingMessage".equals(itemType)
2762                 || "MeetingRequest".equals(itemType)
2763                 || "MeetingResponse".equals(itemType)
2764                 || "MeetingCancellation".equals(itemType)
2765                 || "Task".equals(itemType)
2766                 // VTODOs appear as Messages
2767                 || "Message".equals(itemType)) {
2768             Event event = new Event(folderPath, item);
2769             // force item name to client provided name (for tasks)
2770             event.setItemName(itemName);
2771             return event;
2772         } else {
2773             throw new HttpNotFoundException(itemName + " not found in " + folderPath);
2774         }
2775 
2776     }
2777 
2778     @Override
2779     public ContactPhoto getContactPhoto(ExchangeSession.Contact contact) throws IOException {
2780         ContactPhoto contactPhoto;
2781 
2782         GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, ((EwsExchangeSession.Contact) contact).itemId, false);
2783         getItemMethod.addAdditionalProperty(Field.get("attachments"));
2784         executeMethod(getItemMethod);
2785         EWSMethod.Item item = getItemMethod.getResponseItem();
2786         if (item == null) {
2787             return null;
2788         }
2789         FileAttachment attachment = item.getAttachmentByName("ContactPicture.jpg");
2790         if (attachment == null) {
2791             return null;
2792         }
2793         // get attachment content
2794         GetAttachmentMethod getAttachmentMethod = new GetAttachmentMethod(attachment.attachmentId);
2795         executeMethod(getAttachmentMethod);
2796 
2797         contactPhoto = new ContactPhoto();
2798         contactPhoto.content = getAttachmentMethod.getResponseItem().get("Content");
2799         if (attachment.contentType == null) {
2800             contactPhoto.contentType = "image/jpeg";
2801         } else {
2802             contactPhoto.contentType = attachment.contentType;
2803         }
2804 
2805         return contactPhoto;
2806     }
2807 
2808     @Override
2809     public ContactPhoto getADPhoto(String email) {
2810         ContactPhoto contactPhoto = null;
2811 
2812         if (email != null && !email.isEmpty()) {
2813             try {
2814                 GetUserPhotoMethod userPhotoMethod = new GetUserPhotoMethod(email, GetUserPhotoMethod.SizeRequested.HR240x240);
2815                 executeMethod(userPhotoMethod);
2816                 if (userPhotoMethod.getPictureData() != null) {
2817                     contactPhoto = new ContactPhoto();
2818                     contactPhoto.content = userPhotoMethod.getPictureData();
2819                     contactPhoto.contentType = userPhotoMethod.getContentType();
2820                     if (contactPhoto.contentType == null) {
2821                         contactPhoto.contentType = "image/jpeg";
2822                     }
2823                 }
2824             } catch (IOException e) {
2825                 LOGGER.debug("Error loading contact image from AD " + e + " " + e.getMessage());
2826             }
2827         }
2828 
2829         return contactPhoto;
2830     }
2831 
2832     @Override
2833     public void deleteItem(String folderPath, String itemName) throws IOException {
2834         EWSMethod.Item item = getEwsItem(folderPath, itemName, EVENT_REQUEST_PROPERTIES);
2835         if (item != null && "CalendarItem".equals(item.type)) {
2836             // reload with calendar property
2837             if (serverVersion.compareTo("Exchange2013") >= 0) {
2838                 CALENDAR_ITEM_REQUEST_PROPERTIES.add("isorganizer");
2839             }
2840             item = getEwsItem(folderPath, itemName, CALENDAR_ITEM_REQUEST_PROPERTIES);
2841         }
2842         if (item == null && isMainCalendar(folderPath)) {
2843             // look for item in task folder
2844             item = getEwsItem(TASKS, itemName, EVENT_REQUEST_PROPERTIES);
2845         }
2846         if (item != null) {
2847             boolean isMeeting = "true".equals(item.get(Field.get("ismeeting").getResponseName()));
2848             boolean isOrganizer;
2849             if (item.get(Field.get("isorganizer").getResponseName()) != null) {
2850                 // Exchange 2013 or later
2851                 isOrganizer = "true".equals(item.get(Field.get("isorganizer").getResponseName()));
2852             } else {
2853                 isOrganizer = "Organizer".equals(item.get(Field.get("myresponsetype").getResponseName()));
2854             }
2855             boolean hasAttendees = item.get(Field.get("displayto").getResponseName()) != null
2856                     || item.get(Field.get("displaycc").getResponseName()) != null;
2857 
2858             if (isMeeting && isOrganizer && hasAttendees && !isSharedFolder(folderPath)) {
2859                 // cancel meeting
2860                 SendMeetingInvitations sendMeetingInvitations = SendMeetingInvitations.SendToAllAndSaveCopy;
2861                 MessageDisposition messageDisposition = MessageDisposition.SendAndSaveCopy;
2862                 String body = null;
2863                 // This is a meeting cancel, let user edit notification message
2864                 if (Settings.getBooleanProperty("davmail.caldavEditNotifications")) {
2865                     String vEventSubject = item.get(Field.get("subject").getResponseName());
2866                     if (vEventSubject == null) {
2867                         vEventSubject = "";
2868                     }
2869                     String notificationSubject = (BundleMessage.format("CANCELLED") + vEventSubject);
2870 
2871                     NotificationDialog notificationDialog = new NotificationDialog(notificationSubject, "");
2872                     if (!notificationDialog.getSendNotification()) {
2873                         LOGGER.debug("Notification canceled by user");
2874                         sendMeetingInvitations = SendMeetingInvitations.SendToNone;
2875                         messageDisposition = MessageDisposition.SaveOnly;
2876                     }
2877                     // get description from dialog
2878                     body = notificationDialog.getBody();
2879                 }
2880                 EWSMethod.Item cancelItem = new EWSMethod.Item();
2881                 cancelItem.type = "CancelCalendarItem";
2882                 cancelItem.referenceItemId = new ItemId("ReferenceItemId", item);
2883                 if (body != null && !body.isEmpty()) {
2884                     item.put("Body", body);
2885                 }
2886                 CreateItemMethod cancelItemMethod = new CreateItemMethod(messageDisposition,
2887                         sendMeetingInvitations,
2888                         getFolderId(SENT),
2889                         cancelItem
2890                 );
2891                 executeMethod(cancelItemMethod);
2892 
2893             } else {
2894                 DeleteType deleteType = DeleteType.MoveToDeletedItems;
2895                 if (isSharedFolder(folderPath)) {
2896                     // can't move event to trash in a shared mailbox
2897                     deleteType = DeleteType.HardDelete;
2898                 }
2899                 // delete item
2900                 DeleteItemMethod deleteItemMethod = new DeleteItemMethod(new ItemId(item), deleteType, SendMeetingCancellations.SendToAllAndSaveCopy);
2901                 executeMethod(deleteItemMethod);
2902             }
2903         }
2904     }
2905 
2906     @Override
2907     public void processItem(String folderPath, String itemName) throws IOException {
2908         EWSMethod.Item item = getEwsItem(folderPath, itemName, EVENT_REQUEST_PROPERTIES);
2909         if (item != null) {
2910             HashMap<String, String> localProperties = new HashMap<>();
2911             localProperties.put("processed", "1");
2912             localProperties.put("read", "1");
2913             UpdateItemMethod updateItemMethod = new UpdateItemMethod(MessageDisposition.SaveOnly,
2914                     ConflictResolution.AlwaysOverwrite,
2915                     SendMeetingInvitationsOrCancellations.SendToNone,
2916                     new ItemId(item), buildProperties(localProperties));
2917             executeMethod(updateItemMethod);
2918         }
2919     }
2920 
2921     @Override
2922     public int sendEvent(String icsBody) throws IOException {
2923         String itemName = UUID.randomUUID() + ".EML";
2924         byte[] mimeContent = new Event(DRAFTS, itemName, "urn:content-classes:calendarmessage", icsBody, null, null).createMimeContent();
2925         if (mimeContent == null) {
2926             // no recipients, cancel
2927             return HttpStatus.SC_NO_CONTENT;
2928         } else {
2929             sendMessage(null, mimeContent);
2930             return HttpStatus.SC_OK;
2931         }
2932     }
2933 
2934     @Override
2935     protected Contact buildContact(String folderPath, String itemName, Map<String, String> properties, String etag, String noneMatch) {
2936         return new Contact(folderPath, itemName, properties, StringUtil.removeQuotes(etag), noneMatch);
2937     }
2938 
2939     @Override
2940     protected ItemResult internalCreateOrUpdateEvent(String folderPath, String itemName, String contentClass, String icsBody, String etag, String noneMatch) throws IOException {
2941         return new Event(folderPath, itemName, contentClass, icsBody, StringUtil.removeQuotes(etag), noneMatch).createOrUpdate();
2942     }
2943 
2944     @Override
2945     public boolean isSharedFolder(String folderPath) {
2946         return folderPath.startsWith("/") && !folderPath.toLowerCase().startsWith(currentMailboxPath);
2947     }
2948 
2949     @Override
2950     public boolean isMainCalendar(String folderPath) throws IOException {
2951         FolderId currentFolderId = getFolderId(folderPath);
2952         FolderId calendarFolderId = getFolderId("calendar");
2953         return calendarFolderId.name.equals(currentFolderId.name) && calendarFolderId.value.equals(currentFolderId.value);
2954     }
2955 
2956     @Override
2957     protected String getCalendarEmail(String folderPath) throws IOException {
2958         // retrieve mailbox from folder
2959         String calendarEmail = getFolderId(folderPath).mailbox;
2960         if (calendarEmail == null) {
2961             // default is current mailbox
2962             calendarEmail = email;
2963         }
2964         return calendarEmail;
2965     }
2966 
2967     @Override
2968     protected String getFreeBusyData(String attendee, String start, String end, int interval) {
2969         String result = null;
2970         GetUserAvailabilityMethod getUserAvailabilityMethod = new GetUserAvailabilityMethod(attendee, start, end, interval);
2971         try {
2972             executeMethod(getUserAvailabilityMethod);
2973             result = getUserAvailabilityMethod.getMergedFreeBusy();
2974         } catch (IOException e) {
2975             // ignore
2976         }
2977         return result;
2978     }
2979 
2980     @Override
2981     protected void loadVtimezone() {
2982 
2983         try {
2984             String timezoneId;
2985             timezoneId = Settings.getProperty("davmail.timezoneId");
2986             if (timezoneId != null) {
2987                 // Check user provided a standard timezone, convert to Exchange
2988                 timezoneId = DateUtil.getExchangeTimeZone(timezoneId);
2989             } else {
2990                 if (!"Exchange2007_SP1".equals(serverVersion)) {
2991                     // On Exchange 2010, get user timezone from server
2992                     GetUserConfigurationMethod getUserConfigurationMethod = new GetUserConfigurationMethod();
2993                     executeMethod(getUserConfigurationMethod);
2994                     EWSMethod.Item item = getUserConfigurationMethod.getResponseItem();
2995                     if (item != null) {
2996                         timezoneId = item.get("timezone");
2997                     }
2998                 } else if (!directEws) {
2999                     timezoneId = getTimezoneidFromOptions();
3000                 }
3001             }
3002             // failover: use timezone id from settings file
3003             // last failover: use GMT
3004             if (timezoneId == null) {
3005                 LOGGER.warn("Unable to get user timezone, using GMT Standard Time. Set davmail.timezoneId setting to override this.");
3006                 timezoneId = "GMT Standard Time";
3007             }
3008 
3009             EWSMethod.Item item = new EWSMethod.Item();
3010             item.type = "CalendarItem";
3011             if (!"Exchange2007_SP1".equals(serverVersion)) {
3012                 SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
3013                 dateFormatter.setTimeZone(GMT_TIMEZONE);
3014                 Calendar cal = Calendar.getInstance();
3015                 item.put("Start", dateFormatter.format(cal.getTime()));
3016                 cal.add(Calendar.DAY_OF_MONTH, 1);
3017                 item.put("End", dateFormatter.format(cal.getTime()));
3018                 item.put("StartTimeZone", timezoneId);
3019             } else {
3020                 item.put("MeetingTimeZone", timezoneId);
3021             }
3022             CreateItemMethod createItemMethod = new CreateItemMethod(MessageDisposition.SaveOnly, SendMeetingInvitations.SendToNone, getFolderId("calendar"), item);
3023             executeMethod(createItemMethod);
3024             item = createItemMethod.getResponseItem();
3025             if (item == null) {
3026                 throw new IOException("Empty timezone item");
3027             }
3028             VCalendar vCalendar = new VCalendar(getContent(new ItemId(item)), email, null);
3029             this.vTimezone = vCalendar.getVTimezone();
3030             // delete temporary item
3031             DeleteItemMethod deleteItemMethod = new DeleteItemMethod(new ItemId(item), DeleteType.HardDelete, SendMeetingCancellations.SendToNone);
3032             executeMethod(deleteItemMethod);
3033         } catch (IOException e) {
3034             LOGGER.warn("Unable to get VTIMEZONE info: " + e, e);
3035         }
3036     }
3037 
3038     protected String getTimezoneidFromOptions() {
3039         String result = null;
3040         // get time zone setting from HTML body
3041         String optionsPath = "/owa/?ae=Options&t=Regional";
3042         GetRequest optionsMethod = new GetRequest(optionsPath);
3043         try (
3044                 CloseableHttpResponse response = httpClient.execute(optionsMethod);
3045                 BufferedReader optionsPageReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))
3046         ) {
3047             String line;
3048             // find timezone
3049             //noinspection StatementWithEmptyBody
3050             while ((line = optionsPageReader.readLine()) != null
3051                     && (!line.contains("tblTmZn"))
3052                     && (!line.contains("selTmZn"))) {
3053             }
3054             if (line != null) {
3055                 if (line.contains("tblTmZn")) {
3056                     int start = line.indexOf("oV=\"") + 4;
3057                     int end = line.indexOf('\"', start);
3058                     result = line.substring(start, end);
3059                 } else {
3060                     int end = line.lastIndexOf("\" selected>");
3061                     int start = line.lastIndexOf('\"', end - 1);
3062                     result = line.substring(start + 1, end);
3063                 }
3064             }
3065         } catch (IOException e) {
3066             LOGGER.error("Error parsing options page at " + optionsPath);
3067         }
3068 
3069         return result;
3070     }
3071 
3072 
3073     protected FolderId getFolderId(String folderPath) throws IOException {
3074         FolderId folderId = getFolderIdIfExists(folderPath);
3075         if (folderId == null) {
3076             throw new HttpNotFoundException("Folder '" + folderPath + "' not found");
3077         }
3078         return folderId;
3079     }
3080 
3081     protected static final String USERS_ROOT = "/users/";
3082 
3083     protected FolderId getFolderIdIfExists(String folderPath) throws IOException {
3084         String lowerCaseFolderPath = folderPath.toLowerCase();
3085         if (lowerCaseFolderPath.equals(currentMailboxPath)) {
3086             return getSubFolderIdIfExists(null, "");
3087         } else if (lowerCaseFolderPath.startsWith(currentMailboxPath + '/')) {
3088             return getSubFolderIdIfExists(null, folderPath.substring(currentMailboxPath.length() + 1));
3089         } else if (folderPath.startsWith("/users/")) {
3090             int slashIndex = folderPath.indexOf('/', USERS_ROOT.length());
3091             String mailbox;
3092             String subFolderPath;
3093             if (slashIndex >= 0) {
3094                 mailbox = folderPath.substring(USERS_ROOT.length(), slashIndex);
3095                 subFolderPath = folderPath.substring(slashIndex + 1);
3096             } else {
3097                 mailbox = folderPath.substring(USERS_ROOT.length());
3098                 subFolderPath = "";
3099             }
3100             return getSubFolderIdIfExists(mailbox, subFolderPath);
3101         } else {
3102             return getSubFolderIdIfExists(null, folderPath);
3103         }
3104     }
3105 
3106     protected FolderId getSubFolderIdIfExists(String mailbox, String folderPath) throws IOException {
3107         String[] folderNames;
3108         FolderId currentFolderId;
3109 
3110         if ("/public".equals(folderPath)) {
3111             return DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.publicfoldersroot);
3112         } else if ("/archive".equals(folderPath)) {
3113             return DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.archivemsgfolderroot);
3114         } else if (isSubFolderOf(folderPath, PUBLIC_ROOT)) {
3115             currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.publicfoldersroot);
3116             folderNames = folderPath.substring(PUBLIC_ROOT.length()).split("/");
3117         } else if (isSubFolderOf(folderPath, ARCHIVE_ROOT)) {
3118             currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.archivemsgfolderroot);
3119             folderNames = folderPath.substring(ARCHIVE_ROOT.length()).split("/");
3120         } else if (isSubFolderOf(folderPath, INBOX) ||
3121                 isSubFolderOf(folderPath, LOWER_CASE_INBOX) ||
3122                 isSubFolderOf(folderPath, MIXED_CASE_INBOX)) {
3123             currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.inbox);
3124             folderNames = folderPath.substring(INBOX.length()).split("/");
3125         } else if (isSubFolderOf(folderPath, CALENDAR)) {
3126             currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.calendar);
3127             folderNames = folderPath.substring(CALENDAR.length()).split("/");
3128         } else if (isSubFolderOf(folderPath, TASKS)) {
3129             currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.tasks);
3130             folderNames = folderPath.substring(TASKS.length()).split("/");
3131         } else if (isSubFolderOf(folderPath, CONTACTS)) {
3132             currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.contacts);
3133             folderNames = folderPath.substring(CONTACTS.length()).split("/");
3134         } else if (isSubFolderOf(folderPath, SENT)) {
3135             currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.sentitems);
3136             folderNames = folderPath.substring(SENT.length()).split("/");
3137         } else if (isSubFolderOf(folderPath, DRAFTS)) {
3138             currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.drafts);
3139             folderNames = folderPath.substring(DRAFTS.length()).split("/");
3140         } else if (isSubFolderOf(folderPath, TRASH)) {
3141             currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.deleteditems);
3142             folderNames = folderPath.substring(TRASH.length()).split("/");
3143         } else if (isSubFolderOf(folderPath, JUNK)) {
3144             currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.junkemail);
3145             folderNames = folderPath.substring(JUNK.length()).split("/");
3146         } else if (isSubFolderOf(folderPath, UNSENT)) {
3147             currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.outbox);
3148             folderNames = folderPath.substring(UNSENT.length()).split("/");
3149         } else {
3150             currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.msgfolderroot);
3151             folderNames = folderPath.split("/");
3152         }
3153         for (String folderName : folderNames) {
3154             if (!folderName.isEmpty()) {
3155                 currentFolderId = getSubFolderByName(currentFolderId, folderName);
3156                 if (currentFolderId == null) {
3157                     break;
3158                 }
3159             }
3160         }
3161         return currentFolderId;
3162     }
3163 
3164     /**
3165      * Check if folderPath is the base folder or a sub folder path.
3166      *
3167      * @param folderPath folder path
3168      * @param baseFolder base folder
3169      * @return true if folderPath is under baseFolder
3170      */
3171     private boolean isSubFolderOf(String folderPath, String baseFolder) {
3172         if (PUBLIC_ROOT.equals(baseFolder) || ARCHIVE_ROOT.equals(baseFolder)) {
3173             return folderPath.startsWith(baseFolder);
3174         } else {
3175             return folderPath.startsWith(baseFolder)
3176                     && (folderPath.length() == baseFolder.length() || folderPath.charAt(baseFolder.length()) == '/');
3177         }
3178     }
3179 
3180     protected FolderId getSubFolderByName(FolderId parentFolderId, String folderName) throws IOException {
3181         FolderId folderId = null;
3182         FindFolderMethod findFolderMethod = new FindFolderMethod(
3183                 FolderQueryTraversal.SHALLOW,
3184                 BaseShape.ID_ONLY,
3185                 parentFolderId,
3186                 FOLDER_PROPERTIES,
3187                 new TwoOperandExpression(TwoOperandExpression.Operator.IsEqualTo,
3188                         Field.get("folderDisplayName"), decodeFolderName(folderName)),
3189                 0, 1
3190         );
3191         executeMethod(findFolderMethod);
3192         EWSMethod.Item item = findFolderMethod.getResponseItem();
3193         if (item != null) {
3194             folderId = new FolderId(item);
3195         }
3196         return folderId;
3197     }
3198 
3199     public static String decodeFolderName(String folderName) {
3200         if (folderName.contains("_xF8FF_")) {
3201             return folderName.replace("_xF8FF_", "/");
3202         }
3203         if (folderName.contains("_x003E_")) {
3204             return folderName.replace("_x003E_", ">");
3205         }
3206         return folderName;
3207     }
3208 
3209     public static String encodeFolderName(String folderName) {
3210         if (folderName.contains("/")) {
3211             folderName = folderName.replace("/", "_xF8FF_");
3212         }
3213         if (folderName.contains(">")) {
3214             folderName = folderName.replace(">", "_x003E_");
3215         }
3216         return folderName;
3217     }
3218 
3219     long throttlingTimestamp = 0;
3220 
3221     protected int executeMethod(EWSMethod ewsMethod) throws IOException {
3222         long throttlingDelay = throttlingTimestamp - System.currentTimeMillis();
3223         try {
3224             if (throttlingDelay > 0) {
3225                 LOGGER.warn("Throttling active on server, waiting " + (throttlingDelay / 1000) + " seconds");
3226                 try {
3227                     Thread.sleep(throttlingDelay);
3228                 } catch (InterruptedException e1) {
3229                     LOGGER.error("Throttling delay interrupted " + e1.getMessage());
3230                     Thread.currentThread().interrupt();
3231                 }
3232             }
3233             internalExecuteMethod(ewsMethod);
3234         } catch (EWSThrottlingException e) {
3235             // default throttling delay is one minute
3236             throttlingDelay = 60000;
3237             if (ewsMethod.backOffMilliseconds > 0) {
3238                 // server provided a throttling delay, add 10 seconds
3239                 throttlingDelay = ewsMethod.backOffMilliseconds + 10000;
3240             }
3241             throttlingTimestamp = System.currentTimeMillis() + throttlingDelay;
3242 
3243             LOGGER.warn("Throttling active on server, waiting " + (throttlingDelay / 1000) + " seconds");
3244             try {
3245                 Thread.sleep(throttlingDelay);
3246             } catch (InterruptedException e1) {
3247                 LOGGER.error("Throttling delay interrupted " + e1.getMessage());
3248                 Thread.currentThread().interrupt();
3249             }
3250             // retry once
3251             internalExecuteMethod(ewsMethod);
3252         }
3253         return ewsMethod.getStatusCode();
3254     }
3255 
3256     protected void internalExecuteMethod(EWSMethod ewsMethod) throws IOException {
3257         ewsMethod.setServerVersion(serverVersion);
3258         if (token != null) {
3259             ewsMethod.setHeader("Authorization", "Bearer " + token.getAccessToken());
3260         }
3261         try (CloseableHttpResponse response = httpClient.execute(ewsMethod)) {
3262             ewsMethod.handleResponse(response);
3263         }
3264         if (serverVersion == null) {
3265             serverVersion = ewsMethod.getServerVersion();
3266         }
3267         ewsMethod.checkSuccess();
3268     }
3269 
3270     protected static final HashMap<String, String> GALFIND_ATTRIBUTE_MAP = new HashMap<>();
3271 
3272     static {
3273         GALFIND_ATTRIBUTE_MAP.put("imapUid", "Name");
3274         GALFIND_ATTRIBUTE_MAP.put("cn", "DisplayName");
3275         GALFIND_ATTRIBUTE_MAP.put("givenName", "GivenName");
3276         GALFIND_ATTRIBUTE_MAP.put("sn", "Surname");
3277         GALFIND_ATTRIBUTE_MAP.put("smtpemail1", "EmailAddress");
3278 
3279         GALFIND_ATTRIBUTE_MAP.put("roomnumber", "OfficeLocation");
3280         GALFIND_ATTRIBUTE_MAP.put("street", "BusinessStreet");
3281         GALFIND_ATTRIBUTE_MAP.put("l", "BusinessCity");
3282         GALFIND_ATTRIBUTE_MAP.put("o", "CompanyName");
3283         GALFIND_ATTRIBUTE_MAP.put("postalcode", "BusinessPostalCode");
3284         GALFIND_ATTRIBUTE_MAP.put("st", "BusinessState");
3285         GALFIND_ATTRIBUTE_MAP.put("co", "BusinessCountryOrRegion");
3286 
3287         GALFIND_ATTRIBUTE_MAP.put("manager", "Manager");
3288         GALFIND_ATTRIBUTE_MAP.put("middlename", "Initials");
3289         GALFIND_ATTRIBUTE_MAP.put("title", "JobTitle");
3290         GALFIND_ATTRIBUTE_MAP.put("department", "Department");
3291 
3292         GALFIND_ATTRIBUTE_MAP.put("otherTelephone", "OtherTelephone");
3293         GALFIND_ATTRIBUTE_MAP.put("telephoneNumber", "BusinessPhone");
3294         GALFIND_ATTRIBUTE_MAP.put("mobile", "MobilePhone");
3295         GALFIND_ATTRIBUTE_MAP.put("facsimiletelephonenumber", "BusinessFax");
3296         GALFIND_ATTRIBUTE_MAP.put("secretarycn", "AssistantName");
3297 
3298         GALFIND_ATTRIBUTE_MAP.put("homePhone", "HomePhone");
3299         GALFIND_ATTRIBUTE_MAP.put("pager", "Pager");
3300         GALFIND_ATTRIBUTE_MAP.put("msexchangecertificate", "MSExchangeCertificate");
3301         GALFIND_ATTRIBUTE_MAP.put("usersmimecertificate", "UserSMIMECertificate");
3302     }
3303 
3304     protected static final HashSet<String> IGNORE_ATTRIBUTE_SET = new HashSet<>();
3305 
3306     static {
3307         IGNORE_ATTRIBUTE_SET.add("ContactSource");
3308         IGNORE_ATTRIBUTE_SET.add("Culture");
3309         IGNORE_ATTRIBUTE_SET.add("AssistantPhone");
3310     }
3311 
3312     protected Contact buildGalfindContact(EWSMethod.Item response) {
3313         Contact contact = new Contact();
3314         contact.setName(response.get("Name"));
3315         contact.put("imapUid", response.get("Name"));
3316         contact.put("uid", response.get("Name"));
3317         if (LOGGER.isDebugEnabled()) {
3318             for (Map.Entry<String, String> entry : response.entrySet()) {
3319                 String key = entry.getKey();
3320                 if (!IGNORE_ATTRIBUTE_SET.contains(key) && !GALFIND_ATTRIBUTE_MAP.containsValue(key)) {
3321                     LOGGER.debug("Unsupported ResolveNames " + contact.getName() + " response attribute: " + key + " value: " + entry.getValue());
3322                 }
3323             }
3324         }
3325         for (Map.Entry<String, String> entry : GALFIND_ATTRIBUTE_MAP.entrySet()) {
3326             String attributeValue = response.get(entry.getValue());
3327             if (attributeValue != null && !attributeValue.isEmpty()) {
3328                 contact.put(entry.getKey(), attributeValue);
3329             }
3330         }
3331         return contact;
3332     }
3333 
3334     @Override
3335     public Map<String, ExchangeSession.Contact> galFind(Condition condition, Set<String> returningAttributes, int sizeLimit) throws IOException {
3336         Map<String, ExchangeSession.Contact> contacts = new HashMap<>();
3337         if (condition instanceof MultiCondition) {
3338             List<Condition> conditions = ((ExchangeSession.MultiCondition) condition).getConditions();
3339             Operator operator = ((ExchangeSession.MultiCondition) condition).getOperator();
3340             if (operator == Operator.Or) {
3341                 for (Condition innerCondition : conditions) {
3342                     contacts.putAll(galFind(innerCondition, returningAttributes, sizeLimit));
3343                 }
3344             } else if (operator == Operator.And && !conditions.isEmpty()) {
3345                 Map<String, ExchangeSession.Contact> innerContacts = galFind(conditions.get(0), returningAttributes, sizeLimit);
3346                 for (ExchangeSession.Contact contact : innerContacts.values()) {
3347                     if (condition.isMatch(contact)) {
3348                         contacts.put(contact.getName().toLowerCase(), contact);
3349                     }
3350                 }
3351             }
3352         } else if (condition instanceof AttributeCondition) {
3353             String mappedAttributeName = GALFIND_ATTRIBUTE_MAP.get(((ExchangeSession.AttributeCondition) condition).getAttributeName());
3354             if (mappedAttributeName != null) {
3355                 String value = ((ExchangeSession.AttributeCondition) condition).getValue().toLowerCase();
3356                 Operator operator = ((AttributeCondition) condition).getOperator();
3357                 String searchValue = value;
3358                 if (mappedAttributeName.startsWith("EmailAddress")) {
3359                     searchValue = "smtp:" + searchValue;
3360                 }
3361                 if (operator == Operator.IsEqualTo) {
3362                     searchValue = '=' + searchValue;
3363                 }
3364                 ResolveNamesMethod resolveNamesMethod = new ResolveNamesMethod(searchValue);
3365                 executeMethod(resolveNamesMethod);
3366                 List<EWSMethod.Item> responses = resolveNamesMethod.getResponseItems();
3367                 if (LOGGER.isDebugEnabled()) {
3368                     LOGGER.debug("ResolveNames(" + searchValue + ") returned " + responses.size() + " results");
3369                 }
3370                 for (EWSMethod.Item response : responses) {
3371                     Contact contact = buildGalfindContact(response);
3372                     if (condition.isMatch(contact)) {
3373                         contacts.put(contact.getName().toLowerCase(), contact);
3374                     }
3375                 }
3376             }
3377         }
3378         return contacts;
3379     }
3380 
3381     protected Date parseDateFromExchange(String exchangeDateValue) throws DavMailException {
3382         Date dateValue = null;
3383         if (exchangeDateValue != null) {
3384             try {
3385                 dateValue = getExchangeZuluDateFormat().parse(exchangeDateValue);
3386             } catch (ParseException e) {
3387                 throw new DavMailException("EXCEPTION_INVALID_DATE", exchangeDateValue);
3388             }
3389         }
3390         return dateValue;
3391     }
3392 
3393     protected String convertDateFromExchange(String exchangeDateValue) throws DavMailException {
3394         // yyyy-MM-dd'T'HH:mm:ss'Z' to yyyyMMdd'T'HHmmss'Z'
3395         if (exchangeDateValue == null) {
3396             return null;
3397         } else {
3398             if (exchangeDateValue.length() != 20) {
3399                 throw new DavMailException("EXCEPTION_INVALID_DATE", exchangeDateValue);
3400             }
3401             StringBuilder buffer = new StringBuilder();
3402             for (int i = 0; i < exchangeDateValue.length(); i++) {
3403                 if (i == 4 || i == 7 || i == 13 || i == 16) {
3404                     i++;
3405                 }
3406                 buffer.append(exchangeDateValue.charAt(i));
3407             }
3408             return buffer.toString();
3409         }
3410     }
3411 
3412     protected String convertCalendarDateToExchange(String vcalendarDateValue) throws DavMailException {
3413         String zuluDateValue = null;
3414         if (vcalendarDateValue != null) {
3415             try {
3416                 SimpleDateFormat dateParser;
3417                 if (vcalendarDateValue.length() == 8) {
3418                     dateParser = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
3419                 } else {
3420                     dateParser = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH);
3421                 }
3422                 dateParser.setTimeZone(GMT_TIMEZONE);
3423                 SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
3424                 dateFormatter.setTimeZone(GMT_TIMEZONE);
3425                 zuluDateValue = dateFormatter.format(dateParser.parse(vcalendarDateValue));
3426             } catch (ParseException e) {
3427                 throw new DavMailException("EXCEPTION_INVALID_DATE", vcalendarDateValue);
3428             }
3429         }
3430         return zuluDateValue;
3431     }
3432 
3433     public static String convertDateFromExchangeToTaskDate(String exchangeDateValue) throws DavMailException {
3434         String zuluDateValue = null;
3435         if (exchangeDateValue != null) {
3436             try {
3437                 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
3438                 dateFormat.setTimeZone(GMT_TIMEZONE);
3439                 zuluDateValue = dateFormat.format(getExchangeZuluDateFormat().parse(exchangeDateValue));
3440             } catch (ParseException e) {
3441                 throw new DavMailException("EXCEPTION_INVALID_DATE", exchangeDateValue);
3442             }
3443         }
3444         return zuluDateValue;
3445     }
3446 
3447     protected String convertTaskDateToZulu(String value) {
3448         String result = null;
3449         if (value != null && !value.isEmpty()) {
3450             try {
3451                 SimpleDateFormat parser = ExchangeSession.getExchangeDateFormat(value);
3452                 Calendar calendarValue = Calendar.getInstance(GMT_TIMEZONE);
3453                 calendarValue.setTime(parser.parse(value));
3454                 // zulu time: add 12 hours
3455                 if (value.length() == 16) {
3456                     calendarValue.add(Calendar.HOUR, 12);
3457                 }
3458                 calendarValue.set(Calendar.HOUR, 0);
3459                 calendarValue.set(Calendar.MINUTE, 0);
3460                 calendarValue.set(Calendar.SECOND, 0);
3461                 result = ExchangeSession.getExchangeZuluDateFormat().format(calendarValue.getTime());
3462             } catch (ParseException e) {
3463                 LOGGER.warn("Invalid date: " + value);
3464             }
3465         }
3466 
3467         return result;
3468     }
3469 
3470     /**
3471      * Format date to exchange defined search format.
3472      *
3473      * @param date date object
3474      * @return formatted search date
3475      */
3476     @Override
3477     public String formatSearchDate(Date date) {
3478         SimpleDateFormat dateFormatter = new SimpleDateFormat(YYYY_MM_DD_T_HHMMSS_Z, Locale.ENGLISH);
3479         dateFormatter.setTimeZone(GMT_TIMEZONE);
3480         return dateFormatter.format(date);
3481     }
3482 
3483     private static final Pattern BASE64_EML_PATTERN = Pattern.compile("^([A-Za-z0-9\\-_]{4})*([A-Za-z0-9\\-_]{4}|[A-Za-z0-9\\-_]{3}=|[A-Za-z0-9\\-_]{2}==)\\.EML$");
3484 
3485     /**
3486      * Check if the itemName is long and base64 encoded.
3487      * User generated item names are usually short
3488      *
3489      * @param itemName item name
3490      * @return true if itemName is an EWS item id
3491      */
3492     protected static boolean isItemId(String itemName) {
3493         return itemName.length() >= 140
3494                 // item name is base64url
3495                 && BASE64_EML_PATTERN.matcher(itemName).matches()
3496                 && itemName.indexOf(' ') < 0;
3497     }
3498 
3499     /**
3500      * Close session.
3501      * Shutdown http client connection manager
3502      */
3503     @Override
3504     public void close() {
3505         httpClient.close();
3506     }
3507 
3508 }
3509