-
Notifications
You must be signed in to change notification settings - Fork 138
/
GlassfishNamingManagerImpl.java
883 lines (740 loc) · 33.5 KB
/
GlassfishNamingManagerImpl.java
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
/*
* Copyright (c) 2022 Contributors to the Eclipse Foundation
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.enterprise.naming.impl;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import java.io.Serializable;
import java.lang.System.Logger;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NameAlreadyBoundException;
import javax.naming.NameClassPair;
import javax.naming.NameNotFoundException;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.NotContextException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import javax.naming.spi.NamingManager;
import org.glassfish.api.invocation.ComponentInvocation;
import org.glassfish.api.invocation.InvocationManager;
import org.glassfish.api.naming.GlassfishNamingManager;
import org.glassfish.api.naming.JNDIBinding;
import org.glassfish.api.naming.NamingObjectProxy;
import org.glassfish.api.naming.SimpleJndiName;
import org.glassfish.hk2.api.ServiceLocator;
import org.jvnet.hk2.annotations.Service;
import org.omg.CORBA.ORB;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.TRACE;
import static java.lang.System.Logger.Level.WARNING;
import static java.util.Objects.requireNonNull;
import static org.glassfish.api.naming.SimpleJndiName.JNDI_CTX_JAVA;
import static org.glassfish.api.naming.SimpleJndiName.JNDI_CTX_JAVA_APP;
import static org.glassfish.api.naming.SimpleJndiName.JNDI_CTX_JAVA_APP_NS_ID;
import static org.glassfish.api.naming.SimpleJndiName.JNDI_CTX_JAVA_COMPONENT;
import static org.glassfish.api.naming.SimpleJndiName.JNDI_CTX_JAVA_COMPONENT_NS_ID;
import static org.glassfish.api.naming.SimpleJndiName.JNDI_CTX_JAVA_MODULE;
import static org.glassfish.api.naming.SimpleJndiName.JNDI_CTX_JAVA_MODULE_NS_ID;
/**
* This is the manager that handles all naming operations including
* publishObject as well as binding environment props, resource and ejb
* references in the namespace.
*/
@Service
@Singleton
public final class GlassfishNamingManagerImpl implements GlassfishNamingManager {
public static final String IIOPOBJECT_FACTORY = "com.sun.enterprise.naming.util.IIOPObjectFactory";
private static final Logger LOG = System.getLogger(GlassfishNamingManagerImpl.class.getName());
@Inject
private ServiceLocator habitat;
private final InitialContext initialContext;
private final NameParser nameParser = new SerialNameParser();
private final NamespacesMap<String> componentNamespaces;
private final NamespacesMap<String> appNamespaces;
private final NamespacesMap<AppModuleKey> moduleNamespaces;
private final Map<String, ComponentIdInfo> componentIdInfo;
private InvocationManager invMgr;
// FIXME: cosContext has nothing to do with the rest of the class.
private Context cosContext;
/**
* Create the naming manager. Creates a new initial context.
*
* @throws NamingException if the creation of the {@link InitialContext} instance failed.
*/
public GlassfishNamingManagerImpl() throws NamingException {
this(new InitialContext());
}
/**
* Create the naming manager.
*/
public GlassfishNamingManagerImpl(InitialContext initialContext) {
this.initialContext = initialContext;
this.componentNamespaces = new NamespacesMap<>(SimpleJndiName.JNDI_CTX_JAVA_COMPONENT);
this.appNamespaces = new NamespacesMap<>(JNDI_CTX_JAVA_APP);
this.moduleNamespaces = new NamespacesMap<>(SimpleJndiName.JNDI_CTX_JAVA_MODULE);
this.componentIdInfo = new HashMap<>();
JavaURLContext.setNamingManager(this);
}
// Used only for unit testing
void setInvocationManager(final InvocationManager invMgr) {
this.invMgr = invMgr;
}
/**
* Get the initial naming context.
*/
@Override
public Context getInitialContext() {
return initialContext;
}
public NameParser getNameParser() {
return nameParser;
}
@Override
public Remote initializeRemoteNamingSupport(ORB orb) throws NamingException {
Remote remoteProvider;
try {
// Now that we have an ORB, initialize the CosNaming service
// and set it on the server's naming service.
Hashtable<Object, Object> cosNamingEnv = new Hashtable<>();
cosNamingEnv.put("java.naming.factory.initial", "org.glassfish.jndi.cosnaming.CNCtxFactory");
cosNamingEnv.put("java.naming.corba.orb", orb);
cosContext = new InitialContext(cosNamingEnv);
ProviderManager pm = ProviderManager.getProviderManager();
// Initialize RemoteSerialProvider. This allows access to the naming
// service from clients.
remoteProvider = pm.initRemoteProvider(orb);
} catch(RemoteException re) {
NamingException ne = new NamingException("Exception during remote naming initialization");
ne.initCause(ne);
throw ne;
}
return remoteProvider;
}
private Context getCosContext() {
return requireNonNull(cosContext, "cosContext was not initialized by initializeRemoteNamingSupport method");
}
@Override
public void publishObject(SimpleJndiName name, Object obj, boolean rebind) throws NamingException {
publishObject(name.toName(), obj, rebind);
}
@Override
public void publishObject(Name name, Object obj, boolean rebind) throws NamingException {
LOG.log(DEBUG, "publishObject(name={0}, obj={1}, rebind={2})", name, obj, rebind);
if (rebind) {
initialContext.rebind(name, obj);
} else {
initialContext.bind(name, obj);
}
}
@Override
public void publishCosNamingObject(SimpleJndiName name, Object obj, boolean rebind) throws NamingException {
Name nameObj = name.toName();
// Create any COS naming sub-contexts in name
// that don't already exist.
createSubContexts(nameObj, getCosContext());
if (rebind) {
getCosContext().rebind(nameObj, obj);
} else {
getCosContext().bind(nameObj, obj);
}
// Bind a reference to it in the SerialContext using
// the same name. This is needed to allow standalone clients
// to lookup the object using the same JNDI name.
// It is also used from bindObjects while populating ejb-refs in
// the java:comp namespace.
StringRefAddr addr = new StringRefAddr("url", name.toString());
Object serialObj = new Reference("reference", addr, IIOPOBJECT_FACTORY, null);
publishObject(name, serialObj, rebind);
}
@Override
public void unpublishObject(SimpleJndiName name) throws NamingException {
initialContext.unbind(name.toName());
}
@Override
public void unpublishCosNamingObject(SimpleJndiName name) throws NamingException {
try {
getCosContext().unbind(name.toName());
} catch (NamingException cne) {
LOG.log(WARNING, "Error during CosNaming.unbind for name: " + name, cne);
}
initialContext.unbind(name.toName());
}
@Override
public void unpublishObject(Name name) throws NamingException {
this.unpublishObject(SimpleJndiName.of(name));
}
/**
* Create any sub-contexts in name that don't already exist.
*
* @param name Name containing sub-contexts to create
* @param rootCtx in which sub-contexts should be created
* @throws Exception
*/
private void createSubContexts(Name name, Context rootCtx) throws NamingException {
int numSubContexts = name.size() - 1;
Context currentCtx = rootCtx;
for (int subCtxIndex = 0; subCtxIndex < numSubContexts; subCtxIndex++) {
String subCtxName = name.get(subCtxIndex);
try {
Object obj = currentCtx.lookup(subCtxName);
if (obj == null) {
// Doesn't exist so create it.
currentCtx = currentCtx.createSubcontext(subCtxName);
} else if (obj instanceof Context) {
// OK -- no need to create it.
currentCtx = (Context) obj;
} else {
// Context name clashes with existing object.
throw new NameAlreadyBoundException(subCtxName);
}
}
catch (NameNotFoundException e) {
// Doesn't exist so create it.
currentCtx = currentCtx.createSubcontext(subCtxName);
}
} // End for -- each sub-context
}
private JavaNamespace getComponentNamespace(String componentId) {
// Note: HashMap is not synchronized. The namespace is populated
// at deployment time by a single thread, and then on there are
// no structural modifications (i.e. no keys added/removed).
// So the namespace doesnt need to be synchronized.
JavaNamespace namespace = componentNamespaces.get(componentId);
if (namespace == null) {
namespace = new JavaNamespace(componentId, "comp");
componentNamespaces.put(componentId, namespace);
}
return namespace;
}
private JavaNamespace getModuleNamespace(AppModuleKey appModuleKey) throws NamingException {
if (appModuleKey.getAppName() == null || appModuleKey.getModuleName() == null) {
throw new NamingException("Invalid appModuleKey " + appModuleKey);
}
// Note: HashMap is not synchronized. The namespace is populated
// at deployment time by a single thread, and then on there are
// no structural modifications (i.e. no keys added/removed).
// So the namespace doesnt need to be synchronized.
JavaNamespace namespace = moduleNamespaces.get(appModuleKey);
if (namespace == null) {
namespace = new JavaNamespace(appModuleKey.toString(), "module");
moduleNamespaces.put(appModuleKey, namespace);
}
return namespace;
}
@Override
public <T> T lookupFromAppNamespace(String appName, SimpleJndiName name, Hashtable<?, ?> env) throws NamingException {
LOG.log(TRACE, "lookupFromAppNamespace(appName={0}, name={1}, env)", appName, name);
Map<SimpleJndiName, Object> namespace = getAppNamespace(appName);
return lookupFromNamespace(name, namespace, env);
}
@Override
public <T> T lookupFromModuleNamespace(String appName, String moduleName, SimpleJndiName name, Hashtable<?, ?> env)
throws NamingException {
LOG.log(TRACE, "lookupFromModuleNamespace(appName={0}, moduleName={1}, name={2}, env)", appName, moduleName,
name);
AppModuleKey appModuleKey = new AppModuleKey(appName, moduleName);
Map<SimpleJndiName, Object> namespace = getModuleNamespace(appModuleKey);
return lookupFromNamespace(name, namespace, env);
}
private <T> T getObjectInstance(SimpleJndiName name, Object obj, Hashtable<?, ?> env) throws Exception {
if (env == null) {
env = new Hashtable<>();
}
return (T) NamingManager.getObjectInstance(obj, name.toName(), null, env);
}
private JavaNamespace getAppNamespace(String appName) throws NamingException {
if (appName == null) {
throw new NamingException("Null appName");
}
// Note: HashMap is not synchronized. The namespace is populated
// at deployment time by a single thread, and then on there are
// no structural modifications (i.e. no keys added/removed).
// So the namespace doesnt need to be synchronized.
JavaNamespace namespace = appNamespaces.get(appName);
if (namespace == null) {
namespace = new JavaNamespace(appName, "app");
appNamespaces.put(appName, namespace);
}
return namespace;
}
private JavaNamespace getNamespace(String componentId, SimpleJndiName logicalJndiName) throws NamingException {
LOG.log(TRACE, "getNamespace(componentId={0}, logicalJndiName={1})", componentId, logicalJndiName);
ComponentIdInfo info = componentIdInfo.get(componentId);
if (info == null) {
return getComponentNamespace(componentId);
}
return getNamespace(info.appName, info.moduleName, componentId, logicalJndiName);
}
private JavaNamespace getNamespace(String appName, String moduleName, String componentId,
SimpleJndiName logicalJndiName) throws NamingException {
if (logicalJndiName.isJavaModule()) {
return getModuleNamespace(new AppModuleKey(appName, moduleName));
} else if (logicalJndiName.isJavaApp()) {
return getAppNamespace(appName);
} else {
return getComponentNamespace(componentId);
}
}
/**
* This method binds them in a java:namespace.
*/
private void bindToNamespace(JavaNamespace namespace, SimpleJndiName logicalJndiName, Object value)
throws NamingException {
LOG.log(DEBUG, "bindToNamespace(namespace={0}, logicalJndiName={1}, value={2})", namespace.name, logicalJndiName, value);
if (namespace.put(logicalJndiName, value) != null) {
LOG.log(WARNING, "Naming binding already exists for {0} in namespace {1}", logicalJndiName, namespace);
}
bindIntermediateContexts(namespace, logicalJndiName);
}
private boolean existsInNamespace(Map<SimpleJndiName, ?> namespace, SimpleJndiName logicalJndiName) {
return namespace.containsKey(logicalJndiName);
}
@Override
public void bindToComponentNamespace(String appName, String moduleName, String componentId,
boolean treatComponentAsModule, Collection<? extends JNDIBinding> bindings) throws NamingException {
LOG.log(DEBUG,
"bindToComponentNamespace(appName={0}, moduleName={1}, componentId={2}, treatComponentAsModule={3}, bindings={4})",
appName, moduleName, componentId, treatComponentAsModule, bindings);
// These are null in rare cases, e.g. default web app.
if (appName != null && moduleName != null) {
ComponentIdInfo info = new ComponentIdInfo();
info.appName = appName;
info.moduleName = moduleName;
info.componentId = componentId;
info.treatComponentAsModule = treatComponentAsModule;
componentIdInfo.put(componentId, info);
}
for (JNDIBinding binding : bindings) {
final SimpleJndiName logicalJndiName;
if (treatComponentAsModule && binding.getName().isJavaComponent()) {
logicalJndiName = binding.getName().changePrefix(JNDI_CTX_JAVA_MODULE);
} else {
logicalJndiName = binding.getName();
}
final JavaNamespace namespace;
if (logicalJndiName.isJavaComponent()) {
namespace = getComponentNamespace(componentId);
} else if (logicalJndiName.isJavaModule()) {
namespace = getModuleNamespace(new AppModuleKey(appName, moduleName));
} else if (logicalJndiName.isJavaApp()) {
namespace = getAppNamespace(appName);
} else {
namespace = null;
}
if (namespace == null) {
LOG.log(WARNING, "No namespace found for appName={0}, moduleName={1}, componentId={2}", appName,
moduleName, componentId);
return;
}
// FIXME: it is checked inside again, but with warning.
if (!existsInNamespace(namespace, logicalJndiName)) {
bindToNamespace(namespace, logicalJndiName, binding.getValue());
}
}
}
@Override
public void bindToModuleNamespace(String appName, String moduleName, Collection<? extends JNDIBinding> bindings)
throws NamingException {
LOG.log(TRACE, "bindToModuleNamespace(appName={0}, moduleName={1}, bindings={2})", appName, moduleName,
bindings);
AppModuleKey appModuleKey = new AppModuleKey(appName, moduleName);
JavaNamespace namespace = getModuleNamespace(appModuleKey);
for (JNDIBinding binding : bindings) {
SimpleJndiName logicalJndiName = binding.getName();
if (logicalJndiName.isJavaModule()) {
bindToNamespace(namespace, logicalJndiName, binding.getValue());
}
}
}
@Override
public void bindToAppNamespace(String appName, Collection<? extends JNDIBinding> bindings) throws NamingException {
LOG.log(TRACE, "bindToAppNamespace(appName={0}, bindings={1})", appName, bindings);
JavaNamespace namespace = getAppNamespace(appName);
for (JNDIBinding binding : bindings) {
SimpleJndiName logicalJndiName = binding.getName();
if (logicalJndiName.isJavaApp()) {
bindToNamespace(namespace, logicalJndiName, binding.getValue());
}
}
}
private void bindIntermediateContexts(JavaNamespace namespace, SimpleJndiName jndiName)
throws NamingException {
LOG.log(TRACE, "bindIntermediateContexts(namespace={0}, jndiName={1})", namespace.name, jndiName);
// for each component of name, put an entry into namespace
String partialName;
if (jndiName.isJavaComponent()) {
partialName = JNDI_CTX_JAVA_COMPONENT_NS_ID;
} else if (jndiName.isJavaModule()) {
partialName = JNDI_CTX_JAVA_MODULE_NS_ID;
} else if (jndiName.isJavaApp()) {
partialName = JNDI_CTX_JAVA_APP_NS_ID;
} else {
throw new NamingException("Invalid environment namespace name: " + jndiName);
}
String name = jndiName.toString().substring(partialName.length() + 1);
StringTokenizer toks = new StringTokenizer(name, "/", false);
StringBuilder sb = new StringBuilder();
sb.append(partialName);
while (toks.hasMoreTokens()) {
String tok = toks.nextToken();
sb.append('/').append(tok);
final SimpleJndiName nsJndiName = new SimpleJndiName(sb.toString());
if (namespace.get(nsJndiName) == null) {
namespace.put(nsJndiName, new JavaURLContext(nsJndiName, null));
}
}
}
@Override
public void unbindComponentObjects(String componentId) throws NamingException {
LOG.log(DEBUG, "unbindComponentObjects(componentId={0})", componentId);
// remove local namespace cache
componentNamespaces.remove(componentId);
componentIdInfo.remove(componentId);
}
@Override
public void unbindAppObjects(String appName) throws NamingException {
LOG.log(DEBUG, "unbindAppObjects(appName={0})", appName);
appNamespaces.remove(appName);
Iterator<AppModuleKey> keys = moduleNamespaces.keySet().iterator();
while (keys.hasNext()) {
AppModuleKey key = keys.next();
if (key.getAppName().equals(appName)) {
keys.remove();
}
}
}
@Override
public void unbindAppObject(String appName, SimpleJndiName name) throws NamingException {
LOG.log(DEBUG, "unbindAppObject(appName={0}, name={1})", appName, name);
Map<SimpleJndiName, Object> namespaces = appNamespaces.get(appName);
if (namespaces != null) {
namespaces.remove(name);
}
}
@Override
public void unbindModuleObject(String appName, String moduleName, SimpleJndiName name) throws NamingException {
LOG.log(DEBUG, "unbindModuleObject(appName={0}, moduleName={1}, name={2})", appName, moduleName, name);
AppModuleKey appModuleKey = new AppModuleKey(appName, moduleName);
Map<SimpleJndiName, Object> namespaces = moduleNamespaces.get(appModuleKey);
if (namespaces != null) {
namespaces.remove(name);
}
}
/**
* Recreate a context for java:comp/env or one of its sub-contexts given the context name.
*/
@Override
public Context restoreJavaCompEnvContext(SimpleJndiName contextName) throws NamingException {
if (contextName.hasJavaPrefix()) {
return new JavaURLContext(contextName, null);
}
throw new NamingException("Invalid context name [" + contextName + "]. Name must start with java:");
}
public <T> T lookup(SimpleJndiName name) throws NamingException {
final String componentId = getComponentId();
return lookup(componentId, name, initialContext);
}
/**
* This method is called from SerialContext class. The serialContext
* instance that was created by the appclient's Main class is passed so that
* stickiness is preserved. Called from javaURLContext.lookup, for java:comp
* names.
*/
public <T> T lookup(SimpleJndiName name, SerialContext serialContext) throws NamingException {
// initialContext is used as ic in case of PE while
// serialContext is used as ic in case of EE/SE
// Get the component id and namespace to lookup
final Context ic = serialContext == null ? initialContext : serialContext;
final String componentId = getComponentId();
return lookup(componentId, name, ic);
}
/**
* Lookup object for a particular componentId and name.
*/
@Override
public <T> T lookup(String componentId, SimpleJndiName name) throws NamingException {
return lookup(componentId, name, initialContext);
}
private <T> T lookup(String componentId, SimpleJndiName name, Context ctx) throws NamingException {
LOG.log(DEBUG, "lookup(componentId={0}, name={1}, ctx={2})", componentId, name, ctx);
if (!name.hasJavaPrefix() && name.contains(":")) {
// generic jndi names
return (T) initialContext.lookup(name.toName());
}
ComponentIdInfo info = componentIdInfo.get(componentId);
boolean replaceName = info != null && info.treatComponentAsModule && name.isJavaComponent();
final SimpleJndiName replacedName;
if (replaceName) {
replacedName = name.changePrefix(JNDI_CTX_JAVA_MODULE);
} else {
replacedName = name;
}
Map<SimpleJndiName, Object> namespace = getNamespace(componentId, replacedName);
Object obj = namespace.get(replacedName);
if (obj == null) {
throw new NameNotFoundException("No object bound to name " + replacedName + " in namespace " + namespace);
}
if (obj instanceof NamingObjectProxy) {
NamingObjectProxy namingProxy = (NamingObjectProxy) obj;
return namingProxy.create(ctx);
} else if (obj instanceof Context) {
// Need to preserve the original prefix so that further operations
// on the context maintain the correct external view. In the case
// of a replaced java:comp, create a new equivalent javaURLContext
// and return that.
if (replaceName) {
obj = new JavaURLContext(name, null);
}
if (obj instanceof JavaURLContext) {
if (ctx instanceof SerialContext) {
return (T) new JavaURLContext((JavaURLContext) obj, (SerialContext) ctx);
}
return (T) new JavaURLContext((JavaURLContext) obj, null);
}
}
return (T) obj;
}
public NamingEnumeration<NameClassPair> list(SimpleJndiName name) throws NamingException {
ArrayList<SimpleJndiName> list = listNames(name);
return new BindingsIterator<>(this, list.iterator(), true);
}
public NamingEnumeration<Binding> listBindings(SimpleJndiName name) throws NamingException {
ArrayList<SimpleJndiName> list = listNames(name);
return new BindingsIterator<>(this, list.iterator(), false);
}
private ArrayList<SimpleJndiName> listNames(SimpleJndiName name) throws NamingException {
// Get the component id and namespace to lookup
String componentId = getComponentId();
ComponentIdInfo info = componentIdInfo.get(componentId);
boolean replaceName = info != null && info.treatComponentAsModule && name.isJavaComponent();
final SimpleJndiName logicalJndiName;
if (replaceName) {
logicalJndiName = name.changePrefix(JNDI_CTX_JAVA_MODULE);
} else {
logicalJndiName = name;
}
JavaNamespace namespace = getNamespace(componentId, logicalJndiName);
Object obj = namespace.get(logicalJndiName);
if (obj == null) {
throw new NameNotFoundException("No object bound to name " + name + " in namespace " + namespace);
}
if (!(obj instanceof JavaURLContext)) {
throw new NotContextException(name + " cannot be listed");
}
// This iterates over all names in entire component namespace,
// so its a little inefficient. The alternative is to store
// a list of bindings in each javaURLContext instance.
ArrayList<SimpleJndiName> list = new ArrayList<>();
final String logicalNameWithSlash;
if (logicalJndiName.hasSuffix("/")) {
logicalNameWithSlash = logicalJndiName.toString();
} else {
logicalNameWithSlash = logicalJndiName + "/";
}
for (SimpleJndiName key : namespace.keySet()) {
// Check if key begins with name and has only 1 component extra (i.e. no more slashes)
// Make sure keys reflect the original prefix in the case of comp->module replacement
// The search string itself is excluded from the returned list
if (key.hasPrefix(logicalNameWithSlash) && key.toString().indexOf('/', logicalNameWithSlash.length()) == -1
&& !key.toString().equals(logicalNameWithSlash)) {
SimpleJndiName toAdd = replaceName ? key.changePrefix(JNDI_CTX_JAVA_COMPONENT) : key;
list.add(toAdd);
}
}
return list;
}
/**
* Get the component id from the Invocation Manager.
*
* @return the component id as a string.
*/
private String getComponentId() throws NamingException {
final ComponentInvocation ci;
if (invMgr == null) {
ci = habitat.<InvocationManager> getService(InvocationManager.class).getCurrentInvocation();
} else {
ci = invMgr.getCurrentInvocation();
}
if (ci == null) {
throw new NamingException("Invocation exception: Got null ComponentInvocation ");
}
try {
String id = ci.getComponentId();
if (id == null) {
throw new NamingException("Invocation exception: ComponentId is null");
}
return id;
} catch (Throwable th) {
NamingException ine = new NamingException("Invocation exception: " + th);
ine.initCause(th);
throw ine;
}
}
private <T> T lookupFromNamespace(SimpleJndiName name, Map<SimpleJndiName, Object> namespace, Hashtable<?, ?> env)
throws NamingException {
final Object objectOrProxyOrRef = namespace.get(name);
if (objectOrProxyOrRef == null) {
throw new NameNotFoundException("No object bound to name " + name);
}
if (objectOrProxyOrRef instanceof NamingObjectProxy) {
NamingObjectProxy namingProxy = (NamingObjectProxy) objectOrProxyOrRef;
return namingProxy.create(env == null ? initialContext : new InitialContext(env));
} else if (objectOrProxyOrRef instanceof Reference) {
try {
return getObjectInstance(name, objectOrProxyOrRef, env);
} catch (Exception e) {
LOG.log(DEBUG, () -> "Unable to get Object instance from Reference for name [" + name + "]. "
+ "Hence returning the Reference object " + objectOrProxyOrRef, e);
}
}
return (T) objectOrProxyOrRef;
}
private static class AppModuleKey implements Serializable {
private static final long serialVersionUID = -6080646413719869870L;
private final String app;
private final String module;
public AppModuleKey(String appName, String moduleName) {
app = appName;
module = moduleName;
}
public String getAppName() {
return app;
}
public String getModuleName() {
return module;
}
@Override
public boolean equals(Object o) {
if (o != null && o instanceof AppModuleKey) {
AppModuleKey other = (AppModuleKey) o;
return app.equals(other.app) && module.equals(other.module);
}
return false;
}
@Override
public int hashCode() {
return app.hashCode();
}
@Override
public String toString() {
return app + '/' + module;
}
}
private static class ComponentIdInfo {
String appName;
String moduleName;
String componentId;
boolean treatComponentAsModule;
@Override
public String toString() {
return "appName=" + appName + ", module=" + moduleName + ", componentId=" + componentId
+ ", treatComponentAsModule=" + treatComponentAsModule;
}
}
private static class BindingsIterator<T> implements NamingEnumeration<T> {
private final GlassfishNamingManagerImpl nm;
private final Iterator<SimpleJndiName> names;
private final boolean producesNamesOnly;
BindingsIterator(GlassfishNamingManagerImpl nm, Iterator<SimpleJndiName> names, boolean producesNamesOnly) {
this.nm = nm;
this.names = names;
this.producesNamesOnly = producesNamesOnly;
}
@Override
public boolean hasMoreElements() {
return names.hasNext();
}
@Override
public boolean hasMore() throws NamingException {
return hasMoreElements();
}
@Override
public T nextElement() {
if (!names.hasNext()) {
return null;
}
try {
SimpleJndiName name = names.next();
Object obj = nm.lookup(name);
@SuppressWarnings("unchecked")
T next = producesNamesOnly
? (T) (new NameClassPair(name.toString(), getClass().getName()))
: (T) (new Binding(name.toString(), obj));
return next;
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Override
public T next() throws NamingException {
return nextElement();
}
@Override
public void close() {
//no-op since no steps needed to free up resources
}
}
// FIXME: no synchronization or concurrency, is it alright?
private static class NamespacesMap<K extends Serializable> extends HashMap<K, JavaNamespace> {
private static final long serialVersionUID = 7921214769289453089L;
private final String name;
private NamespacesMap(String name) {
this.name = name;
}
@Override
public String toString() {
return "NamespacesMap[name=" + name + ", keys=" + keySet() + ']';
}
}
private static class JavaNamespace extends HashMap<SimpleJndiName, Object> {
private static final long serialVersionUID = 8493699306782159175L;
private final String name;
private JavaNamespace(String name, String subContextName) {
this.name = name;
SimpleJndiName javaJndi = new SimpleJndiName(JNDI_CTX_JAVA);
JavaURLContext javaContext = new JavaURLContext(javaJndi);
put(javaJndi, javaContext);
put(new SimpleJndiName(javaJndi + "/"), javaContext);
JavaURLContext subContext = new JavaURLContext(new SimpleJndiName(javaJndi + subContextName));
put(subContext.getName(), subContext);
SimpleJndiName subContextJndi = new SimpleJndiName(subContext.getName() + "/");
put(subContextJndi, subContext);
JavaURLContext envContext = new JavaURLContext(new SimpleJndiName(subContextJndi + "env"));
put(envContext.getName(), envContext);
put(new SimpleJndiName(envContext.getName() + "/"), envContext);
}
@Override
public String toString() {
return "JavaNamespace[name=" + name + ", keys=" + keySet() + ']';
}
}
}