summaryrefslogtreecommitdiffstats
path: root/libjava/classpath/javax/naming/InitialContext.java
blob: 1a3b1e38b03f3f7cdb80e504c04871b5210bfb92 (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
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
/* InitialContext.java -- Initial naming context.
   Copyright (C) 2000, 2002, 2003, 2004, 2006 Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath 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; either version 2, or (at your option)
any later version.

GNU Classpath 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 GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package javax.naming;

import java.applet.Applet;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Properties;

import javax.naming.spi.NamingManager;

/**
 * The starting context for performing naming operations. All naming operations
 * are performed in the scope of some context. The initial context is the
 * starting point for the name resolution.
 */
public class InitialContext implements Context
{
  /**
   * Contains the default initial context. This value is returned by
   * {@link NamingManager#getInitialContext}. It is set by this method
   * when calling it first time. The subsequent calls return the value of
   * this field.
   */
  protected Context defaultInitCtx;
  
  /**
   * Indicates if the initial context was obtained by calling
   * {@link NamingManager#getInitialContext}. 
   */
  protected boolean gotDefault = false;
  
  /**
   * The environment, associated with this initial context.
   */
  protected Hashtable<Object,Object> myProps;
  
  /**
   * The list of the properties, to that the second alternative value must
   * be appended after the colon to the first possible value. Used in
   * {@link #merge(Hashtable, Hashtable)}
   */
  static final HashSet colon_list;
  static
    {
      colon_list = new HashSet();
      colon_list.add(Context.OBJECT_FACTORIES);
      colon_list.add(Context.URL_PKG_PREFIXES);
      colon_list.add(Context.STATE_FACTORIES);
    };  
    
   /**
    * The properties that are searched in the agreed places in the
    * {@link #init(Hashtable)} method.
    */
    static final String[] use_properties = 
      {
        Context.DNS_URL,
        Context.INITIAL_CONTEXT_FACTORY,
        Context.OBJECT_FACTORIES,
        Context.PROVIDER_URL,
        Context.STATE_FACTORIES,
        Context.URL_PKG_PREFIXES,
      };
    
  
  /**
   * Creates the new initial context with the given properties.
   * 
   * @param environment the properties, used by the initial context being
   *          created.
   * @throws NamingException
   */
  public InitialContext(Hashtable<?,?> environment) throws NamingException
  {
    init(environment);
  }
  
  /**
   * Creates the initial context with the possibility to delay its
   * initialisation.
   * 
   * @param lazy specified if the initialization should not be performed by this
   *          constructor (true). If the valueis false, it works the same way as
   *          the parameterless constructor.
   * @throws NamingException
   */
  protected InitialContext(boolean lazy) throws NamingException
  {
    if (! lazy)
      init(null);
  }
  
  /**
   * Creates teh new initial context with no properties. Same as
   * InitialContext(null).
   * 
   * @throws NamingException
   */
  public InitialContext() throws NamingException
  {
    init(null);
  }
 
  /**
   * <p>
   * Initialises the context, using the properties, specified in the passed
   * table.
   * </p>
   * The missing properties are additionally obtained (in order) from the
   * following locations:
   * <ul>
   * <li>If the passed parameter contains the key Context.APPLET, its value
   * must be the instance of the {@link Applet}. Then the properties are
   * requested via {@link Applet#getParameter(String)}.</li>
   * <li>The value of the system property is used.</li>
   * <li>The resource "jndi.properties" is requested from the context class
   * loader of the current thread</li>
   * <li>The property file "jndi.properties" is read from the location,
   * specified by the system property "gnu.classpath.home.url".
   * </ul>
   * </p>
   * 
   * @param environment the table of the properties, may be null. The method
   *          modifies the table and stores the reference to it. The caller must
   *          not later reuse this structure for other purposes.
   * @since 1.3
   */
  protected void init(Hashtable<?, ?> environment) throws NamingException
  {
    // If is documented that the caller should not modify the environment.
    if (environment != null)
      myProps = (Hashtable<Object, Object>) environment;
    else
      myProps = new Hashtable<Object, Object>();

    Applet napplet = (Applet) myProps.get(Context.APPLET);

    Properties pApplet = null;
    if (napplet != null)
      pApplet = new Properties();
    Properties pSystem = new Properties();
    Object value;

    for (int i = use_properties.length - 1; i >= 0; i--)
      {
        String key = use_properties[i];
        if (napplet != null)
          {
            value = napplet.getParameter(key);
            if (value != null)
              pApplet.put(key, value);
          }
        
        value = System.getProperty(key);
        if (value != null)
          pSystem.put(key, value);
      }
    
    merge(myProps, pSystem);
    if (pApplet != null)
      merge(myProps, pApplet);

    try
      {
        Enumeration ep = Thread.currentThread().
          getContextClassLoader().getResources("jndi.properties");
        while (ep.hasMoreElements())
          {
            URL url = (URL) ep.nextElement();
            Properties p = new Properties();

            try
              {
                InputStream is = url.openStream();
                p.load(is);
                is.close();
              }
            catch (IOException e)
              {
                // Ignore.
              }

            merge(myProps, p);
          }
      }
    catch (IOException e)
      {
        // Ignore.
      }

    String home = System.getProperty("gnu.classpath.home.url");
    if (home != null)
      {
        String url = home + "/jndi.properties";
        Properties p = new Properties();

        try
          {
            InputStream is = new URL(url).openStream();
            p.load(is);
            is.close();
          }
        catch (IOException e)
          {
            // Ignore.
          }

        merge(myProps, p);
      }
  }
  
  /**
   * Merge the content of the two tables. If the second table contains the key
   * that is missing in the first table, this key - value pair is copied to the
   * first table. If both first and second tables contain the same key AND the
   * {@link #colon_list} set also contains this key, the value from the second
   * table is appended to the value from the first table after semicolon, and
   * the resulted value replaces the value in the first table.
   * 
   * @param primary the first table to merge. The merged result is also stored
   *          in this table.
   * @param additional the second table, from where additional values are taken
   */  
  static void merge (Hashtable primary, Hashtable additional)
  {
    Enumeration en = additional.keys();
    
    while (en.hasMoreElements())
      {
        String key2 = (String) en.nextElement();
        Object value1 = primary.get(key2);
        if (value1 == null)
          primary.put(key2, additional.get(key2));
        else if (colon_list.contains(key2))
          {
            String value2 = (String) additional.get(key2);
            primary.put(key2, (String) value1 + ":" + value2);
          }
      }
  }
  
  /**
   * Get the default initial context. If {@link #gotDefault} == false, this
   * method obtains the initial context from the naming manager and sets
   * gotDefault to true. Otherwise the cached value ({@link #defaultInitCtx} is
   * returned.
   * 
   * @return the default initial context
   * @throws NamingException
   */
  protected Context getDefaultInitCtx() throws NamingException
  {
    if (! gotDefault)
      {
        defaultInitCtx = NamingManager.getInitialContext(myProps);
        gotDefault = true;
      }
    return defaultInitCtx;
  }

  /**
   * Obtains the context for resolving the given name. If the first component of
   * the name is the URL string, this method tries to find the corressponding
   * URL naming context. If it is not an URL string, or the URL context is not
   * found, the default initial context is returned.
   * 
   * @param name the name, for that it is required to obtain the context.
   * @return the context for resolving the name.
   * @throws NamingException
   */
  protected Context getURLOrDefaultInitCtx(Name name) throws NamingException
  {
    if (name.size() > 0)
      return getURLOrDefaultInitCtx(name.get(0));
    else
      return getDefaultInitCtx();
  }

  /**
   * Obtains the context for resolving the given name. If the first component of
   * the name is the URL string, this method tries to find the corressponding
   * URL naming context. If it is not an URL string, or the URL context is not
   * found, the default initial context is returned.
   * 
   * @param name the name, for that it is required to obtain the context.
   * @return the context for resolving the name.
   * @throws NamingException
   */
  protected Context getURLOrDefaultInitCtx(String name) throws NamingException
  {
    String scheme = null;

    if (NamingManager.hasInitialContextFactoryBuilder())
      return getDefaultInitCtx();
    int colon = name.indexOf(':');
    int slash = name.indexOf('/');
    if (colon > 0 && (slash == - 1 || colon < slash))
      scheme = name.substring(0, colon);
    if (scheme != null)
      {
        Context context = NamingManager.getURLContext(scheme, myProps);
        if (context != null)
          return context;
      }

    return getDefaultInitCtx();
  }

  /** @inheritDoc */  
  public void bind (Name name, Object obj) throws NamingException
  {
    getURLOrDefaultInitCtx (name).bind (name, obj);
  }

  /** @inheritDoc */  
  public void bind (String name, Object obj) throws NamingException
  {
    getURLOrDefaultInitCtx (name).bind (name, obj);
  }

  /** @inheritDoc */  
  public Object lookup (Name name) throws NamingException
  {
    try
      {
        return getURLOrDefaultInitCtx (name).lookup (name);
      }
    catch (CannotProceedException cpe)
      {
        Context ctx = NamingManager.getContinuationContext (cpe);
        return ctx.lookup (cpe.getRemainingName());
      }
  }

  /** @inheritDoc */  
  public Object lookup (String name) throws NamingException
  {
      try
        {
          return getURLOrDefaultInitCtx (name).lookup (name);
        }
      catch (CannotProceedException cpe)
        {
          Context ctx = NamingManager.getContinuationContext (cpe);
          return ctx.lookup (cpe.getRemainingName());
        }
  }

  /** @inheritDoc */  
  public void rebind (Name name, Object obj) throws NamingException
  {
    getURLOrDefaultInitCtx (name).rebind (name, obj);
  }
  
  /** @inheritDoc */
  public void rebind (String name, Object obj) throws NamingException
  {
    getURLOrDefaultInitCtx (name).rebind (name, obj);
  }

  /** @inheritDoc */  
  public void unbind (Name name) throws NamingException
  {
    getURLOrDefaultInitCtx (name).unbind (name);
  }

  /** @inheritDoc */  
  public void unbind (String name) throws NamingException
  {
    getURLOrDefaultInitCtx (name).unbind (name);
  }

  /** @inheritDoc */  
  public void rename (Name oldName, Name newName) throws NamingException
  {
    getURLOrDefaultInitCtx (oldName).rename (oldName, newName);
  }

  /** @inheritDoc */  
  public void rename (String oldName, String newName) throws NamingException
  {
    getURLOrDefaultInitCtx (oldName).rename (oldName, newName);
  }

  /** @inheritDoc */  
  public NamingEnumeration<NameClassPair> list (Name name) throws NamingException
  {
    return getURLOrDefaultInitCtx (name).list (name);
  }

  /** @inheritDoc */  
  public NamingEnumeration<NameClassPair> list (String name) throws NamingException
  {
    return getURLOrDefaultInitCtx (name).list (name);
  }

  /** @inheritDoc */  
  public NamingEnumeration<Binding> listBindings (Name name) throws NamingException
  {
    return getURLOrDefaultInitCtx (name).listBindings (name);
  }

  /** @inheritDoc */  
  public NamingEnumeration<Binding> listBindings (String name) throws NamingException
  {
    return getURLOrDefaultInitCtx (name).listBindings (name);
  }

  /** @inheritDoc */  
  public void destroySubcontext (Name name) throws NamingException
  {
    getURLOrDefaultInitCtx (name).destroySubcontext (name);
  }

  /** @inheritDoc */  
  public void destroySubcontext (String name) throws NamingException
  {
    getURLOrDefaultInitCtx (name).destroySubcontext (name);
  }

  /** @inheritDoc */  
  public Context createSubcontext (Name name) throws NamingException
  {
    return getURLOrDefaultInitCtx (name).createSubcontext (name);
  }

  /** @inheritDoc */  
  public Context createSubcontext (String name) throws NamingException
  {
    return getURLOrDefaultInitCtx (name).createSubcontext (name);
  }

  /** @inheritDoc */  
  public Object lookupLink (Name name) throws NamingException
  {
    return getURLOrDefaultInitCtx (name).lookupLink (name);
  }

  /** @inheritDoc */  
  public Object lookupLink (String name) throws NamingException
  {
    return getURLOrDefaultInitCtx (name).lookupLink (name);
  }

  /** @inheritDoc */  
  public NameParser getNameParser (Name name) throws NamingException
  {
    return getURLOrDefaultInitCtx (name).getNameParser (name);
  }

  /** @inheritDoc */  
  public NameParser getNameParser (String name) throws NamingException
  {
    return getURLOrDefaultInitCtx (name).getNameParser (name);
  }

  /** @inheritDoc */  
  public Name composeName (Name name, Name prefix) throws NamingException
  {
    return getURLOrDefaultInitCtx (name).composeName (name, prefix);
  }

  /** @inheritDoc */  
  public String composeName (String name, 
                             String prefix) throws NamingException
  {
    return getURLOrDefaultInitCtx (name).composeName (name, prefix);
  }
  
  /** @inheritDoc */
  public Object addToEnvironment (String propName, 
                                  Object propVal) throws NamingException
  {
    return myProps.put (propName, propVal);
  }

  /** @inheritDoc */  
  public Object removeFromEnvironment (String propName) throws NamingException
  {
    return myProps.remove (propName);
  }

  /** @inheritDoc */  
  public Hashtable<?,?> getEnvironment () throws NamingException
  {
    return myProps;
  }

  /** @inheritDoc */  
  public void close () throws NamingException
  {
    myProps = null;
    defaultInitCtx = null;
  }

  /**
   * This operation is not supported for the initial naming context.
   * 
   * @throws OperationNotSupportedException always, unless the method is
   *           overridden in the derived class.
   */
  public String getNameInNamespace () throws NamingException
  {
    throw new OperationNotSupportedException ();
  }
}
OpenPOWER on IntegriCloud