Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.naming/share/classes/javax/naming/spi/NamingManager.java
41159 views
1
/*
2
* Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package javax.naming.spi;
27
28
import java.net.MalformedURLException;
29
import java.security.AccessController;
30
import java.security.PrivilegedAction;
31
import java.util.*;
32
33
import javax.naming.*;
34
35
import com.sun.naming.internal.ObjectFactoriesFilter;
36
import com.sun.naming.internal.VersionHelper;
37
import com.sun.naming.internal.ResourceManager;
38
import com.sun.naming.internal.FactoryEnumeration;
39
import jdk.internal.loader.ClassLoaderValue;
40
41
/**
42
* This class contains methods for creating context objects
43
* and objects referred to by location information in the naming
44
* or directory service.
45
*<p>
46
* This class cannot be instantiated. It has only static methods.
47
*<p>
48
* The mention of URL in the documentation for this class refers to
49
* a URL string as defined by RFC 1738 and its related RFCs. It is
50
* any string that conforms to the syntax described therein, and
51
* may not always have corresponding support in the java.net.URL
52
* class or Web browsers.
53
*<p>
54
* NamingManager is safe for concurrent access by multiple threads.
55
*<p>
56
* Except as otherwise noted,
57
* a {@code Name} or environment parameter
58
* passed to any method is owned by the caller.
59
* The implementation will not modify the object or keep a reference
60
* to it, although it may keep a reference to a clone or copy.
61
*
62
* @author Rosanna Lee
63
* @author Scott Seligman
64
* @since 1.3
65
*/
66
67
public class NamingManager {
68
69
/*
70
* Disallow anyone from creating one of these.
71
* Made package private so that DirectoryManager can subclass.
72
*/
73
74
NamingManager() {}
75
76
// should be protected and package private
77
static final VersionHelper helper = VersionHelper.getVersionHelper();
78
79
// --------- object factory stuff
80
81
/**
82
* Package-private; used by DirectoryManager and NamingManager.
83
*/
84
private static ObjectFactoryBuilder object_factory_builder = null;
85
86
private static final ClassLoaderValue<InitialContextFactory> FACTORIES_CACHE =
87
new ClassLoaderValue<>();
88
89
/**
90
* The ObjectFactoryBuilder determines the policy used when
91
* trying to load object factories.
92
* See getObjectInstance() and class ObjectFactory for a description
93
* of the default policy.
94
* setObjectFactoryBuilder() overrides this default policy by installing
95
* an ObjectFactoryBuilder. Subsequent object factories will
96
* be loaded and created using the installed builder.
97
*<p>
98
* The builder can only be installed if the executing thread is allowed
99
* (by the security manager's checkSetFactory() method) to do so.
100
* Once installed, the builder cannot be replaced.
101
*
102
* @param builder The factory builder to install. If null, no builder
103
* is installed.
104
* @throws SecurityException builder cannot be installed
105
* for security reasons.
106
* @throws NamingException builder cannot be installed for
107
* a non-security-related reason.
108
* @throws IllegalStateException If a factory has already been installed.
109
* @see #getObjectInstance
110
* @see ObjectFactory
111
* @see ObjectFactoryBuilder
112
* @see java.lang.SecurityManager#checkSetFactory
113
*/
114
public static synchronized void setObjectFactoryBuilder(
115
ObjectFactoryBuilder builder) throws NamingException {
116
if (object_factory_builder != null)
117
throw new IllegalStateException("ObjectFactoryBuilder already set");
118
119
@SuppressWarnings("removal")
120
SecurityManager security = System.getSecurityManager();
121
if (security != null) {
122
security.checkSetFactory();
123
}
124
object_factory_builder = builder;
125
}
126
127
/**
128
* Used for accessing object factory builder.
129
*/
130
static synchronized ObjectFactoryBuilder getObjectFactoryBuilder() {
131
return object_factory_builder;
132
}
133
134
135
/**
136
* Retrieves the ObjectFactory for the object identified by a reference,
137
* using the reference's factory class name and factory codebase
138
* to load in the factory's class.
139
* @param ref The non-null reference to use.
140
* @param factoryName The non-null class name of the factory.
141
* @return The object factory for the object identified by ref; null
142
* if unable to load the factory.
143
*/
144
static ObjectFactory getObjectFactoryFromReference(
145
Reference ref, String factoryName)
146
throws IllegalAccessException,
147
InstantiationException,
148
MalformedURLException {
149
Class<?> clas = null;
150
151
// Try to use current class loader
152
try {
153
clas = helper.loadClassWithoutInit(factoryName);
154
// Validate factory's class with the objects factory serial filter
155
if (!ObjectFactoriesFilter.canInstantiateObjectsFactory(clas)) {
156
return null;
157
}
158
} catch (ClassNotFoundException e) {
159
// ignore and continue
160
// e.printStackTrace();
161
}
162
// All other exceptions are passed up.
163
164
// Not in class path; try to use codebase
165
String codebase;
166
if (clas == null &&
167
(codebase = ref.getFactoryClassLocation()) != null) {
168
try {
169
clas = helper.loadClass(factoryName, codebase);
170
// Validate factory's class with the objects factory serial filter
171
if (clas == null ||
172
!ObjectFactoriesFilter.canInstantiateObjectsFactory(clas)) {
173
return null;
174
}
175
} catch (ClassNotFoundException e) {
176
}
177
}
178
179
@SuppressWarnings("deprecation") // Class.newInstance
180
ObjectFactory result = (clas != null) ? (ObjectFactory) clas.newInstance() : null;
181
return result;
182
}
183
184
185
/**
186
* Creates an object using the factories specified in the
187
* {@code Context.OBJECT_FACTORIES} property of the environment
188
* or of the provider resource file associated with {@code nameCtx}.
189
*
190
* @return factory created; null if cannot create
191
*/
192
private static Object createObjectFromFactories(Object obj, Name name,
193
Context nameCtx, Hashtable<?,?> environment) throws Exception {
194
195
FactoryEnumeration factories = ResourceManager.getFactories(
196
Context.OBJECT_FACTORIES, environment, nameCtx);
197
198
if (factories == null)
199
return null;
200
201
// Try each factory until one succeeds
202
ObjectFactory factory;
203
Object answer = null;
204
while (answer == null && factories.hasMore()) {
205
factory = (ObjectFactory)factories.next();
206
answer = factory.getObjectInstance(obj, name, nameCtx, environment);
207
}
208
return answer;
209
}
210
211
private static String getURLScheme(String str) {
212
int colon_posn = str.indexOf(':');
213
int slash_posn = str.indexOf('/');
214
215
if (colon_posn > 0 && (slash_posn == -1 || colon_posn < slash_posn))
216
return str.substring(0, colon_posn);
217
return null;
218
}
219
220
/**
221
* Creates an instance of an object for the specified object
222
* and environment.
223
* <p>
224
* If an object factory builder has been installed, it is used to
225
* create a factory for creating the object.
226
* Otherwise, the following rules are used to create the object:
227
*<ol>
228
* <li>If {@code refInfo} is a {@code Reference}
229
* or {@code Referenceable} containing a factory class name,
230
* use the named factory to create the object.
231
* Return {@code refInfo} if the factory cannot be created.
232
* Under JDK 1.1, if the factory class must be loaded from a location
233
* specified in the reference, a {@code SecurityManager} must have
234
* been installed or the factory creation will fail.
235
* If an exception is encountered while creating the factory,
236
* it is passed up to the caller.
237
* <li>If {@code refInfo} is a {@code Reference} or
238
* {@code Referenceable} with no factory class name,
239
* and the address or addresses are {@code StringRefAddr}s with
240
* address type "URL",
241
* try the URL context factory corresponding to each URL's scheme id
242
* to create the object (see {@code getURLContext()}).
243
* If that fails, continue to the next step.
244
* <li> Use the object factories specified in
245
* the {@code Context.OBJECT_FACTORIES} property of the environment,
246
* and of the provider resource file associated with
247
* {@code nameCtx}, in that order.
248
* The value of this property is a colon-separated list of factory
249
* class names that are tried in order, and the first one that succeeds
250
* in creating an object is the one used.
251
* If none of the factories can be loaded,
252
* return {@code refInfo}.
253
* If an exception is encountered while creating the object, the
254
* exception is passed up to the caller.
255
*</ol>
256
*<p>
257
* Service providers that implement the {@code DirContext}
258
* interface should use
259
* {@code DirectoryManager.getObjectInstance()}, not this method.
260
* Service providers that implement only the {@code Context}
261
* interface should use this method.
262
* <p>
263
* Note that an object factory (an object that implements the ObjectFactory
264
* interface) must be public and must have a public constructor that
265
* accepts no arguments.
266
* In cases where the factory is in a named module then it must be in a
267
* package which is exported by that module to the {@code java.naming}
268
* module.
269
* <p>
270
* The {@code name} and {@code nameCtx} parameters may
271
* optionally be used to specify the name of the object being created.
272
* {@code name} is the name of the object, relative to context
273
* {@code nameCtx}. This information could be useful to the object
274
* factory or to the object implementation.
275
* If there are several possible contexts from which the object
276
* could be named -- as will often be the case -- it is up to
277
* the caller to select one. A good rule of thumb is to select the
278
* "deepest" context available.
279
* If {@code nameCtx} is null, {@code name} is relative
280
* to the default initial context. If no name is being specified, the
281
* {@code name} parameter should be null.
282
*
283
* @param refInfo The possibly null object for which to create an object.
284
* @param name The name of this object relative to {@code nameCtx}.
285
* Specifying a name is optional; if it is
286
* omitted, {@code name} should be null.
287
* @param nameCtx The context relative to which the {@code name}
288
* parameter is specified. If null, {@code name} is
289
* relative to the default initial context.
290
* @param environment The possibly null environment to
291
* be used in the creation of the object factory and the object.
292
* @return An object created using {@code refInfo}; or
293
* {@code refInfo} if an object cannot be created using
294
* the algorithm described above.
295
* @throws NamingException if a naming exception was encountered
296
* while attempting to get a URL context, or if one of the
297
* factories accessed throws a NamingException.
298
* @throws Exception if one of the factories accessed throws an
299
* exception, or if an error was encountered while loading
300
* and instantiating the factory and object classes.
301
* A factory should only throw an exception if it does not want
302
* other factories to be used in an attempt to create an object.
303
* See ObjectFactory.getObjectInstance().
304
* @see #getURLContext
305
* @see ObjectFactory
306
* @see ObjectFactory#getObjectInstance
307
*/
308
public static Object
309
getObjectInstance(Object refInfo, Name name, Context nameCtx,
310
Hashtable<?,?> environment)
311
throws Exception
312
{
313
314
ObjectFactory factory;
315
316
// Use builder if installed
317
ObjectFactoryBuilder builder = getObjectFactoryBuilder();
318
if (builder != null) {
319
// builder must return non-null factory
320
factory = builder.createObjectFactory(refInfo, environment);
321
return factory.getObjectInstance(refInfo, name, nameCtx,
322
environment);
323
}
324
325
// Use reference if possible
326
Reference ref = null;
327
if (refInfo instanceof Reference) {
328
ref = (Reference) refInfo;
329
} else if (refInfo instanceof Referenceable) {
330
ref = ((Referenceable)(refInfo)).getReference();
331
}
332
333
Object answer;
334
335
if (ref != null) {
336
String f = ref.getFactoryClassName();
337
if (f != null) {
338
// if reference identifies a factory, use exclusively
339
340
factory = getObjectFactoryFromReference(ref, f);
341
if (factory != null) {
342
return factory.getObjectInstance(ref, name, nameCtx,
343
environment);
344
}
345
// No factory found, so return original refInfo.
346
// Will reach this point if factory class is not in
347
// class path and reference does not contain a URL for it
348
return refInfo;
349
350
} else {
351
// if reference has no factory, check for addresses
352
// containing URLs
353
354
answer = processURLAddrs(ref, name, nameCtx, environment);
355
if (answer != null) {
356
return answer;
357
}
358
}
359
}
360
361
// try using any specified factories
362
answer =
363
createObjectFromFactories(refInfo, name, nameCtx, environment);
364
return (answer != null) ? answer : refInfo;
365
}
366
367
/*
368
* Ref has no factory. For each address of type "URL", try its URL
369
* context factory. Returns null if unsuccessful in creating and
370
* invoking a factory.
371
*/
372
static Object processURLAddrs(Reference ref, Name name, Context nameCtx,
373
Hashtable<?,?> environment)
374
throws NamingException {
375
376
for (int i = 0; i < ref.size(); i++) {
377
RefAddr addr = ref.get(i);
378
if (addr instanceof StringRefAddr &&
379
addr.getType().equalsIgnoreCase("URL")) {
380
381
String url = (String)addr.getContent();
382
Object answer = processURL(url, name, nameCtx, environment);
383
if (answer != null) {
384
return answer;
385
}
386
}
387
}
388
return null;
389
}
390
391
private static Object processURL(Object refInfo, Name name,
392
Context nameCtx, Hashtable<?,?> environment)
393
throws NamingException {
394
Object answer;
395
396
// If refInfo is a URL string, try to use its URL context factory
397
// If no context found, continue to try object factories.
398
if (refInfo instanceof String) {
399
String url = (String)refInfo;
400
String scheme = getURLScheme(url);
401
if (scheme != null) {
402
answer = getURLObject(scheme, refInfo, name, nameCtx,
403
environment);
404
if (answer != null) {
405
return answer;
406
}
407
}
408
}
409
410
// If refInfo is an array of URL strings,
411
// try to find a context factory for any one of its URLs.
412
// If no context found, continue to try object factories.
413
if (refInfo instanceof String[]) {
414
String[] urls = (String[])refInfo;
415
for (int i = 0; i <urls.length; i++) {
416
String scheme = getURLScheme(urls[i]);
417
if (scheme != null) {
418
answer = getURLObject(scheme, refInfo, name, nameCtx,
419
environment);
420
if (answer != null)
421
return answer;
422
}
423
}
424
}
425
return null;
426
}
427
428
429
/**
430
* Retrieves a context identified by {@code obj}, using the specified
431
* environment.
432
* Used by ContinuationContext.
433
*
434
* @param obj The object identifying the context.
435
* @param name The name of the context being returned, relative to
436
* {@code nameCtx}, or null if no name is being
437
* specified.
438
* See the {@code getObjectInstance} method for
439
* details.
440
* @param nameCtx The context relative to which {@code name} is
441
* specified, or null for the default initial context.
442
* See the {@code getObjectInstance} method for
443
* details.
444
* @param environment Environment specifying characteristics of the
445
* resulting context.
446
* @return A context identified by {@code obj}.
447
*
448
* @see #getObjectInstance
449
*/
450
static Context getContext(Object obj, Name name, Context nameCtx,
451
Hashtable<?,?> environment) throws NamingException {
452
Object answer;
453
454
if (obj instanceof Context) {
455
// %%% Ignore environment for now. OK since method not public.
456
return (Context)obj;
457
}
458
459
try {
460
answer = getObjectInstance(obj, name, nameCtx, environment);
461
} catch (NamingException e) {
462
throw e;
463
} catch (Exception e) {
464
NamingException ne = new NamingException();
465
ne.setRootCause(e);
466
throw ne;
467
}
468
469
return (answer instanceof Context)
470
? (Context)answer
471
: null;
472
}
473
474
// Used by ContinuationContext
475
static Resolver getResolver(Object obj, Name name, Context nameCtx,
476
Hashtable<?,?> environment) throws NamingException {
477
Object answer;
478
479
if (obj instanceof Resolver) {
480
// %%% Ignore environment for now. OK since method not public.
481
return (Resolver)obj;
482
}
483
484
try {
485
answer = getObjectInstance(obj, name, nameCtx, environment);
486
} catch (NamingException e) {
487
throw e;
488
} catch (Exception e) {
489
NamingException ne = new NamingException();
490
ne.setRootCause(e);
491
throw ne;
492
}
493
494
return (answer instanceof Resolver)
495
? (Resolver)answer
496
: null;
497
}
498
499
500
/***************** URL Context implementations ***************/
501
502
/**
503
* Creates a context for the given URL scheme id.
504
* <p>
505
* The resulting context is for resolving URLs of the
506
* scheme {@code scheme}. The resulting context is not tied
507
* to a specific URL. It is able to handle arbitrary URLs with
508
* the specified scheme.
509
*<p>
510
* The class name of the factory that creates the resulting context
511
* has the naming convention <i>scheme-id</i>URLContextFactory
512
* (e.g. "ftpURLContextFactory" for the "ftp" scheme-id),
513
* in the package specified as follows.
514
* The {@code Context.URL_PKG_PREFIXES} environment property (which
515
* may contain values taken from system properties,
516
* or application resource files)
517
* contains a colon-separated list of package prefixes.
518
* Each package prefix in
519
* the property is tried in the order specified to load the factory class.
520
* The default package prefix is "com.sun.jndi.url" (if none of the
521
* specified packages work, this default is tried).
522
* The complete package name is constructed using the package prefix,
523
* concatenated with the scheme id.
524
*<p>
525
* For example, if the scheme id is "ldap", and the
526
* {@code Context.URL_PKG_PREFIXES} property
527
* contains "com.widget:com.wiz.jndi",
528
* the naming manager would attempt to load the following classes
529
* until one is successfully instantiated:
530
*<ul>
531
* <li>com.widget.ldap.ldapURLContextFactory
532
* <li>com.wiz.jndi.ldap.ldapURLContextFactory
533
* <li>com.sun.jndi.url.ldap.ldapURLContextFactory
534
*</ul>
535
* If none of the package prefixes work, null is returned.
536
*<p>
537
* If a factory is instantiated, it is invoked with the following
538
* parameters to produce the resulting context.
539
* <p>
540
* {@code factory.getObjectInstance(null, environment);}
541
* <p>
542
* For example, invoking getObjectInstance() as shown above
543
* on a LDAP URL context factory would return a
544
* context that can resolve LDAP urls
545
* (e.g. "ldap://ldap.wiz.com/o=wiz,c=us",
546
* "ldap://ldap.umich.edu/o=umich,c=us", ...).
547
*<p>
548
* Note that an object factory (an object that implements the ObjectFactory
549
* interface) must be public and must have a public constructor that
550
* accepts no arguments.
551
* In cases where the factory is in a named module then it must be in a
552
* package which is exported by that module to the {@code java.naming}
553
* module.
554
*
555
* @param scheme The non-null scheme-id of the URLs supported by the context.
556
* @param environment The possibly null environment properties to be
557
* used in the creation of the object factory and the context.
558
* @return A context for resolving URLs with the
559
* scheme id {@code scheme};
560
* {@code null} if the factory for creating the
561
* context is not found.
562
* @throws NamingException If a naming exception occurs while creating
563
* the context.
564
* @see #getObjectInstance
565
* @see ObjectFactory#getObjectInstance
566
*/
567
public static Context getURLContext(String scheme,
568
Hashtable<?,?> environment)
569
throws NamingException
570
{
571
// pass in 'null' to indicate creation of generic context for scheme
572
// (i.e. not specific to a URL).
573
574
Object answer = getURLObject(scheme, null, null, null, environment);
575
if (answer instanceof Context) {
576
return (Context)answer;
577
} else {
578
return null;
579
}
580
}
581
582
private static final String defaultPkgPrefix = "com.sun.jndi.url";
583
584
/**
585
* Creates an object for the given URL scheme id using
586
* the supplied urlInfo.
587
* <p>
588
* If urlInfo is null, the result is a context for resolving URLs
589
* with the scheme id 'scheme'.
590
* If urlInfo is a URL, the result is a context named by the URL.
591
* Names passed to this context is assumed to be relative to this
592
* context (i.e. not a URL). For example, if urlInfo is
593
* "ldap://ldap.wiz.com/o=Wiz,c=us", the resulting context will
594
* be that pointed to by "o=Wiz,c=us" on the server 'ldap.wiz.com'.
595
* Subsequent names that can be passed to this context will be
596
* LDAP names relative to this context (e.g. cn="Barbs Jensen").
597
* If urlInfo is an array of URLs, the URLs are assumed
598
* to be equivalent in terms of the context to which they refer.
599
* The resulting context is like that of the single URL case.
600
* If urlInfo is of any other type, that is handled by the
601
* context factory for the URL scheme.
602
* @param scheme the URL scheme id for the context
603
* @param urlInfo information used to create the context
604
* @param name name of this object relative to {@code nameCtx}
605
* @param nameCtx Context whose provider resource file will be searched
606
* for package prefix values (or null if none)
607
* @param environment Environment properties for creating the context
608
* @see javax.naming.InitialContext
609
*/
610
private static Object getURLObject(String scheme, Object urlInfo,
611
Name name, Context nameCtx,
612
Hashtable<?,?> environment)
613
throws NamingException {
614
615
// e.g. "ftpURLContextFactory"
616
ObjectFactory factory = (ObjectFactory)ResourceManager.getFactory(
617
Context.URL_PKG_PREFIXES, environment, nameCtx,
618
"." + scheme + "." + scheme + "URLContextFactory", defaultPkgPrefix);
619
620
if (factory == null)
621
return null;
622
623
// Found object factory
624
try {
625
return factory.getObjectInstance(urlInfo, name, nameCtx, environment);
626
} catch (NamingException e) {
627
throw e;
628
} catch (Exception e) {
629
NamingException ne = new NamingException();
630
ne.setRootCause(e);
631
throw ne;
632
}
633
634
}
635
636
637
// ------------ Initial Context Factory Stuff
638
private static InitialContextFactoryBuilder initctx_factory_builder = null;
639
640
/**
641
* Use this method for accessing initctx_factory_builder while
642
* inside an unsynchronized method.
643
*/
644
private static synchronized InitialContextFactoryBuilder
645
getInitialContextFactoryBuilder() {
646
return initctx_factory_builder;
647
}
648
649
/**
650
* Creates an initial context using the specified environment
651
* properties.
652
* <p>
653
* This is done as follows:
654
* <ul>
655
* <li>If an InitialContextFactoryBuilder has been installed,
656
* it is used to create the factory for creating the initial
657
* context</li>
658
* <li>Otherwise, the class specified in the
659
* {@code Context.INITIAL_CONTEXT_FACTORY} environment property
660
* is used
661
* <ul>
662
* <li>First, the {@linkplain java.util.ServiceLoader ServiceLoader}
663
* mechanism tries to locate an {@code InitialContextFactory}
664
* provider using the current thread's context class loader</li>
665
* <li>Failing that, this implementation tries to locate a suitable
666
* {@code InitialContextFactory} using a built-in mechanism
667
* <br>
668
* (Note that an initial context factory (an object that implements
669
* the InitialContextFactory interface) must be public and must have
670
* a public constructor that accepts no arguments.
671
* In cases where the factory is in a named module then it must
672
* be in a package which is exported by that module to the
673
* {@code java.naming} module.)</li>
674
* </ul>
675
* </li>
676
* </ul>
677
* @param env The possibly null environment properties used when
678
* creating the context.
679
* @return A non-null initial context.
680
* @throws NoInitialContextException If the
681
* {@code Context.INITIAL_CONTEXT_FACTORY} property
682
* is not found or names a nonexistent
683
* class or a class that cannot be instantiated,
684
* or if the initial context could not be created for some other
685
* reason.
686
* @throws NamingException If some other naming exception was encountered.
687
* @see javax.naming.InitialContext
688
* @see javax.naming.directory.InitialDirContext
689
*/
690
@SuppressWarnings("removal")
691
public static Context getInitialContext(Hashtable<?,?> env)
692
throws NamingException {
693
ClassLoader loader;
694
InitialContextFactory factory = null;
695
696
InitialContextFactoryBuilder builder = getInitialContextFactoryBuilder();
697
if (builder == null) {
698
// No builder installed, use property
699
// Get initial context factory class name
700
701
String className = env != null ?
702
(String)env.get(Context.INITIAL_CONTEXT_FACTORY) : null;
703
if (className == null) {
704
NoInitialContextException ne = new NoInitialContextException(
705
"Need to specify class name in environment or system " +
706
"property, or in an application resource file: " +
707
Context.INITIAL_CONTEXT_FACTORY);
708
throw ne;
709
}
710
711
if (System.getSecurityManager() == null) {
712
loader = Thread.currentThread().getContextClassLoader();
713
if (loader == null) loader = ClassLoader.getSystemClassLoader();
714
} else {
715
PrivilegedAction<ClassLoader> pa = () -> {
716
ClassLoader cl = Thread.currentThread().getContextClassLoader();
717
return (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
718
};
719
loader = AccessController.doPrivileged(pa);
720
}
721
722
var key = FACTORIES_CACHE.sub(className);
723
try {
724
factory = key.computeIfAbsent(loader, (ld, ky) -> getFactory(ky.key()));
725
} catch (FactoryInitializationError e) {
726
throw e.getCause();
727
}
728
} else {
729
factory = builder.createInitialContextFactory(env);
730
}
731
732
return factory.getInitialContext(env);
733
}
734
735
private static InitialContextFactory getFactory(String className) {
736
InitialContextFactory factory;
737
try {
738
ServiceLoader<InitialContextFactory> loader =
739
ServiceLoader.load(InitialContextFactory.class);
740
741
factory = loader
742
.stream()
743
.filter(p -> p.type().getName().equals(className))
744
.findFirst()
745
.map(ServiceLoader.Provider::get)
746
.orElse(null);
747
} catch (ServiceConfigurationError e) {
748
NoInitialContextException ne =
749
new NoInitialContextException(
750
"Cannot load initial context factory "
751
+ "'" + className + "'");
752
ne.setRootCause(e);
753
throw new FactoryInitializationError(ne);
754
}
755
756
if (factory == null) {
757
try {
758
@SuppressWarnings("deprecation")
759
Object o = helper.loadClass(className).newInstance();
760
factory = (InitialContextFactory) o;
761
} catch (Exception e) {
762
NoInitialContextException ne =
763
new NoInitialContextException(
764
"Cannot instantiate class: " + className);
765
ne.setRootCause(e);
766
throw new FactoryInitializationError(ne);
767
}
768
}
769
return factory;
770
}
771
772
773
/**
774
* Sets the InitialContextFactory builder to be builder.
775
*
776
*<p>
777
* The builder can only be installed if the executing thread is allowed by
778
* the security manager to do so. Once installed, the builder cannot
779
* be replaced.
780
* @param builder The initial context factory builder to install. If null,
781
* no builder is set.
782
* @throws SecurityException builder cannot be installed for security
783
* reasons.
784
* @throws NamingException builder cannot be installed for
785
* a non-security-related reason.
786
* @throws IllegalStateException If a builder was previous installed.
787
* @see #hasInitialContextFactoryBuilder
788
* @see java.lang.SecurityManager#checkSetFactory
789
*/
790
public static synchronized void setInitialContextFactoryBuilder(
791
InitialContextFactoryBuilder builder)
792
throws NamingException {
793
if (initctx_factory_builder != null)
794
throw new IllegalStateException(
795
"InitialContextFactoryBuilder already set");
796
797
@SuppressWarnings("removal")
798
SecurityManager security = System.getSecurityManager();
799
if (security != null) {
800
security.checkSetFactory();
801
}
802
initctx_factory_builder = builder;
803
}
804
805
/**
806
* Determines whether an initial context factory builder has
807
* been set.
808
* @return true if an initial context factory builder has
809
* been set; false otherwise.
810
* @see #setInitialContextFactoryBuilder
811
*/
812
public static boolean hasInitialContextFactoryBuilder() {
813
return (getInitialContextFactoryBuilder() != null);
814
}
815
816
// ----- Continuation Context Stuff
817
818
/**
819
* Constant that holds the name of the environment property into
820
* which {@code getContinuationContext()} stores the value of its
821
* {@code CannotProceedException} parameter.
822
* This property is inherited by the continuation context, and may
823
* be used by that context's service provider to inspect the
824
* fields of the exception.
825
*<p>
826
* The value of this constant is "java.naming.spi.CannotProceedException".
827
*
828
* @see #getContinuationContext
829
* @since 1.3
830
*/
831
public static final String CPE = "java.naming.spi.CannotProceedException";
832
833
/**
834
* Creates a context in which to continue a context operation.
835
*<p>
836
* In performing an operation on a name that spans multiple
837
* namespaces, a context from one naming system may need to pass
838
* the operation on to the next naming system. The context
839
* implementation does this by first constructing a
840
* {@code CannotProceedException} containing information
841
* pinpointing how far it has proceeded. It then obtains a
842
* continuation context from JNDI by calling
843
* {@code getContinuationContext}. The context
844
* implementation should then resume the context operation by
845
* invoking the same operation on the continuation context, using
846
* the remainder of the name that has not yet been resolved.
847
*<p>
848
* Before making use of the {@code cpe} parameter, this method
849
* updates the environment associated with that object by setting
850
* the value of the property <a href="#CPE">{@code CPE}</a>
851
* to {@code cpe}. This property will be inherited by the
852
* continuation context, and may be used by that context's
853
* service provider to inspect the fields of this exception.
854
*
855
* @param cpe
856
* The non-null exception that triggered this continuation.
857
* @return A non-null Context object for continuing the operation.
858
* @throws NamingException If a naming exception occurred.
859
*/
860
@SuppressWarnings("unchecked")
861
public static Context getContinuationContext(CannotProceedException cpe)
862
throws NamingException {
863
864
Hashtable<Object,Object> env = (Hashtable<Object,Object>)cpe.getEnvironment();
865
if (env == null) {
866
env = new Hashtable<>(7);
867
} else {
868
// Make a (shallow) copy of the environment.
869
env = (Hashtable<Object,Object>)env.clone();
870
}
871
env.put(CPE, cpe);
872
873
ContinuationContext cctx = new ContinuationContext(cpe, env);
874
return cctx.getTargetContext();
875
}
876
877
// ------------ State Factory Stuff
878
879
/**
880
* Retrieves the state of an object for binding.
881
* <p>
882
* Service providers that implement the {@code DirContext} interface
883
* should use {@code DirectoryManager.getStateToBind()}, not this method.
884
* Service providers that implement only the {@code Context} interface
885
* should use this method.
886
*<p>
887
* This method uses the specified state factories in
888
* the {@code Context.STATE_FACTORIES} property from the environment
889
* properties, and from the provider resource file associated with
890
* {@code nameCtx}, in that order.
891
* The value of this property is a colon-separated list of factory
892
* class names that are tried in order, and the first one that succeeds
893
* in returning the object's state is the one used.
894
* If no object's state can be retrieved in this way, return the
895
* object itself.
896
* If an exception is encountered while retrieving the state, the
897
* exception is passed up to the caller.
898
* <p>
899
* Note that a state factory
900
* (an object that implements the StateFactory
901
* interface) must be public and must have a public constructor that
902
* accepts no arguments.
903
* In cases where the factory is in a named module then it must be in a
904
* package which is exported by that module to the {@code java.naming}
905
* module.
906
* <p>
907
* The {@code name} and {@code nameCtx} parameters may
908
* optionally be used to specify the name of the object being created.
909
* See the description of "Name and Context Parameters" in
910
* {@link ObjectFactory#getObjectInstance
911
* ObjectFactory.getObjectInstance()}
912
* for details.
913
* <p>
914
* This method may return a {@code Referenceable} object. The
915
* service provider obtaining this object may choose to store it
916
* directly, or to extract its reference (using
917
* {@code Referenceable.getReference()}) and store that instead.
918
*
919
* @param obj The non-null object for which to get state to bind.
920
* @param name The name of this object relative to {@code nameCtx},
921
* or null if no name is specified.
922
* @param nameCtx The context relative to which the {@code name}
923
* parameter is specified, or null if {@code name} is
924
* relative to the default initial context.
925
* @param environment The possibly null environment to
926
* be used in the creation of the state factory and
927
* the object's state.
928
* @return The non-null object representing {@code obj}'s state for
929
* binding. It could be the object ({@code obj}) itself.
930
* @throws NamingException If one of the factories accessed throws an
931
* exception, or if an error was encountered while loading
932
* and instantiating the factory and object classes.
933
* A factory should only throw an exception if it does not want
934
* other factories to be used in an attempt to create an object.
935
* See {@code StateFactory.getStateToBind()}.
936
* @see StateFactory
937
* @see StateFactory#getStateToBind
938
* @see DirectoryManager#getStateToBind
939
* @since 1.3
940
*/
941
public static Object
942
getStateToBind(Object obj, Name name, Context nameCtx,
943
Hashtable<?,?> environment)
944
throws NamingException
945
{
946
947
FactoryEnumeration factories = ResourceManager.getFactories(
948
Context.STATE_FACTORIES, environment, nameCtx);
949
950
if (factories == null) {
951
return obj;
952
}
953
954
// Try each factory until one succeeds
955
StateFactory factory;
956
Object answer = null;
957
while (answer == null && factories.hasMore()) {
958
factory = (StateFactory)factories.next();
959
answer = factory.getStateToBind(obj, name, nameCtx, environment);
960
}
961
962
return (answer != null) ? answer : obj;
963
}
964
965
/**
966
* Thrown when an error is encountered while loading and instantiating the
967
* context factory classes.
968
*/
969
private static class FactoryInitializationError extends Error {
970
@java.io.Serial
971
static final long serialVersionUID = -5805552256848841560L;
972
973
private FactoryInitializationError(NoInitialContextException cause) {
974
super(cause);
975
}
976
977
@Override
978
public NoInitialContextException getCause() {
979
return (NoInitialContextException) super.getCause();
980
}
981
}
982
}
983
984