File: LDAPAttribute.java

package info (click to toggle)
ldapjdk 4.20.0%2Bdfsg1-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 9,708 kB
  • sloc: ansic: 44,727; java: 39,132; xml: 7,419; sh: 4,185; perl: 3,774; makefile: 1,681; cpp: 979
file content (576 lines) | stat: -rw-r--r-- 19,279 bytes parent folder | download | duplicates (8)
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1999
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
package org.ietf.ldap;

import java.io.*;
import java.util.*;
import org.ietf.ldap.ber.stream.*;

/**
 * Represents the name and values of an attribute in an entry.
 *
 * @version 1.0
 * @see org.ietf.ldap.LDAPAttributeSet
 */
public class LDAPAttribute implements Cloneable, Serializable {

    static final long serialVersionUID = -4594745735452202600L; 
    private String name = null;
    private byte[] nameBuf = null;
    /**
     * Internally, this is a list of "byte[]"-based attribute values.
     */
    private Object values[] = new Object[0];

    /**
     * Constructs an attribute from another existing attribute.
     * Effectively, this makes a copy of the existing attribute.
     * @param attr the attribute to copy
     */
    public LDAPAttribute( LDAPAttribute attr ) {
        name = attr.name;
        nameBuf = attr.nameBuf;
        values = new Object[attr.values.length];
        for (int i = 0; i < attr.values.length; i++) {
            values[i] = new byte[((byte[])attr.values[i]).length];
            System.arraycopy((byte[])attr.values[i], 0, (byte[])values[i], 0,
                ((byte[])attr.values[i]).length);
        }
    }

    /**
     * Constructs an attribute with no values.
     * @param attrName name of the attribute
     */
    public LDAPAttribute( String attrName ) {
        name = attrName;
    }

    /**
     * Constructs an attribute with a byte-formatted value.
     * @param attrName name of the attribute
     * @param attrValue value of the attribute in byte format
     */
    public LDAPAttribute( String attrName, byte[] attrValue ) {
        name = attrName;
        addValue(attrValue);
    }

    /**
     * Constructs an attribute that has a single string value.
     * @param attrName name of the attribute
     * @param attrValue value of the attribute in String format
     */
    public LDAPAttribute( String attrName, String attrValue ) {
        name = attrName;
        addValue( attrValue );
    }

    /**
     * Constructs an attribute that has an array of string values.
     * @param attrName name of the attribute
     * @param attrValues the list of string values for this attribute
     */
    public LDAPAttribute( String attrName, String[] attrValues ) {
        name = attrName;
        if (attrValues != null) {
            setValues( attrValues );
        }
    }

    /**
     * Constructs an attribute from a BER (Basic Encoding Rules) element.
     * (The protocol elements of LDAP are encoded for exchange using the
     * Basic Encoding Rules.)
     * @param element element that you want translated into an attribute
     * @exception IOException The attribute could not be created from
     * the specified element.
     */
    public LDAPAttribute(BERElement element) throws IOException {
        BERSequence seq = (BERSequence)element;
        BEROctetString type = (BEROctetString)seq.elementAt(0);
        nameBuf = type.getValue();
        BERSet set = (BERSet)seq.elementAt(1);
        if (set.size() > 0) {
            Object[] vals = new Object[set.size()];
            for (int i = 0; i < set.size(); i++) {
                vals[i] = ((BEROctetString)set.elementAt(i)).getValue();
                if (vals[i] == null) {
                    vals[i] = new byte[0];
                }
            }
            setValues( vals );
        }
     }

    /**
     * Returns the number of values of the attribute.
     * @return number of values for this attribute.
     */
    public int size() {
        return values.length;
    }

    /**
     * Returns an enumerator for the string values of an attribute.
     * @return enumerator for the string values.
     */
    public Enumeration getStringValues() {
        Vector v = new Vector();
        synchronized(this) {
            try {
                for (int i=0; i<values.length; i++) {
                    if ( values[i] != null ) {
                        v.addElement(new String ((byte[])values[i], "UTF8"));
                    } else {
                        v.addElement( new String( "" ) );
                    }
                }
            } catch ( Exception e ) {
                return null;
            }
        }
        return v.elements();
    }
	
