1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package davmail.exchange.ews;
21
22 import org.apache.http.Header;
23 import org.apache.http.HttpResponse;
24 import org.apache.http.client.ResponseHandler;
25 import org.apache.http.client.methods.CloseableHttpResponse;
26 import org.apache.http.client.methods.HttpPost;
27 import org.apache.http.entity.ContentType;
28 import org.apache.http.entity.StringEntity;
29 import org.apache.log4j.Logger;
30
31 import java.io.BufferedReader;
32 import java.io.IOException;
33 import java.io.InputStreamReader;
34 import java.nio.charset.StandardCharsets;
35
36 public class AutoDiscoverMethod extends HttpPost implements ResponseHandler {
37
38 protected static final Logger LOGGER = Logger.getLogger(AutoDiscoverMethod.class);
39
40 public AutoDiscoverMethod(String url, String userEmail) {
41 super(url);
42 setRequestEntity(userEmail);
43 }
44
45 private void setRequestEntity(String userEmail) {
46 String body = "<Autodiscover xmlns=\"http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006\">" +
47 "<Request>" +
48 "<EMailAddress>" + userEmail + "</EMailAddress>" +
49 "<AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema>" +
50 "</Request>" +
51 "</Autodiscover>";
52 setEntity(new StringEntity(body, ContentType.create("text/xml", "UTF-8")));
53 }
54
55 @Override
56 public Object handleResponse(HttpResponse response) throws IOException {
57 String ewsUrl = null;
58 try {
59 Header contentTypeHeader = response.getFirstHeader("Content-Type");
60 if (contentTypeHeader != null &&
61 ("text/xml; charset=utf-8".equals(contentTypeHeader.getValue())
62 || "text/html; charset=utf-8".equals(contentTypeHeader.getValue())
63 )) {
64 BufferedReader autodiscoverReader = null;
65 try {
66 autodiscoverReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
67 String line;
68
69
70 while ((line = autodiscoverReader.readLine()) != null
71 && (!line.contains("<EwsUrl>"))
72 && (!line.contains("</EwsUrl>"))) {
73 }
74 if (line != null) {
75 ewsUrl = line.substring(line.indexOf("<EwsUrl>") + 8, line.indexOf("</EwsUrl>"));
76 }
77 } catch (IOException e) {
78 LOGGER.debug(e);
79 } finally {
80 if (autodiscoverReader != null) {
81 try {
82 autodiscoverReader.close();
83 } catch (IOException e) {
84 LOGGER.debug(e);
85 }
86 }
87 }
88 }
89
90 } finally {
91 ((CloseableHttpResponse) response).close();
92 }
93 return ewsUrl;
94 }
95 }