summaryrefslogtreecommitdiffstats
path: root/base/common/src/com/netscape/cmscore/dbs/DBSSession.java
blob: ddc9f1874092682d96e179829d7d0443f14b6c83 (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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;

import java.util.Enumeration;

import netscape.ldap.LDAPAttribute;
import netscape.ldap.LDAPAttributeSet;
import netscape.ldap.LDAPConnection;
import netscape.ldap.LDAPEntry;
import netscape.ldap.LDAPException;
import netscape.ldap.LDAPModification;
import netscape.ldap.LDAPModificationSet;
import netscape.ldap.LDAPSearchConstraints;
import netscape.ldap.LDAPSearchResults;
import netscape.ldap.LDAPv2;
import netscape.ldap.controls.LDAPPersistSearchControl;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.dbs.EDBException;
import com.netscape.certsrv.dbs.EDBNotAvailException;
import com.netscape.certsrv.dbs.EDBRecordNotFoundException;
import com.netscape.certsrv.dbs.IDBObj;
import com.netscape.certsrv.dbs.IDBSSession;
import com.netscape.certsrv.dbs.IDBSearchResults;
import com.netscape.certsrv.dbs.IDBSubsystem;
import com.netscape.certsrv.dbs.IDBVirtualList;
import com.netscape.certsrv.dbs.Modification;
import com.netscape.certsrv.dbs.ModificationSet;
import com.netscape.certsrv.logging.ILogger;

/**
 * A class represents the database session. Operations
 * can be performed with a session.
 * 
 * Transaction and Caching support can be integrated
 * into session.
 * 
 * @author thomask
 * @version $Revision$, $Date$
 */
public class DBSSession implements IDBSSession {

    private IDBSubsystem mDBSystem = null;
    private LDAPConnection mConn = null;
    private ILogger mLogger = CMS.getLogger();

    /**
     * Constructs a database session.
     * 
     * @param system the database subsytem
     * @param c the ldap connection
     */
    public DBSSession(IDBSubsystem system, LDAPConnection c) {
        mDBSystem = system;
        mConn = c;
        try {
            // no limit
            mConn.setOption(LDAPv2.SIZELIMIT, Integer.valueOf(0));
        } catch (LDAPException e) {
        }
    }

    /**
     * Returns database subsystem.
     */
    public ISubsystem getDBSubsystem() {
        return mDBSystem;
    }

    /**
     * Closes this session.
     */
    public void close() throws EDBException {
        // return ldap connection.
        mDBSystem.returnConn(mConn);
    }

    /**
     * Adds object to backend database. For example,
     * 
     * <PRE>
     * session.add(&quot;cn=123459,o=certificate repository,o=airius.com&quot;,
     *             certRec);
     * </PRE>
     * 
     * @param name the name of the ldap entry
     * @param obj the DBobj that can be mapped to ldap attrubute set
     */
    public void add(String name, IDBObj obj) throws EBaseException {
        try {
            LDAPAttributeSet attrs = mDBSystem.getRegistry(
                    ).createLDAPAttributeSet(obj);
            LDAPEntry e = new LDAPEntry(name, attrs);

            /*LogDoc
             *
             * @phase local ldap add
             * @message DBSSession: begin LDAP add <entry>
             */
            mConn.add(e);
        } catch (LDAPException e) {
            if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
                throw new EDBNotAvailException(
                        CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
            throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
                        name + " " + e.toString()));
        }
    }

    /**
     * Reads an object from the database.
     * all attributes will be returned
     * 
     * @param name the name of the ldap entry
     */
    public IDBObj read(String name) throws EBaseException {
        return read(name, null);
    }

    /**
     * Reads an object from the database, and only populates
     * the selected attributes.
     * 
     * @param name the name of the ldap entry
     * @param attrs the attributes to be selected
     */
    public IDBObj read(String name, String attrs[])
            throws EBaseException {
        try {
            String ldapattrs[] = null;

            if (attrs != null) {
                ldapattrs = mDBSystem.getRegistry(
                        ).getLDAPAttributes(attrs);
            }

            /*LogDoc
             *
             * @phase local ldap read
             * @message DBSSession: begin LDAP read <entry>
             */
            LDAPSearchResults res = mConn.search(name,
                    LDAPv2.SCOPE_BASE, "(objectclass=*)",
                    ldapattrs, false);
            LDAPEntry entry = (LDAPEntry) res.nextElement();

            return mDBSystem.getRegistry().createObject(
                    entry.getAttributeSet());
        } catch (LDAPException e) {

            /*LogDoc
             *
             * @phase local ldap read
             * @message DBSSession: <exception thrown>
             */
            mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_INFO, "DBSSession: " + e.toString());
            if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
                throw new EDBNotAvailException(
                        CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
            if (e.getLDAPResultCode() == LDAPException.NO_SUCH_OBJECT)
                throw new EDBRecordNotFoundException(
                        CMS.getUserMessage("CMS_DBS_RECORD_NOT_FOUND"));
            throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
                        name + " " + e.toString()));
        }
    }

    /**
     * Deletes object from database.
     */
    public void delete(String name) throws EBaseException {
        try {
            mConn.delete(name);
        } catch (LDAPException e) {
            if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
                throw new EDBNotAvailException(
                        CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
            throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
                        name + " " + e.toString()));
        }
    }

    /**
     * Modify an object in the database.
     */
    public void modify(String name, ModificationSet mods)
            throws EBaseException {
        try {
            LDAPModificationSet ldapMods = new
                    LDAPModificationSet();
            Enumeration<?> e = mods.getModifications();

            while (e.hasMoreElements()) {
                Modification mod = (Modification)
                        e.nextElement();
                LDAPAttributeSet attrs = new LDAPAttributeSet();

                mDBSystem.getRegistry().mapObject(null,
                        mod.getName(), mod.getValue(), attrs);
                Enumeration<?> e0 = attrs.getAttributes();

                while (e0.hasMoreElements()) {
                    ldapMods.add(toLdapModOp(mod.getOp()),
                            (LDAPAttribute)
                            e0.nextElement());
                }
            }

            /*LogDoc
             *
             * @phase local ldap add
             * @message DBSSession: begin LDAP modify <entry>
             */
            mConn.modify(name, ldapMods);
        } catch (LDAPException e) {
            if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
                throw new EDBNotAvailException(
                        CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
            throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
                        name + " " + e.toString()));
        }
    }

    private int toLdapModOp(int modOp) throws EBaseException {
        switch (modOp) {
        case Modification.MOD_ADD:
            return LDAPModification.ADD;

        case Modification.MOD_DELETE:
            return LDAPModification.DELETE;

        case Modification.MOD_REPLACE:
            return LDAPModification.REPLACE;
        }
        throw new EBaseException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
                    Integer.toString(modOp)));
    }

    /**
     * Searchs for a list of objects that match the
     * filter.
     */
    public IDBSearchResults search(String base, String filter)
            throws EBaseException {
        return search(base, filter, null);
    }

    @SuppressWarnings("unchecked")
    public IDBSearchResults search(String base, String filter, int maxSize)
            throws EBaseException {
        try {
            String ldapattrs[] = null;
            String ldapfilter =
                    mDBSystem.getRegistry().getFilter(filter);

            LDAPSearchConstraints cons = new LDAPSearchConstraints();

            cons.setMaxResults(maxSize);

            LDAPSearchResults res = mConn.search(base,
                    LDAPv2.SCOPE_ONE, ldapfilter, ldapattrs, false, cons);

            return new DBSearchResults(mDBSystem.getRegistry(),
                    res);
        } catch (LDAPException e) {
            if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
                throw new EDBNotAvailException(
                        CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
            // XXX error handling, should not raise exception if
            // entry not found
            throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
                        e.toString()));
        }
    }

    @SuppressWarnings("unchecked")
    public IDBSearchResults search(String base, String filter, int maxSize, int timeLimit)
            throws EBaseException {
        try {
            String ldapattrs[] = null;
            String ldapfilter =
                    mDBSystem.getRegistry().getFilter(filter);

            LDAPSearchConstraints cons = new LDAPSearchConstraints();

            cons.setMaxResults(maxSize);
            cons.setServerTimeLimit(timeLimit);

            LDAPSearchResults res = mConn.search(base,
                    LDAPv2.SCOPE_ONE, ldapfilter, ldapattrs, false, cons);

            return new DBSearchResults(mDBSystem.getRegistry(),
                    res);
        } catch (LDAPException e) {
            if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
                throw new EDBNotAvailException(
                        CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
            // XXX error handling, should not raise exception if
            // entry not found
            throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
                        e.toString()));
        }
    }

    /**
     * Retrieves a list of object that satifies the given
     * filter.
     */
    @SuppressWarnings("unchecked")
    public IDBSearchResults search(String base, String filter,
            String attrs[]) throws EBaseException {
        try {
            String ldapattrs[] = null;

            if (attrs != null) {
                ldapattrs = mDBSystem.getRegistry(
                        ).getLDAPAttributes(attrs);
            }
            String ldapfilter =
                    mDBSystem.getRegistry().getFilter(filter);

            /*LogDoc
             *
             * @phase local ldap add
             * @message DBSSession: begin LDAP search <filter>
             */
            LDAPSearchConstraints cons = new LDAPSearchConstraints();

            cons.setMaxResults(0);

            LDAPSearchResults res = mConn.search(base,
                    LDAPv2.SCOPE_ONE, ldapfilter, ldapattrs, false, cons);

            return new DBSearchResults(mDBSystem.getRegistry(),
                    res);
        } catch (LDAPException e) {
            if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
                throw new EDBNotAvailException(
                        CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
            // XXX error handling, should not raise exception if
            // entry not found
            throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
                        e.toString()));
        }
    }

    public LDAPSearchResults persistentSearch(String base, String filter, String attrs[])
            throws EBaseException {
        try {
            String ldapattrs[] = null;
            if (attrs != null) {
                ldapattrs = mDBSystem.getRegistry(
                        ).getLDAPAttributes(attrs);
            }
            String ldapfilter =
                    mDBSystem.getRegistry().getFilter(filter);

            Integer version = (Integer) (mConn.getOption(LDAPv2.PROTOCOL_VERSION));

            // Only version 3 protocol supports persistent search. 
            if (version.intValue() == 2) {
                mConn.setOption(LDAPv2.PROTOCOL_VERSION, Integer.valueOf(3));
            }

            int op = LDAPPersistSearchControl.MODIFY;

            boolean changesOnly = true;
            boolean returnControls = true;
            boolean isCritical = true;
            LDAPPersistSearchControl persistCtrl = new
                    LDAPPersistSearchControl(op, changesOnly,
                            returnControls, isCritical);

            LDAPSearchConstraints cons = new LDAPSearchConstraints();
            cons.setBatchSize(0);
            cons.setServerControls(persistCtrl);

            LDAPSearchResults res = mConn.search(base,
                    LDAPv2.SCOPE_ONE, ldapfilter, ldapattrs, false, cons);
            return res;
        } catch (LDAPException e) {
            if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
                throw new EDBNotAvailException(
                        CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
            // XXX error handling, should not raise exception if
            // entry not found
            throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
                        e.toString()));
        }
    }

    public void abandon(LDAPSearchResults results) throws EBaseException {
        try {
            mConn.abandon(results);

        } catch (LDAPException e) {
            if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
                throw new EDBNotAvailException(
                        CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
            // XXX error handling, should not raise exception if
            // entry not found
            throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
                        e.toString()));
        }
    }

    /**
     * Retrieves a list of objects.
     */
    public <T> IDBVirtualList<T> createVirtualList(String base, String filter,
            String attrs[]) throws EBaseException {
        return new DBVirtualList<T>(mDBSystem.getRegistry(), mConn, base,
                filter, attrs);
    }

    /**
     * Retrieves a list of objects.
     */
    public <T> IDBVirtualList<T> createVirtualList(String base, String filter,
            String attrs[], String sortKey[]) throws EBaseException {
        return new DBVirtualList<T>(mDBSystem.getRegistry(), mConn, base,
                filter, attrs, sortKey);
    }

    /**
     * Retrieves a list of objects.
     */
    public IDBVirtualList<?> createVirtualList(String base, String filter,
            String attrs[], String sortKey) throws EBaseException {
        return new DBVirtualList<Object>(mDBSystem.getRegistry(), mConn, base,
                filter, attrs, sortKey);
    }

    /**
     * Retrieves a list of objects.
     */
    public IDBVirtualList<?> createVirtualList(String base, String filter,
            String attrs[], String sortKey[], int pageSize) throws EBaseException {
        return new DBVirtualList<Object>(mDBSystem.getRegistry(), mConn, base,
                filter, attrs, sortKey, pageSize);
    }

    /**
     * Retrieves a list of objects.
     */
    public IDBVirtualList<Object> createVirtualList(String base, String filter,
            String attrs[], String sortKey, int pageSize) throws EBaseException {
        return new DBVirtualList<Object>(mDBSystem.getRegistry(), mConn, base,
                filter, attrs, sortKey, pageSize);
    }

    public IDBVirtualList<Object> createVirtualList(String base, String filter,
            String attrs[], String startFrom, String sortKey, int pageSize) throws EBaseException {
        return new DBVirtualList<Object>(mDBSystem.getRegistry(), mConn, base,
                filter, attrs, startFrom, sortKey, pageSize);

    }

    /**
     * Releases object to this interface. This allows us to
     * use memory more efficiently.
     */
    public void release(Object obj) {
        // not implemented
    }

}