    /**
     * Returns the values of the attribute as an array of <CODE>String</CODE> 
     * objects.
     * @return array of attribute values. Each element in the array
     * is a <CODE>String</CODE> object.
     */
    public String[] getStringValueArray() {
    
    	String s[] = new String[values.length];
    	synchronized(this) {
    		try {
    			for (int i=0; i < values.length; i++) {
    				if ( values[i] !=null ) {
    					s[i] = new String((byte[])values[i], "UTF8");
    				} else {
    					s[i] = new String("");
    				}
    			}
    		} catch (Exception e) {
    			return null;
    		}
    	}
    	return s;
    }
    
    /**
     * Returns an enumerator for the values of the attribute in <CODE>byte[]</CODE>
     * format.
     * @return a set of attribute values. Each element in the enumeration
     * is of type <CODE>byte[]</CODE>.
     */
    public Enumeration getByteValues() {
        Vector v = new Vector();
        synchronized(this) {
            for (int i=0; i<values.length; i++) {
                if ( values[i] != null ) {
                    v.addElement(values[i]);
                } else {
                    v.addElement( new byte[0] );
                }
            }
        }
        return v.elements();
    }

    /**
     * Returns the values of the attribute in an array of <CODE>byte[]</CODE>
     * format.
     * @return array of attribute values. Each element in the array
     * will be of type <CODE>byte[]</CODE>.
     */
     public byte[][] getByteValueArray() {
    	byte b[][] = new byte[values.length][];
    	synchronized(this) {
    		try {
    			for (int i=0; i < values.length; i++) {
    				b[i] = new byte[((byte[])(values[i])).length];
	    			System.arraycopy((byte[])values[i], 0, (byte[])b[i], 0, 
    					((byte[])(values[i])).length);
    			}
    		} catch (Exception e) {
    			return null;
    		}
    	}
    	return b;
     
     }
     
    /**
     * Returns the name of the attribute.
     * @return name of the attribute.
     */
    public String getName() {
        if ((name == null) && (nameBuf != null)) {
            try{
                name = new String(nameBuf, "UTF8");
            } catch(Throwable x) {}
        }
        return name;
    }

    /**
     * Extracts the subtypes from the specified attribute name.
     * For example, if the attribute name is <CODE>cn;lang-ja;phonetic</CODE>,
     * this method returns an array containing <CODE>lang-ja</CODE>
     * and <CODE>phonetic</CODE>.
     * <P>
     *
     * @param attrName name of the attribute from which to extract the subtypes
     * @return array of subtypes, or null (if the name has no subtypes).
     * @see org.ietf.ldap.LDAPAttribute#getBaseName
     */
    public static String[] getSubtypes(String attrName) {
        StringTokenizer st = new StringTokenizer(attrName, ";");
        if( st.hasMoreElements() ) {
            // First element is base name
            st.nextElement();
            String[] subtypes = new String[st.countTokens()];
            int i = 0;
            // Extract the types
            while( st.hasMoreElements() )
                subtypes[i++] = (String)st.nextElement();
            return subtypes;
        }
        return null;
    }

    /**
     * Extracts the subtypes from the attribute name of the current
     * <CODE>LDAPAttribute</CODE> object.  For example, if the attribute
     * name is <CODE>cn;lang-ja;phonetic</CODE>, this method returns an array
     * containing <CODE>lang-ja</CODE> and <CODE>phonetic</CODE>.
     *<P>
     *
     * @return array of subtypes, or null (if the name has no subtypes).
     */
    public String[] getSubtypes() {
        return getSubtypes(getName());
    }

    /**
     * Extracts the language subtype from the attribute name of the
     * <CODE>LDAPAttribute</CODE> object, if any.  For example, if the
     * attribute name is <CODE>cn;lang-ja;phonetic</CODE>, this method
     * returns the String <CODE>lang-ja</CODE>.
     *<P>
     *
     * @return the language subtype, or null (if the name has no
     * language subtype).
     */
    public String getLangSubtype() {
        String[] subTypes = getSubtypes();
        if ( subTypes != null ) {
            for( int i = 0; i < subTypes.length; i++ ) {
                if ((subTypes[i].length() >= 5) &&
                    (subTypes[i].substring(0, 5).equalsIgnoreCase("lang-")))
                    return subTypes[i];
            }
        }
        return null;
    }

