aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/ldap/LdapContactQuery.java
blob: 3f325d57d7eff7be09a4eeb96736e355410ac079 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.impl.ldap;

import java.util.*;
import java.util.regex.*;

import net.java.sip.communicator.service.contactsource.*;
import net.java.sip.communicator.service.ldap.*;
import net.java.sip.communicator.service.ldap.event.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.swing.*;

/**
 * Implements <tt>ContactQuery</tt> for LDAP.
 * <p>
 * In contrast to other contact source implementations like AddressBook and
 * Outlook the LDAP contact source implementation is explicitly moved to the
 * "impl.ldap" package in order to allow us to create LDAP contact sources
 * for ldap directories through the LdapService.
 * </p>
 *
 * @author Sebastien Vincent
 * @author Yana Stamcheva
 */
public class LdapContactQuery
    extends AsyncContactQuery<LdapContactSourceService>
{
    /**
     * Maximum results for LDAP query.
     */
    public static final int LDAP_MAX_RESULTS = 40;

    /**
     * Maximum number of results for this instance.
     */
    private final int count;

    /**
     * LDAP query.
     */
    private LdapQuery ldapQuery = null;

    /**
     * Object lock.
     */
    private final Object objLock = new Object();

    /**
     * Initializes a new <tt>LdapContactQuery</tt> instance which is to perform
     * a specific <tt>query</tt> on behalf of a specific <tt>contactSource</tt>.
     *
     * @param contactSource the <tt>ContactSourceService</tt> which is to
     * perform the new <tt>ContactQuery</tt> instance
     * @param query the <tt>Pattern</tt> for which <tt>contactSource</tt> is
     * being queried
     * @param count maximum number of results
     */
    protected LdapContactQuery(LdapContactSourceService
            contactSource, Pattern query, int count)
    {
        super(contactSource, query);
        this.count = count;
    }

    /**
     * Performs this <tt>AsyncContactQuery</tt> in a background <tt>Thread</tt>.
     *
     * @see AsyncContactQuery#run()
     */
    @Override
    protected void run()
    {
        /* query we get is delimited by \Q and \E
         * and we should not query LDAP server with a too small number of
         * characters
         */
        String queryStr = query.toString();
        if(queryStr.length() < (4))
        {
            return;
        }

        /* remove \Q and \E from the Pattern */
        String queryString = queryStr.substring(2, queryStr.length() - 2);
        LdapService ldapService = LdapActivator.getLdapService();
        LdapFactory factory = ldapService.getFactory();

        ldapQuery = factory.createQuery(queryString);
        LdapSearchSettings settings = factory.createSearchSettings();
        settings.setDelay(250);
        settings.setMaxResults(count);

        LdapListener caller = new LdapListener()
        {
            public void ldapEventReceived(LdapEvent evt)
            {
                processLdapResponse(evt);
            }
        };

        LdapDirectory ldapDir = getContactSource().getLdapDirectory();
        if(ldapDir == null)
        {
            return;
        }

        ldapDir.searchPerson(ldapQuery, caller, settings);

        synchronized(objLock)
        {
            try
            {
                objLock.wait();
            }
            catch(InterruptedException e)
            {
            }
        }
    }

    /**
     * Gets the <tt>contactDetails</tt> to be set on a <tt>SourceContact</tt>.
     *
     * @param person LDAP person
     * @return the <tt>contactDetails</tt> to be set on a <tt>SourceContact</tt>
     */
    private List<ContactDetail> getContactDetails(LdapPersonFound person)
    {
        List<ContactDetail> ret = new LinkedList<ContactDetail>();
        Set<String> mailAddresses = person.getMail();
        Set<String> mobilePhones = person.getMobilePhone();
        Set<String> homePhones = person.getHomePhone();
        Set<String> workPhones = person.getWorkPhone();
        ContactDetail detail = null;

        for(String mail : mailAddresses)
        {
            detail = new ContactDetail(mail, ContactDetail.CATEGORY_EMAIL,
                    null);
            ret.add(detail);
        }

        for(String homePhone : homePhones)
        {
            List<Class<? extends OperationSet>> supportedOpSets
                = new ArrayList<Class<? extends OperationSet>>(1);

            supportedOpSets.add(OperationSetBasicTelephony.class);
            homePhone = PhoneNumberI18nService.normalize(homePhone);
            detail = new ContactDetail(homePhone,
                    ContactDetail.CATEGORY_PHONE,
                    new String[]{ContactDetail.LABEL_HOME});
            detail.setSupportedOpSets(supportedOpSets);
            ret.add(detail);
        }

        for(String workPhone : workPhones)
        {
            List<Class<? extends OperationSet>> supportedOpSets
                = new ArrayList<Class<? extends OperationSet>>(1);

            supportedOpSets.add(OperationSetBasicTelephony.class);
            workPhone = PhoneNumberI18nService.normalize(workPhone);
            detail = new ContactDetail(workPhone,
                    ContactDetail.CATEGORY_PHONE,
                    new String[]{ContactDetail.LABEL_WORK});
            detail.setSupportedOpSets(supportedOpSets);
            ret.add(detail);
        }

        for(String mobilePhone : mobilePhones)
        {
            List<Class<? extends OperationSet>> supportedOpSets
                = new ArrayList<Class<? extends OperationSet>>(1);

            supportedOpSets.add(OperationSetBasicTelephony.class);
            mobilePhone = PhoneNumberI18nService.normalize(mobilePhone);
            detail = new ContactDetail(mobilePhone,
                    ContactDetail.CATEGORY_PHONE,
                    new String[]{ContactDetail.LABEL_MOBILE});
            detail.setSupportedOpSets(supportedOpSets);
            ret.add(detail);
        }

        return ret;
    }

    /**
     * Process LDAP event.
     *
     * @param evt LDAP event
     */
    private void processLdapResponse(LdapEvent evt)
    {
        if(evt.getCause() == LdapEvent.LdapEventCause.SEARCH_ACHIEVED ||
                evt.getCause() == LdapEvent.LdapEventCause.SEARCH_CANCELLED)
        {
            synchronized(objLock)
            {
                objLock.notify();
            }
        }

        if(evt.getCause() == LdapEvent.LdapEventCause.NEW_SEARCH_RESULT)
        {
            LdapPersonFound person = (LdapPersonFound) evt.getContent();
            String displayName = null;

            if(person == null)
            {
                return;
            }

            if(person.getDisplayName() != null)
            {
                displayName = person.getDisplayName();
            }
            else
            {
                displayName = person.getFirstName() + " " + person.getSurname();
            }

            List<ContactDetail> contactDetails = getContactDetails(person);

            if (!contactDetails.isEmpty())
            {
                GenericSourceContact sourceContact
                    = new GenericSourceContact(
                            getContactSource(),
                            displayName,
                            contactDetails);

                try
                {
                    sourceContact.setImage(person.fetchPhoto());
                }
                catch (OutOfMemoryError oome)
                {
                    // Ignore it, the image is not vital.
                }

                addQueryResult(sourceContact);
            }
        }
        else if(evt.getCause() == LdapEvent.LdapEventCause.SEARCH_AUTH_ERROR)
        {
            synchronized(objLock)
            {
                objLock.notify();
            }

            /* show authentication window to obtain new credentials */
            new Thread()
            {
                public void run()
                {
                    LdapDirectorySettingsImpl ldapSettings =
                        (LdapDirectorySettingsImpl) getContactSource()
                            .getLdapDirectory().getSettings();

                    AuthenticationWindow authWindow
                        = new AuthenticationWindow(ldapSettings.getUserName(),
                            ldapSettings.getPassword().toCharArray(),
                            ldapSettings.getName(),
                            false,
                            LdapActivator.getResourceService().getImage(
                                "service.gui.icons.AUTHORIZATION_ICON"),
                            LdapActivator.getResourceService().getI18NString(
                                "impl.ldap.WRONG_CREDENTIALS",
                                new String[]{ldapSettings.getName()}));

                    authWindow.setVisible(true);

                    if(!authWindow.isCanceled())
                    {
                        LdapDirectorySettings newSettings
                            = new LdapDirectorySettingsImpl(ldapSettings);

                        // Remove old server.
                        LdapService ldapService
                            = LdapActivator.getLdapService();

                        LdapFactory factory = ldapService.getFactory();
                        LdapDirectory ldapDir
                            = getContactSource().getLdapDirectory();
                        LdapActivator.unregisterContactSource(ldapDir);
                        ldapService.getServerSet().removeServerWithName(
                                ldapSettings.getName());

                        // Add new server.
                        newSettings.setPassword(
                            new String(authWindow.getPassword()));

                        ldapDir = factory.createServer(newSettings);
                        ldapService.getServerSet().addServer(ldapDir);

                        LdapActivator.registerContactSource(ldapDir);
                    }
                }
            }.start();
        }
    }

    /**
     * Notifies this <tt>LdapContactQuery</tt> that it has stopped performing
     * in the associated background <tt>Thread</tt>.
     *
     * @param completed <tt>true</tt> if this <tt>ContactQuery</tt> has
     * successfully completed, <tt>false</tt> if an error has been encountered
     * during its execution
     * @see AsyncContactQuery#stopped(boolean)
     */
    @Override
    protected void stopped(boolean completed)
    {
        try
        {
            super.stopped(completed);
        }
        finally
        {
            getContactSource().stopped(this);
        }
    }

    /**
     * Cancels this <tt>ContactQuery</tt>.
     *
     * @see ContactQuery#cancel()
     */
    @Override
    public void cancel()
    {
        if(ldapQuery != null)
        {
            ldapQuery.setState(LdapQuery.State.CANCELLED);
        }

        synchronized(objLock)
        {
            objLock.notify();
        }
        super.cancel();
    }
}