    /**
     * Extracts the base name from the specified attribute name.
     * For example, if the attribute name is <CODE>cn;lang-ja;phonetic</CODE>,
     * this method returns <CODE>cn</CODE>.
     * <P>
     *
     * @param attrName name of the attribute from which to extract the base name
     * @return base name (the attribute name without any subtypes).
     * @see org.ietf.ldap.LDAPAttribute#getSubtypes
     */
    public static String getBaseName( String attrName ) {
        String basename = attrName;
        StringTokenizer st = new StringTokenizer(attrName, ";");
        if( st.hasMoreElements() )
            // First element is base name
            basename = (String)st.nextElement();
        return basename;
    }

    /**
     * Extracts the base name from the attribute name of the current
     * <CODE>LDAPAttribute</CODE> object. For example, if the attribute
     * name is <CODE>cn;lang-ja;phonetic</CODE>, this method returns
     * <CODE>cn</CODE>.
     * <P>
     *
     * @return base name (the attribute name without any subtypes).
     * @see org.ietf.ldap.LDAPAttribute#getSubtypes
     */
    public String getBaseName() {
        return getBaseName(getName());
    }

    /**
     * Reports whether the attribute name contains the specified subtype.
     * For example, if you check for the subtype <CODE>lang-en</CODE>
     * and the attribute name is <CODE>cn;lang-en</CODE>, this method
     * returns <CODE>true</CODE>.
     * <P>
     *
     * @param subtype the single subtype for which you want to check
     * @return true if the attribute name contains the specified subtype.
     * @see org.ietf.ldap.LDAPAttribute#getSubtypes
     */
    public boolean hasSubtype( String subtype ) {
        String[] mytypes = getSubtypes();
        for(int i = 0; i < mytypes.length; i++) {
            if( subtype.equalsIgnoreCase( mytypes[i] ) )
                return true;
        }
        return false;
    }

    /**
     * Reports if the attribute name contains all specified subtypes
     * For example, if you check for the subtypes <CODE>lang-en</CODE>
     * and <CODE>phonetic</CODE> and the attribute name is
     * <CODE>cn;lang-en;phonetic</CODE>, this method returns <CODE>true</CODE>.
     * If the attribute name is <CODE>cn;phonetic</CODE> or
     * <CODE>cn;lang-en</CODE>, this method returns <CODE>false</CODE>.
     * <P>
     * @param subtypes an array of subtypes to check
     * @return true if the attribute name contains all subtypes
     * @see org.ietf.ldap.LDAPAttribute#getSubtypes
     */
    public boolean hasSubtypes( String[] subtypes ) {
        for(int i = 0; i < subtypes.length; i++) {
            if( !hasSubtype(subtypes[i]) )
                return false;
        }
        return true;
    }

    /**
     * Adds a string value to the attribute.
     * @param attrValue the string value to add to the attribute
     */
    public synchronized void addValue( String attrValue ) {
        if (attrValue != null) {
            try {
                byte[] b = attrValue.getBytes("UTF8");
                addValue( b );
            } catch(Throwable x)
            {}
        }
    }

    /**
     * Sets the string values as the attribute's values.
     * @param attrValues the string values to use in the attribute
     */
    protected void setValues( String[] attrValues ) {
        Object[] vals;
        if (attrValues != null) {
            vals = new Object[attrValues.length];
            for (int i = 0; i < vals.length; i++) {
                try {
                    vals[i] = attrValues[i].getBytes("UTF8");
                } catch(Throwable x)
                    { vals[i] = new byte[0]; }
            }
        } else {
            vals = new Object[0];
        }
        setValues(vals);
    }

    /**
     * Adds a <CODE>byte[]</CODE>-formatted value to the attribute.
     * @param attrValue the <CODE>byte[]</CODE>-formatted value to
     * add to the attribute
     */
    public synchronized void addValue( byte[] attrValue ) {
        if (attrValue != null) {
            Object[] vals = new Object[values.length+1];
            for (int i = 0; i < values.length; i++)
                vals[i] = values[i];
            vals[values.length] = attrValue;
            values = vals;
        }
    }

    /**
     * Sets the byte[] values as the attribute's values.
     * @param attrValues the values to use in the attribute
     */
    protected synchronized void setValues( Object[] attrValues ) {
        values = attrValues;
    }

    /**
     * Removes a string value from the attribute.
     * @param attrValue the string value to remove
     */
    public synchronized void removeValue( String attrValue) {
        if (attrValue != null) {
            try{
                byte b[] = attrValue.getBytes("UTF8");
                removeValue ( b );
            } catch(Throwable x)
            {}
        }
    }

    /**
     * Removes a <CODE>byte[]</CODE>-formatted value from the attribute.
     * @param attrValue <CODE>byte[]</CODE>-formatted value to remove
     */
    public synchronized void removeValue( byte[] attrValue) {
        if ((attrValue == null) || (values == null)|| (values.length < 1))
            return;
        int ind = -1;
        for (int i=0; i<values.length; i++) {
            if (equalValue(attrValue, (byte[])values[i])) {
                ind = i;
                 break;
            }
        }
        if (ind >= 0) {
            Object[] vals = new Object[values.length-1];
            int j = 0;
            for (int i = 0; i < values.length; i++) {
                if (i != ind) {
                    vals[j++] = values[i];
                }
            }
            values = vals;
        }
    }

    private static boolean equalValue(byte[] a, byte[] b) {
        if (a.length != b.length)
            return false;

        for (int i=0; i<a.length; i++) {
            if (a[i] != b[i])
                return false;
        }
        return true;
    }

    /**
     * Retrieves the BER (Basic Encoding Rules) representation of an attribute.
     * (The protocol elements of LDAP are encoded for exchange using the
     * Basic Encoding Rules.)
     * @return the BER representation of the attribute.
     */
    public BERElement getBERElement() {
        try {
            BERSequence seq = new BERSequence();
            seq.addElement(new BEROctetString(getName()));
            BERSet set = new BERSet();
            for (int i = 0; i < values.length; i++) {
                set.addElement(new BEROctetString((byte[])values[i]));
            }
            seq.addElement(set);
            return seq;
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * Retrieves the string representation of attribute parameters.
     * @return string representation parameters.
     */
    private String getParamString() {
        StringBuffer sb = new StringBuffer();
        
        if ( values.length > 0 ) {
            for (int i = 0; i < values.length; i++) {
                if (i != 0) {
                    sb.append(",");
                }
                byte[] val = (byte[])values[i];
                try {
                    String sval = new String(val, "UTF8");
                    if (sval.length() == 0 && val.length > 0) {
                        sb.append("<binary value, length:");
                        sb.append(val.length);
                        sb.append(">");
                    }
                    else {
                        sb.append(sval);
                    }
                     
                } catch (Exception e) {
                    if (val != null) {
                        sb.append("<binary value, length:");
                        sb.append(val.length);
                        sb.append(">");
                    }
                    else {
                        sb.append("null value");
                    }
                }
            }
        }
        return "{type='" + getName() + "', values='" + sb.toString() + "'}";
    }

    /**
     * Creates and returns a new <CODE>LDAPAttribute</CODE> object that
     * contains the same information as this one. The cloned object has
     * a deep copy of the contents of the original.
     *
     * @return A deep copy of this object
     */
    public synchronized Object clone() {
        return new LDAPAttribute( this );
    }

    /**
     * Retrieves the string representation of an attribute
     * in an LDAP entry. For example:
     *
     * <PRE>LDAPAttribute {type='cn', values='Barbara Jensen,Babs Jensen'}</PRE>
     *
     * @return string representation of the attribute.
     */
    public String toString() {
        return "LDAPAttribute " + getParamString();
    }
}