repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
null |
wildfly-main/naming/src/test/java/org/jboss/as/naming/WritableServiceBasedNamingStoreTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.naming.CompositeName;
import javax.naming.Name;
import javax.naming.NameNotFoundException;
import javax.naming.OperationNotSupportedException;
import org.wildfly.naming.java.permission.JndiPermission;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.deployment.JndiNamingDependencyProcessor;
import org.jboss.as.naming.deployment.RuntimeBindReleaseService;
import org.jboss.as.naming.service.NamingStoreService;
import org.jboss.msc.service.LifecycleEvent;
import org.jboss.msc.service.LifecycleListener;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import static org.jboss.as.naming.SecurityHelper.testActionWithPermission;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* @author John Bailey
* @author Eduardo Martins
*/
public class WritableServiceBasedNamingStoreTestCase {
private ServiceContainer container;
private WritableServiceBasedNamingStore store;
private static final ServiceName OWNER_FOO = ServiceName.of("Foo");
private static final ServiceName OWNER_BAR = ServiceName.of("Bar");
@Before
public void setup() throws Exception {
container = ServiceContainer.Factory.create();
installOwnerService(OWNER_FOO);
installOwnerService(OWNER_BAR);
final CountDownLatch latch2 = new CountDownLatch(1);
final NamingStoreService namingStoreService = new NamingStoreService();
container.addService(ContextNames.JAVA_CONTEXT_SERVICE_NAME, namingStoreService)
.setInitialMode(ServiceController.Mode.ACTIVE)
.addListener(new LifecycleListener() {
public void handleEvent(ServiceController<?> controller, LifecycleEvent event) {
switch (event) {
case UP: {
latch2.countDown();
break;
}
case FAILED: {
latch2.countDown();
fail("Did not install store service - " + controller.getStartException().getMessage());
break;
}
default:
break;
}
}
})
.install();
latch2.await(10, TimeUnit.SECONDS);
store = (WritableServiceBasedNamingStore) namingStoreService.getValue();
}
private void installOwnerService(ServiceName owner) throws InterruptedException {
final CountDownLatch latch1 = new CountDownLatch(1);
container.addService(JndiNamingDependencyProcessor.serviceName(owner), new RuntimeBindReleaseService())
.setInitialMode(ServiceController.Mode.ACTIVE)
.addListener(new LifecycleListener() {
public void handleEvent(ServiceController<?> controller, LifecycleEvent event) {
switch (event) {
case UP: {
latch1.countDown();
break;
}
case FAILED: {
latch1.countDown();
fail("Did not install store service - " + controller.getStartException().getMessage());
break;
}
default:
break;
}
}
})
.install();
latch1.await(10, TimeUnit.SECONDS);
}
@After
public void shutdownServiceContainer() {
if (container != null) {
container.shutdown();
try {
container.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
container = null;
}
}
store = null;
}
@Test
public void testBindNoOwner() throws Exception {
try {
store.bind(new CompositeName("test"), new Object());
fail("Should have failed with a read-only context exception");
} catch (OperationNotSupportedException expected) {
}
}
@Test
public void testBind() throws Exception {
final Name name = new CompositeName("test");
final Object value = new Object();
WritableServiceBasedNamingStore.pushOwner(OWNER_FOO);
try {
store.bind(name, value);
} finally {
WritableServiceBasedNamingStore.popOwner();
}
assertEquals(value, store.lookup(name));
}
@Test
public void testBindNested() throws Exception {
final Name name = new CompositeName("nested/test");
final Object value = new Object();
WritableServiceBasedNamingStore.pushOwner(OWNER_FOO);
try {
store.bind(name, value);
} finally {
WritableServiceBasedNamingStore.popOwner();
}
assertEquals(value, store.lookup(name));
}
@Test
public void testUnbind() throws Exception {
final Name name = new CompositeName("test");
final Object value = new Object();
WritableServiceBasedNamingStore.pushOwner(OWNER_FOO);
try {
store.bind(name, value);
store.unbind(name);
} finally {
WritableServiceBasedNamingStore.popOwner();
}
try {
store.lookup(name);
fail("Should have thrown name not found");
} catch (NameNotFoundException expect) {
}
}
@Test
public void testUnBindNoOwner() throws Exception {
try {
store.unbind(new CompositeName("test"));
fail("Should have failed with a read-only context exception");
} catch (OperationNotSupportedException expected) {
}
}
@Test
public void testCreateSubcontext() throws Exception {
WritableServiceBasedNamingStore.pushOwner(OWNER_FOO);
try {
assertTrue(((NamingContext) store.createSubcontext(new CompositeName("test"))).getNamingStore() instanceof WritableServiceBasedNamingStore);
} finally {
WritableServiceBasedNamingStore.popOwner();
}
}
@Test
public void testCreateSubContextNoOwner() throws Exception {
try {
store.createSubcontext(new CompositeName("test"));
fail("Should have failed with a read-only context exception");
} catch (OperationNotSupportedException expected) {
}
}
@Test
public void testRebind() throws Exception {
final Name name = new CompositeName("test");
final Object value = new Object();
final Object newValue = new Object();
WritableServiceBasedNamingStore.pushOwner(OWNER_FOO);
try {
store.bind(name, value);
store.rebind(name, newValue);
} finally {
WritableServiceBasedNamingStore.popOwner();
}
assertEquals(newValue, store.lookup(name));
}
@Test
public void testRebindNoOwner() throws Exception {
try {
store.rebind(new CompositeName("test"), new Object());
fail("Should have failed with a read-only context exception");
} catch (OperationNotSupportedException expected) {
}
}
/**
* Binds an entry and then do lookups with several permissions
* @throws Exception
*/
@Test
public void testPermissions() throws Exception {
final NamingContext namingContext = new NamingContext(store, null);
final String name = "a/b";
final Object value = new Object();
ArrayList<JndiPermission> permissions = new ArrayList<JndiPermission>();
// simple bind test, note that permission must have absolute path
WritableServiceBasedNamingStore.pushOwner(OWNER_FOO);
try {
permissions.add(new JndiPermission(store.getBaseName()+"/"+name,"bind,list,listBindings"));
Name nameObj = new CompositeName(name);
store.bind(nameObj, value);
store.lookup(nameObj);
} finally {
WritableServiceBasedNamingStore.popOwner();
}
// all of these lookup should work
permissions.set(0,new JndiPermission(store.getBaseName()+"/"+name,JndiPermission.ACTION_LOOKUP));
assertEquals(value, testActionWithPermission(JndiPermission.ACTION_LOOKUP, permissions, namingContext, name));
permissions.set(0,new JndiPermission(store.getBaseName()+"/-",JndiPermission.ACTION_LOOKUP));
assertEquals(value, testActionWithPermission(JndiPermission.ACTION_LOOKUP, permissions, namingContext, name));
permissions.set(0,new JndiPermission(store.getBaseName()+"/a/*",JndiPermission.ACTION_LOOKUP));
assertEquals(value, testActionWithPermission(JndiPermission.ACTION_LOOKUP, permissions, namingContext, name));
permissions.set(0,new JndiPermission(store.getBaseName()+"/a/-",JndiPermission.ACTION_LOOKUP));
assertEquals(value, testActionWithPermission(JndiPermission.ACTION_LOOKUP, permissions, namingContext, name));
permissions.set(0,new JndiPermission("<<ALL BINDINGS>>",JndiPermission.ACTION_LOOKUP));
assertEquals(value, testActionWithPermission(JndiPermission.ACTION_LOOKUP, permissions, namingContext, name));
permissions.set(0,new JndiPermission(store.getBaseName()+"/"+name,JndiPermission.ACTION_LOOKUP));
assertEquals(value, testActionWithPermission(JndiPermission.ACTION_LOOKUP, permissions, namingContext, store.getBaseName()+"/"+name));
NamingContext aNamingContext = (NamingContext) namingContext.lookup("a");
permissions.set(0,new JndiPermission(store.getBaseName()+"/"+name,JndiPermission.ACTION_LOOKUP));
assertEquals(value, testActionWithPermission(JndiPermission.ACTION_LOOKUP, permissions, aNamingContext, "b"));
// this lookup should not work, no permission
try {
testActionWithPermission(JndiPermission.ACTION_LOOKUP, Collections.<JndiPermission>emptyList(), namingContext, name);
fail("Should have failed due to missing permission");
} catch (AccessControlException e) {
}
// a permission which only allows entries in store.getBaseName()
try {
permissions.set(0,new JndiPermission(store.getBaseName()+"/*",JndiPermission.ACTION_LOOKUP));
testActionWithPermission(JndiPermission.ACTION_LOOKUP, permissions, namingContext, name);
fail("Should have failed due to missing permission");
} catch (AccessControlException e) {
}
// permissions which are not absolute paths (do not include store base name, i.e. java:)
try {
permissions.set(0,new JndiPermission(name,JndiPermission.ACTION_LOOKUP));
testActionWithPermission(JndiPermission.ACTION_LOOKUP, permissions, namingContext, name);
fail("Should have failed due to missing permission");
} catch (AccessControlException e) {
}
if (! "java:".equals(store.getBaseName().toString())) {
try {
permissions.set(0,new JndiPermission("/"+name,JndiPermission.ACTION_LOOKUP));
testActionWithPermission(JndiPermission.ACTION_LOOKUP, permissions, namingContext, name);
fail("Should have failed due to missing permission");
} catch (AccessControlException e) {
}
try {
permissions.set(0,new JndiPermission("/-",JndiPermission.ACTION_LOOKUP));
testActionWithPermission(JndiPermission.ACTION_LOOKUP, permissions, namingContext, name);
fail("Should have failed due to missing permission");
} catch (AccessControlException e) {
}
}
}
@Test
public void testOwnerBindingReferences() throws Exception {
final Name name = new CompositeName("test");
final ServiceName serviceName = store.buildServiceName(name);
final Object value = new Object();
// ensure bind does not exists
try {
store.lookup(name);
fail("Should have thrown name not found");
} catch (NameNotFoundException expect) {
}
final RuntimeBindReleaseService.References duBindingReferences = (RuntimeBindReleaseService.References) container.getService(JndiNamingDependencyProcessor.serviceName(OWNER_FOO)).getValue();
WritableServiceBasedNamingStore.pushOwner(OWNER_FOO);
try {
store.bind(name, value);
// Foo's RuntimeBindReleaseService should now have a reference to the new bind
assertTrue(duBindingReferences.contains(serviceName));
store.rebind(name, value);
// after rebind, Foo's RuntimeBindReleaseService should continue to have a reference to the bind
assertTrue(duBindingReferences.contains(serviceName));
store.unbind(name);
} finally {
WritableServiceBasedNamingStore.popOwner();
}
}
@Test
public void testMultipleOwnersBindingReferences() throws Exception {
final Name name = new CompositeName("test");
final ServiceName serviceName = store.buildServiceName(name);
final Object value = new Object();
// ensure bind does not exists
try {
store.lookup(name);
fail("Should have thrown name not found");
} catch (NameNotFoundException expect) {
}
// ensure the owners RuntimeBindReleaseService have no reference to the future bind
final RuntimeBindReleaseService.References fooDuBindingReferences = (RuntimeBindReleaseService.References) container.getService(JndiNamingDependencyProcessor.serviceName(OWNER_FOO)).getValue();
assertFalse(fooDuBindingReferences.contains(serviceName));
final RuntimeBindReleaseService.References barDuBindingReferences = (RuntimeBindReleaseService.References) container.getService(JndiNamingDependencyProcessor.serviceName(OWNER_BAR)).getValue();
assertFalse(barDuBindingReferences.contains(serviceName));
WritableServiceBasedNamingStore.pushOwner(OWNER_FOO);
try {
store.bind(name, value);
// Foo's RuntimeBindReleaseService should now have a reference to the new bind
assertTrue(fooDuBindingReferences.contains(serviceName));
// Bar's RuntimeBindReleaseService reference to the bind should not exist
assertFalse(barDuBindingReferences.contains(serviceName));
} finally {
WritableServiceBasedNamingStore.popOwner();
}
WritableServiceBasedNamingStore.pushOwner(OWNER_BAR);
try {
store.rebind(name, value);
// after rebind, Foo's RuntimeBindReleaseService reference to the bind should still exist
assertTrue(fooDuBindingReferences.contains(serviceName));
// after rebind, Bar's RuntimeBindReleaseService reference to the bind should now exist
assertTrue(barDuBindingReferences.contains(serviceName));
} finally {
WritableServiceBasedNamingStore.popOwner();
}
WritableServiceBasedNamingStore.pushOwner(OWNER_FOO);
try {
store.unbind(name);
} finally {
WritableServiceBasedNamingStore.popOwner();
}
}
}
| 17,057 | 41.967254 | 201 |
java
|
null |
wildfly-main/naming/src/test/java/org/jboss/as/naming/SecurityHelper.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import static org.junit.Assert.fail;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.Permission;
import java.security.Permissions;
import java.security.Policy;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.Callable;
import javax.naming.CompositeName;
import javax.naming.Name;
import javax.naming.NamingException;
import org.wildfly.naming.java.permission.JndiPermission;
/**
* @author Lukas Krejci
*/
public class SecurityHelper {
private SecurityHelper() {
}
public static Object testActionPermission(final int action, final NamingContext namingContext,
final String name, final Object... params) throws Exception {
return testActionPermission(action, Collections.<JndiPermission>emptyList(), namingContext, name, params);
}
public static Object testActionPermission(final int action,
final Collection<JndiPermission> additionalRequiredPerms, final NamingContext namingContext, final String name,
final Object... params) throws Exception {
Exception positiveTestCaseException = null;
try {
//positive test case
return testActionWithPermission(action, additionalRequiredPerms, namingContext, name, params);
} catch (Exception e) {
positiveTestCaseException = e;
//this is just to satisfy the compiler... the finally clause should always throw an exception in this case
return null;
} finally {
//negative test case
try {
testActionWithoutPermission(action, additionalRequiredPerms, namingContext, name, params);
} catch (Exception e) {
if (positiveTestCaseException == null) {
throw e;
} else {
throw new Exception("Both positive and negative permission test for JNDI action "
+ action
+ " failed. The negative test case (which should have resulted in a security exception)"
+ " failed with a message: "
+ "("
+ e.getClass().getName()
+ "): "
+ e.getMessage()
+ ". The exception of the positive testcase"
+ " is set up as the cause of this exception.", positiveTestCaseException);
}
}
if (positiveTestCaseException != null) {
throw positiveTestCaseException;
}
}
}
public static Object testActionWithPermission(final int action,
final Collection<JndiPermission> additionalRequiredPerms, final NamingContext namingContext, final String name,
final Object... params) throws Exception {
final CompositeName n = name == null ? new CompositeName() : new CompositeName(name);
final String sn = name == null ? "" : name;
ArrayList<JndiPermission> allPerms = new ArrayList<JndiPermission>(additionalRequiredPerms);
allPerms.add(new JndiPermission(sn, action));
return runWithSecurityManager(new Callable<Object>() {
@Override
public Object call() throws Exception {
return performAction(action, namingContext, n, params);
}
}, getSecurityContextForJNDILookup(allPerms));
}
public static void testActionWithoutPermission(final int action,
final Collection<JndiPermission> additionalRequiredPerms, final NamingContext namingContext, final String name,
final Object... params) throws Exception {
final CompositeName n = name == null ? new CompositeName() : new CompositeName(name);
final String sn = name == null ? "" : name;
ArrayList<JndiPermission> allPerms = new ArrayList<JndiPermission>(additionalRequiredPerms);
allPerms.add(new JndiPermission(sn, not(action)));
try {
runWithSecurityManager(new Callable<Object>() {
@Override
public Object call() throws Exception {
return performAction(action, namingContext, n, params);
}
}, getSecurityContextForJNDILookup(allPerms));
fail("Naming operation " + action + " should not have been permitted");
} catch (SecurityException e) {
//expected
}
}
private static int not(int action) {
return ~action & JndiPermission.ACTION_ALL;
}
private static Object performAction(int action, NamingContext namingContext, Name name,
Object... params) throws NamingException {
switch (action) {
case JndiPermission.ACTION_BIND:
if (params.length == 1) {
namingContext.bind(name, params[0]);
} else {
throw new IllegalArgumentException("Invalid number of arguments passed to bind()");
}
return null;
case JndiPermission.ACTION_CREATE_SUBCONTEXT:
return namingContext.createSubcontext(name);
case JndiPermission.ACTION_LIST:
return namingContext.list(name);
case JndiPermission.ACTION_LIST_BINDINGS:
return namingContext.listBindings(name);
case JndiPermission.ACTION_LOOKUP:
if (params.length == 0) {
return namingContext.lookup(name);
} else if (params.length == 1) {
return namingContext.lookup(name, (Boolean) params[0]);
} else {
throw new IllegalArgumentException("Invalid number of arguments passed to lookup()");
}
case JndiPermission.ACTION_REBIND:
if (params.length == 1) {
namingContext.rebind(name, params[0]);
} else {
throw new IllegalArgumentException("Invalid number of arguments passed to rebind()");
}
return null;
case JndiPermission.ACTION_UNBIND:
namingContext.unbind(name);
return null;
default:
throw new IllegalArgumentException("Action "
+ action
+ " not supported by the generic testActionPermission test");
}
}
public static <T> T runWithSecurityManager(final Callable<T> action, final AccessControlContext securityContext)
throws Exception {
Policy previousPolicy = Policy.getPolicy();
SecurityManager previousSM = System.getSecurityManager();
//let's be a bit brutal here and just allow any code do anything by default for the time this method executes.
Policy.setPolicy(new Policy() {
@Override
public boolean implies(ProtectionDomain domain, Permission permission) {
return true;
}
});
//with our new totally unsecure policy, let's install a new security manager
System.setSecurityManager(new SecurityManager());
try {
//run the code to test with limited privs defined by the securityContext
return AccessController.doPrivileged(new PrivilegedExceptionAction<T>() {
@Override
public T run() throws Exception {
return action.call();
}
}, securityContext);
} catch (PrivilegedActionException e) {
throw e.getException();
} finally {
//and reset back the previous security settings
System.setSecurityManager(previousSM);
Policy.setPolicy(previousPolicy);
}
}
private static AccessControlContext getSecurityContextForJNDILookup(Collection<JndiPermission> jndiPermissions) {
CodeSource src = new CodeSource(null, (Certificate[]) null);
Permissions perms = new Permissions();
for (JndiPermission p : jndiPermissions) {
perms.add(p);
}
ProtectionDomain domain = new ProtectionDomain(src, perms);
AccessControlContext ctx = new AccessControlContext(new ProtectionDomain[]{domain});
return ctx;
}
}
| 9,861 | 40.091667 | 162 |
java
|
null |
wildfly-main/naming/src/test/java/org/jboss/as/naming/InMemoryNamingStoreTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import org.junit.After;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import javax.naming.Binding;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.InvalidNameException;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameNotFoundException;
import javax.naming.Reference;
import javax.naming.spi.ResolveResult;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author John E. Bailey
*/
public class InMemoryNamingStoreTestCase {
private final InMemoryNamingStore nameStore = new InMemoryNamingStore();
@After
public void cleanup() throws Exception {
nameStore.close();
}
@Test
public void testBindEmptyName() throws Exception {
try {
nameStore.bind(new CompositeName(), new Object(), Object.class);
fail("Should have thrown and InvalidNameException");
} catch(InvalidNameException expected){}
try {
nameStore.bind(new CompositeName(""), new Object(), Object.class);
fail("Should have thrown and InvalidNameException");
} catch(InvalidNameException expected){}
}
@Test
public void testBindAndLookup() throws Exception {
final Name name = new CompositeName("test");
final Object object = new Object();
nameStore.bind(name, object, Object.class);
final Object result = nameStore.lookup(name);
assertEquals(object, result);
}
@Test
public void testLookupNameNotFound() throws Exception {
try {
nameStore.lookup(new CompositeName("test"));
fail("Should have thrown and NameNotFoundException");
} catch(NameNotFoundException expected) {}
}
@Test
public void testLookupEmptyName() throws Exception {
Object result = nameStore.lookup(new CompositeName());
assertTrue(result instanceof NamingContext);
result = nameStore.lookup(new CompositeName(""));
assertTrue(result instanceof NamingContext);
}
@Test
public void testBindAndLookupResolveResult() throws Exception {
final Name name = new CompositeName("test");
final Reference reference = new Reference(Context.class.getName());
nameStore.bind(name, reference, Context.class);
final Object result = nameStore.lookup(new CompositeName("test/value"));
assertTrue(result instanceof ResolveResult);
}
@Test
public void testUnbindNotFound() throws Exception {
try {
nameStore.unbind(new CompositeName("test"));
fail("Should have thrown and NameNotFoundException");
} catch(NameNotFoundException expected) {}
}
@Test
public void testBindUnbindLookup() throws Exception {
final Name name = new CompositeName("test");
final Object object = new Object();
nameStore.bind(name, object, Object.class);
final Object result = nameStore.lookup(name);
assertEquals(object, result);
nameStore.unbind(name);
try {
nameStore.lookup(name);
fail("Should have thrown and NameNotFoundException");
} catch(NameNotFoundException expected) {}
}
@Test
public void testRebindEmptyName() throws Exception {
try {
nameStore.rebind(new CompositeName(), new Object(), Object.class);
fail("Should have thrown and InvalidNameException");
} catch(InvalidNameException expected){}
try {
nameStore.rebind(new CompositeName(""), new Object(), Object.class);
fail("Should have thrown and InvalidNameException");
} catch(InvalidNameException expected){}
}
@Test
public void testRebindInvalidContext() throws Exception {
try {
nameStore.rebind(new CompositeName("subcontext/test"), new Object(), Object.class);
fail("Should have thrown and NameNotFoundException");
} catch(NameNotFoundException expected){}
}
@Test
public void testRebindAndLookup() throws Exception {
final Name name = new CompositeName("test");
final Object object = new Object();
nameStore.rebind(name, object, Object.class);
final Object result = nameStore.lookup(name);
assertEquals(object, result);
}
@Test
public void testBindAndRebind() throws Exception {
final Name name = new CompositeName("test");
final Object object = new Object();
nameStore.bind(name, object, Object.class);
assertEquals(object, nameStore.lookup(name));
final Object objectTwo = new Object();
nameStore.rebind(name, objectTwo, Object.class);
assertEquals(objectTwo, nameStore.lookup(name));
}
@Test
public void testListNameNotFound() throws Exception {
try {
nameStore.list(new CompositeName("test"));
fail("Should have thrown and NameNotFoundException");
} catch(NameNotFoundException expected) {}
}
@Test
public void testList() throws Exception {
final Name name = new CompositeName("test");
final Object object = new Object();
nameStore.bind(name, object, Object.class);
final Name nameTwo = new CompositeName("testTwo");
final Object objectTwo = new Object();
nameStore.bind(nameTwo, objectTwo, Object.class);
final Name nameThree = new CompositeName("testThree");
final Object objectThree = new Object();
nameStore.bind(nameThree, objectThree, Object.class);
nameStore.bind(new CompositeName("testContext/test"), "test");
final List<NameClassPair> results = nameStore.list(new CompositeName());
assertEquals(4, results.size());
final Set<String> expected = new HashSet<String>(Arrays.asList("test", "testTwo", "testThree", "testContext"));
for(NameClassPair result : results) {
final String resultName = result.getName();
if("test".equals(resultName) || "testTwo".equals(resultName) || "testThree".equals(resultName)) {
assertEquals(Object.class.getName(), result.getClassName());
} else if("testContext".equals(resultName)) {
assertEquals(Context.class.getName(), result.getClassName());
} else {
fail("Unknown result name: " + resultName);
}
expected.remove(resultName);
}
assertTrue("Not all expected results were returned", expected.isEmpty());
}
@Test
public void testListBindingsNameNotFound() throws Exception {
try {
nameStore.listBindings(new CompositeName("test"));
fail("Should have thrown and NameNotFoundException");
} catch(NameNotFoundException expected) {}
}
@Test
public void testListBindings() throws Exception {
final Name name = new CompositeName("test");
final Object object = new Object();
nameStore.bind(name, object);
final Name nameTwo = new CompositeName("testTwo");
final Object objectTwo = new Object();
nameStore.bind(nameTwo, objectTwo);
final Name nameThree = new CompositeName("testThree");
final Object objectThree = new Object();
nameStore.bind(nameThree, objectThree);
nameStore.bind(new CompositeName("testContext/test"), "test");
final List<Binding> results = nameStore.listBindings(new CompositeName());
assertEquals(4, results.size());
final Set<String> expected = new HashSet<String>(Arrays.asList("test", "testTwo", "testThree", "testContext"));
for(Binding result : results) {
final String resultName = result.getName();
if("test".equals(resultName)) {
assertEquals(Object.class.getName(), result.getClassName());
assertEquals(object, result.getObject());
} else if("testTwo".equals(resultName)) {
assertEquals(Object.class.getName(), result.getClassName());
assertEquals(objectTwo, result.getObject());
} else if("testThree".equals(resultName)) {
assertEquals(Object.class.getName(), result.getClassName());
assertEquals(objectThree, result.getObject());
} else if("testContext".equals(resultName)) {
assertEquals(Context.class.getName(), result.getClassName());
} else {
fail("Unknown result name: " + resultName);
}
expected.remove(resultName);
}
assertTrue("Not all expected results were returned", expected.isEmpty());
}
@Test
public void testAutoRemove() throws Exception {
nameStore.bind(new CompositeName("test/item"), new Object());
assertNotNull(nameStore.lookup(new CompositeName("test/item")));
assertNotNull(nameStore.lookup(new CompositeName("test")));
nameStore.unbind(new CompositeName("test/item"));
try {
nameStore.lookup(new CompositeName("test"));
fail("Should have throw name not found exception");
} catch (NameNotFoundException expected){}
}
}
| 10,463 | 37.899628 | 119 |
java
|
null |
wildfly-main/naming/src/test/java/org/jboss/as/naming/ObjectFactoryTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import java.util.Hashtable;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;
import org.junit.After;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @author John Bailey
*/
public class ObjectFactoryTestCase {
private WritableNamingStore namingStore;
private NamingContext namingContext;
@BeforeClass
public static void initNamingManager() throws Exception {
NamingContext.initializeNamingManager();
}
@Before
public void setup() throws Exception {
namingStore = new InMemoryNamingStore();
NamingContext.setActiveNamingStore(namingStore);
namingContext = new NamingContext(namingStore, null);
}
@After
public void cleanup() throws Exception {
NamingContext.setActiveNamingStore(new InMemoryNamingStore());
}
@Test
public void testBindAndRetrieveObjectFactoryFromNamingContext() throws Exception {
final Reference reference = new Reference("java.util.String", TestObjectFactory.class.getName(), null);
namingStore.bind(new CompositeName("test"), reference);
final Object result = namingContext.lookup("test");
assertTrue(result instanceof String);
assertEquals("Test ParsedResult", result);
}
@Test
public void testBindAndRetrieveObjectFactoryFromInitialContext() throws Exception {
final Reference reference = new Reference("java.util.String", TestObjectFactory.class.getName(), null);
namingStore.bind(new CompositeName("test"), reference);
final InitialContext initialContext = new InitialContext();
final Object result = initialContext.lookup("test");
assertTrue(result instanceof String);
assertEquals("Test ParsedResult", result);
}
public static class TestObjectFactory implements ObjectFactory {
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
return "Test ParsedResult";
}
}
}
| 3,325 | 35.549451 | 127 |
java
|
null |
wildfly-main/naming/src/test/java/org/jboss/as/naming/NamingEventCoordinatorTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import org.junit.Before;
import org.junit.Test;
import javax.naming.CompositeName;
import javax.naming.event.EventContext;
import javax.naming.event.NamespaceChangeListener;
import javax.naming.event.NamingEvent;
import javax.naming.event.NamingExceptionEvent;
import javax.naming.event.ObjectChangeListener;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Basic naming event coordinator tests.
*
* @author John E. Bailey
*/
public class NamingEventCoordinatorTestCase {
private NamingContext context;
@Before
public void setup() throws Exception {
NamingContext.setActiveNamingStore(new InMemoryNamingStore());
context = new NamingContext(null);
}
@Test
public void testFireObjectEvent() throws Exception {
final NamingEventCoordinator coordinator = new NamingEventCoordinator();
final CollectingListener objectListener = new CollectingListener(1);
coordinator.addListener("test/path", EventContext.OBJECT_SCOPE, objectListener);
final CollectingListener subtreeListener = new CollectingListener(0);
coordinator.addListener("test", EventContext.SUBTREE_SCOPE, subtreeListener);
final CollectingListener oneLevelListener = new CollectingListener(0);
coordinator.addListener("test", EventContext.ONELEVEL_SCOPE, oneLevelListener);
coordinator.fireEvent(context, new CompositeName("test/path"), null, null, NamingEvent.OBJECT_ADDED, "bind", EventContext.OBJECT_SCOPE);
objectListener.latch.await(1, TimeUnit.SECONDS);
assertEquals(1, objectListener.capturedEvents.size());
assertTrue(oneLevelListener.capturedEvents.isEmpty());
assertTrue(subtreeListener.capturedEvents.isEmpty());
}
@Test
public void testFireSubTreeEvent() throws Exception {
final NamingEventCoordinator coordinator = new NamingEventCoordinator();
final CollectingListener objectListener = new CollectingListener(0);
coordinator.addListener("test/path", EventContext.OBJECT_SCOPE, objectListener);
final CollectingListener subtreeListener = new CollectingListener(1);
coordinator.addListener("test", EventContext.SUBTREE_SCOPE, subtreeListener);
final CollectingListener oneLevelListener = new CollectingListener(0);
coordinator.addListener("test", EventContext.ONELEVEL_SCOPE, oneLevelListener);
coordinator.fireEvent(context, new CompositeName("test/path"), null, null, NamingEvent.OBJECT_ADDED, "bind", EventContext.SUBTREE_SCOPE);
subtreeListener.latch.await(1, TimeUnit.SECONDS);
assertTrue(objectListener.capturedEvents.isEmpty());
assertTrue(oneLevelListener.capturedEvents.isEmpty());
assertEquals(1, subtreeListener.capturedEvents.size());
}
@Test
public void testFireOneLevelEvent() throws Exception {
final NamingEventCoordinator coordinator = new NamingEventCoordinator();
final CollectingListener objectListener = new CollectingListener(0);
coordinator.addListener("test/path", EventContext.OBJECT_SCOPE, objectListener);
final CollectingListener subtreeListener = new CollectingListener(0);
coordinator.addListener("test", EventContext.SUBTREE_SCOPE, subtreeListener);
final CollectingListener oneLevelListener = new CollectingListener(1);
coordinator.addListener("test", EventContext.ONELEVEL_SCOPE, oneLevelListener);
coordinator.fireEvent(context, new CompositeName("test/path"), null, null, NamingEvent.OBJECT_ADDED, "bind", EventContext.ONELEVEL_SCOPE);
oneLevelListener.latch.await(1, TimeUnit.SECONDS);
assertTrue(objectListener.capturedEvents.isEmpty());
assertTrue(subtreeListener.capturedEvents.isEmpty());
assertEquals(1, oneLevelListener.capturedEvents.size());
}
@Test
public void testFireAllEvent() throws Exception {
final NamingEventCoordinator coordinator = new NamingEventCoordinator();
final CollectingListener objectListener = new CollectingListener(1);
coordinator.addListener("test/path", EventContext.OBJECT_SCOPE, objectListener);
final CollectingListener subtreeListener = new CollectingListener(1);
coordinator.addListener("test", EventContext.SUBTREE_SCOPE, subtreeListener);
final CollectingListener oneLevelListener = new CollectingListener(1);
coordinator.addListener("test", EventContext.ONELEVEL_SCOPE, oneLevelListener);
coordinator.fireEvent(context, new CompositeName("test/path"), null, null, NamingEvent.OBJECT_ADDED, "bind", EventContext.OBJECT_SCOPE, EventContext.ONELEVEL_SCOPE, EventContext.SUBTREE_SCOPE);
objectListener.latch.await(1, TimeUnit.SECONDS);
oneLevelListener.latch.await(1, TimeUnit.SECONDS);
subtreeListener.latch.await(1, TimeUnit.SECONDS);
assertEquals(1, objectListener.capturedEvents.size());
assertEquals(1, subtreeListener.capturedEvents.size());
assertEquals(1, oneLevelListener.capturedEvents.size());
}
@Test
public void testFireMultiLevelEvent() throws Exception {
final NamingEventCoordinator coordinator = new NamingEventCoordinator();
final CollectingListener subtreeListener = new CollectingListener(1);
coordinator.addListener("foo", EventContext.SUBTREE_SCOPE, subtreeListener);
final CollectingListener subtreeListenerTwo = new CollectingListener(1);
coordinator.addListener("foo/bar", EventContext.SUBTREE_SCOPE, subtreeListenerTwo);
final CollectingListener subtreeListenerThree = new CollectingListener(1);
coordinator.addListener("foo/bar/baz", EventContext.SUBTREE_SCOPE, subtreeListenerThree);
coordinator.fireEvent(context, new CompositeName("foo/bar/baz/boo"), null, null, NamingEvent.OBJECT_ADDED, "bind", EventContext.OBJECT_SCOPE, EventContext.ONELEVEL_SCOPE, EventContext.SUBTREE_SCOPE);
subtreeListener.latch.await(1, TimeUnit.SECONDS);
subtreeListenerTwo.latch.await(1, TimeUnit.SECONDS);
subtreeListenerThree.latch.await(1, TimeUnit.SECONDS);
assertEquals(1, subtreeListener.capturedEvents.size());
assertEquals(1, subtreeListenerTwo.capturedEvents.size());
assertEquals(1, subtreeListenerThree.capturedEvents.size());
}
private class CollectingListener implements ObjectChangeListener, NamespaceChangeListener {
private final List<NamingEvent> capturedEvents = new ArrayList<NamingEvent>();
private final CountDownLatch latch;
CollectingListener(int expectedEvents) {
latch = new CountDownLatch(expectedEvents);
}
@Override
public void objectChanged(NamingEvent evt) {
captured(evt);
}
@Override
public void objectAdded(NamingEvent evt) {
captured(evt);
}
@Override
public void objectRemoved(NamingEvent evt) {
captured(evt);
}
@Override
public void objectRenamed(NamingEvent evt) {
captured(evt);
}
private void captured(final NamingEvent event) {
capturedEvents.add(event);
latch.countDown();
}
@Override
public void namingExceptionThrown(NamingExceptionEvent evt) {
}
}
}
| 8,588 | 41.310345 | 207 |
java
|
null |
wildfly-main/naming/src/test/java/org/jboss/as/naming/InitialContextTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.spi.ObjectFactory;
import java.util.Hashtable;
import org.junit.Assert;
import org.junit.Test;
import org.junit.Before;
/**
* @author David Bosschaert
*/
public class InitialContextTestCase {
@Before
public void before() {
NamingContext.setActiveNamingStore(new InMemoryNamingStore());
}
@Test
public void testRegisterURLSchemeHandler() throws Exception {
InitialContext ictx = new InitialContext(null);
try {
ictx.lookup("foobar:something");
Assert.fail("Precondition: the foobar: scheme should not yet be registered");
} catch (NamingException ne) {
// good
}
ObjectFactory tof = new TestObjectFactory();
InitialContext.addUrlContextFactory("foobar", tof);
String something = (String) ictx.lookup("foobar:something");
Assert.assertTrue("The object should now be provided by our TestObjectFactory", something.startsWith("TestObject:"));
try {
InitialContext.removeUrlContextFactory("foobar:", new TestObjectFactory());
Assert.fail("Should throw an IllegalArgumentException since the associated factory object doesn't match the registration");
} catch (IllegalArgumentException iae) {
// good;
}
Assert.assertEquals("The foobar: scheme should still be registered", something, ictx.lookup("foobar:something"));
InitialContext.removeUrlContextFactory("foobar", tof);
try {
ictx.lookup("foobar:something");
Assert.fail("The foobar: scheme should not be registered any more");
} catch (NamingException ne) {
// good
}
}
private class TestObjectFactory implements ObjectFactory {
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
return new InitialContext(new Hashtable<String, Object>()) {
@Override
public Object lookup(Name name) throws NamingException {
return "TestObject: " + name;
}
@Override
public Object lookup(String name) throws NamingException {
return "TestObject: " + name;
}
};
}
}
}
| 3,513 | 35.989474 | 135 |
java
|
null |
wildfly-main/naming/src/test/java/org/jboss/as/naming/NamingContextTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import static org.jboss.as.naming.SecurityHelper.testActionPermission;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Set;
import javax.naming.Binding;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.LinkRef;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.Referenceable;
import javax.naming.StringRefAddr;
import javax.naming.spi.ObjectFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.wildfly.naming.java.permission.JndiPermission;
/**
* @author John E. Bailey
*/
public class NamingContextTestCase {
private WritableNamingStore namingStore;
private NamingContext namingContext;
@BeforeClass
public static void setupObjectFactoryBuilder() throws Exception {
NamingContext.initializeNamingManager();
}
@Before
public void setup() throws Exception {
namingStore = new InMemoryNamingStore();
NamingContext.setActiveNamingStore(namingStore);
namingContext = new NamingContext(namingStore, null);
}
@After
public void cleanup() throws Exception {
namingStore.close();
NamingContext.setActiveNamingStore(new InMemoryNamingStore());
}
@Test
public void testLookup() throws Exception {
final Name name = new CompositeName("test");
final Object object = new Object();
namingStore.bind(name, object);
Object result = namingContext.lookup(name);
assertEquals(object, result);
//the same with security permissions
result = testActionPermission(JndiPermission.ACTION_LOOKUP, namingContext, "test");
assertEquals(object, result);
}
@Test
public void testLookupReference() throws Exception {
final Name name = new CompositeName("test");
final Reference reference = new Reference(String.class.getName(), new StringRefAddr("blah", "test"), TestObjectFactory.class.getName(), null);
namingStore.bind(name, reference);
Object result = namingContext.lookup(name);
assertEquals("test", result);
//the same with security permissions
result = testActionPermission(JndiPermission.ACTION_LOOKUP, namingContext, "test");
assertEquals("test", result);
}
@Test
public void testLookupWithContinuation() throws Exception {
namingStore.bind(new CompositeName("comp/nested"), "test");
final Reference reference = new Reference(String.class.getName(), new StringRefAddr("nns", "comp"), TestObjectFactoryWithNameResolution.class.getName(), null);
namingStore.bind(new CompositeName("test"), reference);
Object result = namingContext.lookup(new CompositeName("test/nested"));
assertEquals("test", result);
//the same with security permissions
result = testActionPermission(JndiPermission.ACTION_LOOKUP, Arrays.asList(new JndiPermission("comp/nested", "lookup")), namingContext, "test/nested");
assertEquals("test", result);
}
@Test
public void testLookupWitResolveResult() throws Exception {
namingStore.bind(new CompositeName("test/nested"), "test");
final Reference reference = new Reference(String.class.getName(), new StringRefAddr("blahh", "test"), TestObjectFactoryWithNameResolution.class.getName(), null);
namingStore.bind(new CompositeName("comp"), reference);
Object result = namingContext.lookup(new CompositeName("comp/nested"));
assertEquals("test", result);
//the same with security permissions
result = testActionPermission(JndiPermission.ACTION_LOOKUP, Arrays.asList(new JndiPermission("test/nested", "lookup")), namingContext, "comp/nested");
assertEquals("test", result);
}
@Test
public void testLookupLink() throws Exception {
final Name name = new CompositeName("test");
namingStore.bind(name, "testValue", String.class);
final Name linkName = new CompositeName("link");
namingStore.bind(linkName, new LinkRef("./test"));
Object result = namingContext.lookup(linkName);
assertEquals("testValue", result);
//the same with security permissions
result = testActionPermission(JndiPermission.ACTION_LOOKUP, Arrays.asList(new JndiPermission("test", "lookup")), namingContext, "link");
assertEquals("testValue", result);
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, InitialContextFactory.class.getName());
namingStore.rebind(linkName, new LinkRef(name));
result = namingContext.lookup(linkName);
assertEquals("testValue", result);
//the same with security permissions
result = testActionPermission(JndiPermission.ACTION_LOOKUP, Arrays.asList(new JndiPermission("test", "lookup")), namingContext, "link");
assertEquals("testValue", result);
}
@Test
public void testLookupContextLink() throws Exception {
final Name name = new CompositeName("test/value");
namingStore.bind(name, "testValue");
final Name linkName = new CompositeName("link");
namingStore.bind(linkName, new LinkRef("./test"));
Object result = namingContext.lookup("link/value");
assertEquals("testValue", result);
//the same with security permissions
result = testActionPermission(JndiPermission.ACTION_LOOKUP, Arrays.asList(new JndiPermission("test", "lookup"),
new JndiPermission("test/value", "lookup")), namingContext, "link/value");
assertEquals("testValue", result);
}
@Test
public void testLookupNameNotFound() throws Exception {
try {
namingContext.lookup(new CompositeName("test"));
fail("Should have thrown and NameNotFoundException");
} catch (NameNotFoundException expected) {
}
//the same with security permissions
try {
testActionPermission(JndiPermission.ACTION_LOOKUP, namingContext, "test");
fail("Should have thrown and NameNotFoundException with appropriate permissions");
} catch (NameNotFoundException expected) {
}
}
@Test
public void testLookupEmptyName() throws Exception {
Object result = namingContext.lookup(new CompositeName());
assertTrue(result instanceof NamingContext);
result = namingContext.lookup(new CompositeName(""));
assertTrue(result instanceof NamingContext);
//the same with security permissions
result = testActionPermission(JndiPermission.ACTION_LOOKUP, namingContext, null);
assertTrue(result instanceof NamingContext);
result = testActionPermission(JndiPermission.ACTION_LOOKUP, namingContext, "");
assertTrue(result instanceof NamingContext);
}
@Test
public void testBind() throws Exception {
Name name = new CompositeName("test");
final Object value = new Object();
namingContext.bind(name, value);
assertEquals(value, namingStore.lookup(name));
//the same with security permissions
name = new CompositeName("securitytest");
testActionPermission(JndiPermission.ACTION_BIND, namingContext, "securitytest", value);
assertEquals(value, namingStore.lookup(name));
}
@Test
public void testBindReferenceable() throws Exception {
Name name = new CompositeName("test");
final TestObjectReferenceable referenceable = new TestObjectReferenceable("addr");
namingContext.bind(name, referenceable);
Object result = namingContext.lookup(name);
assertEquals(referenceable.addr, result);
//the same with security permissions
name = new CompositeName("securitytest");
testActionPermission(JndiPermission.ACTION_BIND, namingContext, "securitytest", referenceable);
result = testActionPermission(JndiPermission.ACTION_LOOKUP, namingContext, "securitytest");
assertEquals(referenceable.addr, result);
}
@Test
public void testUnbind() throws Exception {
final Name name = new CompositeName("test");
final Object value = new Object();
namingStore.bind(name, value);
namingContext.unbind(name);
try {
namingStore.lookup(name);
fail("Should have thrown name not found");
} catch (NameNotFoundException expect) {}
//the same with security permissions
testActionPermission(JndiPermission.ACTION_BIND, namingContext, "test", value);
testActionPermission(JndiPermission.ACTION_UNBIND, namingContext, "test");
try {
namingStore.lookup(name);
fail("Should have thrown name not found");
} catch (NameNotFoundException expect) {}
}
@Test
public void testCreateSubcontext() throws Exception {
assertTrue(namingContext.createSubcontext(new CompositeName("test")) instanceof NamingContext);
//the same with security permissions
assertTrue(testActionPermission(JndiPermission.ACTION_CREATE_SUBCONTEXT, namingContext, "securitytest") instanceof NamingContext);
}
@Test
public void testRebind() throws Exception {
final Name name = new CompositeName("test");
final Object value = new Object();
namingStore.bind(name, value);
Object newValue = new Object();
namingContext.rebind(name, newValue);
assertEquals(newValue, namingStore.lookup(name));
//the same with security permissions
newValue = new Object();
testActionPermission(JndiPermission.ACTION_REBIND, namingContext, "test", newValue);
assertEquals(newValue, namingStore.lookup(name));
}
@Test
public void testRebindReferenceable() throws Exception {
final Name name = new CompositeName("test");
final TestObjectReferenceable referenceable = new TestObjectReferenceable("addr");
namingContext.bind(name, referenceable);
TestObjectReferenceable newReferenceable = new TestObjectReferenceable("newAddr");
namingContext.rebind(name, newReferenceable);
Object result = namingContext.lookup(name);
assertEquals(newReferenceable.addr, result);
//the same with security permissions
newReferenceable = new TestObjectReferenceable("yetAnotherNewAddr");
testActionPermission(JndiPermission.ACTION_REBIND, namingContext, "test", newReferenceable);
result = namingContext.lookup(name);
assertEquals(newReferenceable.addr, result);
}
@Test
public void testListNameNotFound() throws Exception {
try {
namingContext.list(new CompositeName("test"));
fail("Should have thrown and NameNotFoundException");
} catch (NameNotFoundException expected) {
}
//the same with security permissions
try {
testActionPermission(JndiPermission.ACTION_LIST, namingContext, "test");
fail("Should have thrown and NameNotFoundException with appropriate permissions");
} catch (NameNotFoundException expected) {
}
}
@Test
@SuppressWarnings("unchecked")
public void testList() throws Exception {
bindList();
NamingEnumeration<NameClassPair> results = namingContext.list(new CompositeName());
checkListResults(results);
//the same with security permissions
results = (NamingEnumeration<NameClassPair>) testActionPermission(JndiPermission.ACTION_LIST, namingContext, null);
checkListResults(results);
}
@Test
@SuppressWarnings("unchecked")
public void testListWithContinuation() throws Exception {
bindListWithContinuations();
NamingEnumeration<NameClassPair> results = namingContext.list(new CompositeName("comp"));
checkListWithContinuationsResults(results);
//the same with security permissions
results = (NamingEnumeration<NameClassPair>) testActionPermission(JndiPermission.ACTION_LIST, Arrays.asList(
new JndiPermission("test", "list")), namingContext, "comp");
checkListWithContinuationsResults(results);
}
@Test
public void testListBindingsNameNotFound() throws Exception {
try {
namingContext.listBindings(new CompositeName("test"));
fail("Should have thrown and NameNotFoundException");
} catch (NameNotFoundException expected) {
}
//the same with security permissions
try {
testActionPermission(JndiPermission.ACTION_LIST_BINDINGS, namingContext, "test");
fail("Should have thrown and NameNotFoundException with appropriate permissions");
} catch (NameNotFoundException expected) {
}
}
@Test
@SuppressWarnings("unchecked")
public void testListBindings() throws Exception {
bindList();
NamingEnumeration<Binding> results = namingContext.listBindings(new CompositeName());
checkListResults(results);
//the same with security permissions
results = (NamingEnumeration<Binding>) testActionPermission(JndiPermission.ACTION_LIST_BINDINGS, namingContext, null);
checkListResults(results);
}
@Test
@SuppressWarnings("unchecked")
public void testListBindingsWithContinuation() throws Exception {
bindListWithContinuations();
NamingEnumeration<Binding> results = namingContext.listBindings(new CompositeName("comp"));
checkListWithContinuationsResults(results);
//the same with security permissions
results = (NamingEnumeration<Binding>) testActionPermission(JndiPermission.ACTION_LIST_BINDINGS, Arrays.asList(
new JndiPermission("test", "listBindings")), namingContext, "comp");
checkListWithContinuationsResults(results);
}
public static class TestObjectFactory implements ObjectFactory {
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
return ((Reference) obj).get(0).getContent();
}
}
public static class TestObjectFactoryWithNameResolution implements ObjectFactory {
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
final Reference reference = (Reference) obj;
return new NamingContext(new CompositeName((String) reference.get(0).getContent()), null);
}
}
public static class TestObjectReferenceable implements Referenceable, Serializable {
private static final long serialVersionUID = 1L;
private String addr;
public TestObjectReferenceable(String addr) {
this.addr = addr;
}
@Override
public Reference getReference() throws NamingException {
return new Reference(String.class.getName(), new StringRefAddr("blah", addr), TestObjectFactory.class.getName(),
null);
}
}
private void bindList() throws NamingException {
final Name name = new CompositeName("test");
final Object object = new Object();
namingStore.bind(name, object);
final Name nameTwo = new CompositeName("testTwo");
final Object objectTwo = new Object();
namingStore.bind(nameTwo, objectTwo);
final Name nameThree = new CompositeName("testThree");
final Object objectThree = new Object();
namingStore.bind(nameThree, objectThree);
namingStore.bind(new CompositeName("testContext/test"), "testNested");
}
private void bindListWithContinuations() throws NamingException {
final Name name = new CompositeName("test/test");
final Object object = new Object();
namingStore.bind(name, object);
final Name nameTwo = new CompositeName("test/testTwo");
final Object objectTwo = new Object();
namingStore.bind(nameTwo, objectTwo);
final Name nameThree = new CompositeName("test/testThree");
final Object objectThree = new Object();
namingStore.bind(nameThree, objectThree);
final Reference reference = new Reference(String.class.getName(), new StringRefAddr("nns", "test"), TestObjectFactoryWithNameResolution.class.getName(), null);
namingStore.bind(new CompositeName("comp"), reference);
}
private void checkListResults(NamingEnumeration<? extends NameClassPair> results) throws NamingException {
final Set<String> expected = new HashSet<String>(Arrays.asList("test", "testTwo", "testThree", "testContext"));
while (results.hasMore()) {
NameClassPair result = results.next();
final String resultName = result.getName();
if ("test".equals(resultName) || "testTwo".equals(resultName) || "testThree".equals(resultName)) {
assertEquals(Object.class.getName(), result.getClassName());
} else if ("testContext".equals(resultName)) {
assertEquals(Context.class.getName(), result.getClassName());
} else {
fail("Unknown result name: " + resultName);
}
expected.remove(resultName);
}
assertTrue("Not all expected results were returned", expected.isEmpty());
}
private void checkListWithContinuationsResults(NamingEnumeration<? extends NameClassPair> results) throws NamingException {
final Set<String> expected = new HashSet<String>(Arrays.asList("test", "testTwo", "testThree"));
while (results.hasMore()) {
NameClassPair result = results.next();
final String resultName = result.getName();
if ("test".equals(resultName) || "testTwo".equals(resultName) || "testThree".equals(resultName)) {
assertEquals(Object.class.getName(), result.getClassName());
} else {
fail("Unknown result name: " + resultName);
}
expected.remove(resultName);
}
assertTrue("Not all expected results were returned", expected.isEmpty());
}
}
| 19,655 | 39.780083 | 169 |
java
|
null |
wildfly-main/naming/src/test/java/org/jboss/as/naming/ExternalContextsNavigableSetTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import org.jboss.as.naming.context.external.ExternalContextsNavigableSet;
import org.jboss.msc.service.ServiceName;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author emmartins
*/
public class ExternalContextsNavigableSetTestCase {
/**
* Asserts {@link ExternalContextsNavigableSet#getParentExternalContext(ServiceName)}
* @throws Exception
*/
@Test
public void testGetParentContext() throws Exception {
final ServiceName nameA = ServiceName.JBOSS.append("a");
final ServiceName nameP = ServiceName.JBOSS.append("p");
final ServiceName namePC = ServiceName.JBOSS.append("p","c");
final ServiceName nameZ = ServiceName.JBOSS.append("z");
ExternalContextsNavigableSet set = new ExternalContextsNavigableSet();
set.addExternalContext(nameP);
assertNull(set.getParentExternalContext(nameA));
assertNull(set.getParentExternalContext(nameP));
assertNotNull(set.getParentExternalContext(namePC));
assertEquals(nameP, set.getParentExternalContext(namePC));
assertNull(set.getParentExternalContext(nameZ));
}
}
| 2,198 | 40.490566 | 89 |
java
|
null |
wildfly-main/naming/src/test/java/org/jboss/as/naming/ServiceBasedNamingStoreTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.naming.Binding;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* @author John Bailey
*/
public class ServiceBasedNamingStoreTestCase {
private ServiceContainer container;
private ServiceBasedNamingStore store;
@Before
public void setupServiceContainer() {
container = ServiceContainer.Factory.create();
store = new ServiceBasedNamingStore(container, ServiceName.JBOSS);
}
@After
public void shutdownServiceContainer() {
if (container != null) {
container.shutdown();
try {
container.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
container = null;
}
}
store = null;
}
@Test
public void testLookupBase() throws Exception {
final Object obj = store.lookup(new CompositeName());
assertNotNull(obj);
}
@Test
public void testLookupBinding() throws Exception {
final ServiceName bindingName = ServiceName.JBOSS.append("foo", "bar");
final Object value = new Object();
bindObject(bindingName, value);
final Object obj = store.lookup(new CompositeName("foo/bar"));
assertNotNull(obj);
assertEquals(value, obj);
}
@Test
public void testLookupParentContext() throws Exception {
final ServiceName bindingName = ServiceName.JBOSS.append("foo", "bar");
store.add(bindingName);
final Object obj = store.lookup(new CompositeName("foo"));
assertNotNull(obj);
assertTrue(obj instanceof Context);
}
@Test
public void testStoredContext() throws Exception {
final ServiceName bindingName = ServiceName.JBOSS.append("foo-stored").append("again");
bindObject(bindingName, new Context() {
@Override
public Object lookup(Name name) throws NamingException {
if ("blah/blah2".equals(name.toString())) {
return 5;
}
return null;
}
@Override
public Object lookup(String name) throws NamingException {
return lookup(new CompositeName(name));
}
@Override
public void bind(Name name, Object obj) throws NamingException {
}
@Override
public void bind(String name, Object obj) throws NamingException {
}
@Override
public void rebind(Name name, Object obj) throws NamingException {
}
@Override
public void rebind(String name, Object obj) throws NamingException {
}
@Override
public void unbind(Name name) throws NamingException {
}
@Override
public void unbind(String name) throws NamingException {
}
@Override
public void rename(Name oldName, Name newName) throws NamingException {
}
@Override
public void rename(String oldName, String newName) throws NamingException {
}
@Override
public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
return null;
}
@Override
public NamingEnumeration<NameClassPair> list(String name) throws NamingException {
return null;
}
@Override
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
if (!"hi/there".equals(name.toString()))
throw new IllegalArgumentException("Expected hi/there");
return null;
}
@Override
public NamingEnumeration<Binding> listBindings(String name) throws NamingException {
return null;
}
@Override
public void destroySubcontext(Name name) throws NamingException {
}
@Override
public void destroySubcontext(String name) throws NamingException {
}
@Override
public Context createSubcontext(Name name) throws NamingException {
return null;
}
@Override
public Context createSubcontext(String name) throws NamingException {
return null;
}
@Override
public Object lookupLink(Name name) throws NamingException {
return null;
}
@Override
public Object lookupLink(String name) throws NamingException {
return null;
}
@Override
public NameParser getNameParser(Name name) throws NamingException {
return null;
}
@Override
public NameParser getNameParser(String name) throws NamingException {
return null;
}
@Override
public Name composeName(Name name, Name prefix) throws NamingException {
return null;
}
@Override
public String composeName(String name, String prefix) throws NamingException {
return null;
}
@Override
public Object addToEnvironment(String propName, Object propVal) throws NamingException {
return null;
}
@Override
public Object removeFromEnvironment(String propName) throws NamingException {
return null;
}
@Override
public Hashtable<?, ?> getEnvironment() throws NamingException {
return null;
}
@Override
public void close() throws NamingException {
}
@Override
public String getNameInNamespace() throws NamingException {
return null;
}
});
final NamingContext ctx = new NamingContext(new CompositeName(), store, null);
final Object obj = ctx.lookup(new CompositeName("foo-stored/again/blah/blah2"));
ctx.listBindings("foo-stored/again/hi/there");
assertNotNull(obj);
assertEquals(5, obj);
}
@Test
public void testLookupNestedContext() throws Exception {
final ServiceName bindingName = ServiceName.JBOSS.append("foo", "bar", "baz", "TestBean");
store.add(bindingName);
store.add(ServiceName.JBOSS.append("foos", "bar"));
store.add(ServiceName.JBOSS.append("fo", "bar"));
store.add(ServiceName.JBOSS.append("foo", "ba"));
store.add(ServiceName.JBOSS.append("foo", "bart"));
store.add(ServiceName.JBOSS.append("foo", "bar", "ba"));
store.add(ServiceName.JBOSS.append("foo", "bar", "bazt"));
store.add(ServiceName.JBOSS.append("foo", "bar", "art"));
Object obj = store.lookup(new CompositeName("foo"));
assertNotNull(obj);
assertTrue(obj instanceof Context);
obj = Context.class.cast(obj).lookup(new CompositeName("bar"));
assertNotNull(obj);
assertTrue(obj instanceof Context);
obj = Context.class.cast(obj).lookup(new CompositeName("baz"));
assertNotNull(obj);
assertTrue(obj instanceof Context);
}
@Test
public void testLookupBindingUsingNestedContext() throws Exception {
final ServiceName bindingName = ServiceName.JBOSS.append("foo", "bar", "baz", "TestBean");
final Object value = new Object();
bindObject(bindingName, value);
Object context = store.lookup(new CompositeName("foo"));
assertNotNull(context);
assertTrue(context instanceof Context);
Object obj = Context.class.cast(context).lookup(new CompositeName("bar/baz/TestBean"));
assertNotNull(obj);
assertEquals(value, obj);
context = Context.class.cast(context).lookup(new CompositeName("bar"));
obj = Context.class.cast(context).lookup(new CompositeName("baz/TestBean"));
assertNotNull(obj);
assertEquals(value, obj);
context = Context.class.cast(context).lookup(new CompositeName("baz"));
obj = Context.class.cast(context).lookup(new CompositeName("TestBean"));
assertNotNull(obj);
assertEquals(value, obj);
}
@Test
public void testList() throws Exception {
final Object value = new Object();
bindObject(ServiceName.JBOSS.append("TestBean"), value);
bindObject(ServiceName.JBOSS.append("foo", "TestBean"), value);
bindObject(ServiceName.JBOSS.append("foo", "bar", "TestBean"), value);
bindObject(ServiceName.JBOSS.append("foo", "bar", "baz", "TestBean"), value);
store.add(ServiceName.JBOSS.append("foos", "bar"));
store.add(ServiceName.JBOSS.append("fo", "bar"));
store.add(ServiceName.JBOSS.append("foo", "ba", "baz"));
store.add(ServiceName.JBOSS.append("foo", "bart", "baz"));
store.add(ServiceName.JBOSS.append("foo", "bar", "ba"));
store.add(ServiceName.JBOSS.append("foo", "bar", "bazt"));
store.add(ServiceName.JBOSS.append("foo", "bar", "art"));
store.add(ServiceName.JBOSS.append("other", "one"));
List<NameClassPair> list = store.list(new CompositeName(""));
assertEquals(5, list.size());
assertContains(list, "TestBean", Object.class);
assertContains(list, "foo", Context.class);
assertContains(list, "fo", Context.class);
assertContains(list, "foos", Context.class);
assertContains(list, "other", Context.class);
list = store.list(new CompositeName("foo"));
assertEquals(4, list.size());
assertContains(list, "TestBean", Object.class);
assertContains(list, "ba", Context.class);
assertContains(list, "bart", Context.class);
assertContains(list, "bar", Context.class);
}
@Test
public void testListBindings() throws Exception {
final Object value = new Object();
bindObject(ServiceName.JBOSS.append("TestBean"), value);
bindObject(ServiceName.JBOSS.append("foo", "TestBean"), value);
bindObject(ServiceName.JBOSS.append("foo", "bar", "TestBean"), value);
bindObject(ServiceName.JBOSS.append("foo", "bar", "baz", "TestBean"), value);
store.add(ServiceName.JBOSS.append("foos", "bar"));
store.add(ServiceName.JBOSS.append("fo", "bar"));
store.add(ServiceName.JBOSS.append("foo", "ba", "baz"));
store.add(ServiceName.JBOSS.append("foo", "bart", "baz"));
store.add(ServiceName.JBOSS.append("foo", "bar", "ba"));
store.add(ServiceName.JBOSS.append("foo", "bar", "bazt"));
store.add(ServiceName.JBOSS.append("foo", "bar", "art"));
store.add(ServiceName.JBOSS.append("other", "one"));
List<Binding> list = store.listBindings(new CompositeName(""));
assertEquals(5, list.size());
assertContains(list, "TestBean", Object.class);
assertContains(list, "foo", NamingContext.class);
assertContains(list, "fo", NamingContext.class);
assertContains(list, "foos", NamingContext.class);
assertContains(list, "other", NamingContext.class);
list = store.listBindings(new CompositeName("foo"));
assertEquals(4, list.size());
assertContains(list, "TestBean", Object.class);
assertContains(list, "ba", NamingContext.class);
assertContains(list, "bart", NamingContext.class);
assertContains(list, "bar", NamingContext.class);
for (Binding binding : list) {
if (binding.getName().equals("bar")) {
final Object bean = Context.class.cast(binding.getObject()).lookup("TestBean");
assertNotNull(bean);
assertEquals(value, bean);
}
}
}
private void assertContains(final List<? extends NameClassPair> list, String name, Class<?> type) {
for (NameClassPair value : list) {
if (value instanceof Binding) {
assertNotNull(Binding.class.cast(value).getObject());
}
if (value.getName().equals(name) && value.getClassName().equals(type.getName())) {
return;
}
}
fail("Child [" + name + "] not found in [" + list + "]");
}
private void bindObject(final ServiceName serviceName, final Object value) throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
container.addService(serviceName, new Service<ManagedReferenceFactory>() {
public void start(StartContext context) throws StartException {
store.add(serviceName);
latch.countDown();
}
public void stop(StopContext context) {
}
public ManagedReferenceFactory getValue() throws IllegalStateException, IllegalArgumentException {
return new ValueManagedReferenceFactory(value);
}
}).install();
latch.await();
}
}
| 15,156 | 35.260766 | 110 |
java
|
null |
wildfly-main/naming/src/test/java/org/jboss/as/naming/subsystem/NamingSubsystemTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.List;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
/**
* @author <a href="[email protected]">Kabir Khan</a>
*/
public class NamingSubsystemTestCase extends AbstractSubsystemBaseTest {
public NamingSubsystemTestCase() {
super(NamingExtension.SUBSYSTEM_NAME, new NamingExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("subsystem.xml");
}
@Override
protected String getSubsystemXsdPath() throws IOException {
return "schema/jboss-as-naming_2_0.xsd";
}
@Test
public void testOnlyExternalContextAllowsCache() throws Exception {
KernelServices services = createKernelServicesBuilder(createAdditionalInitialization())
.build();
Assert.assertTrue(services.isSuccessfulBoot());
List<ModelNode> list = parse(ModelTestUtils.readResource(this.getClass(), "subsystem.xml"));
for (ModelNode addOp : list) {
PathAddress addr = PathAddress.pathAddress(addOp.require(ModelDescriptionConstants.OP_ADDR));
if (addr.size() == 2 && addr.getLastElement().getKey().equals(NamingSubsystemModel.BINDING) && BindingType.forName(addOp.get(NamingBindingResourceDefinition.BINDING_TYPE.getName()).asString()) != BindingType.EXTERNAL_CONTEXT) {
//Add the cache attribute and make sure it fails
addOp.get(NamingBindingResourceDefinition.CACHE.getName()).set(true);
services.executeForFailure(addOp);
//Remove the cache attribute and make sure it succeeds
addOp.remove(NamingBindingResourceDefinition.CACHE.getName());
ModelTestUtils.checkOutcome(services.executeOperation(addOp));
//Try to write the cache attribute, which should fail
ModelTestUtils.checkFailed(services.executeOperation(Util.getWriteAttributeOperation(addr, NamingBindingResourceDefinition.CACHE.getName(), ModelNode.TRUE)));
} else {
ModelTestUtils.checkOutcome(services.executeOperation(addOp));
}
}
}
/**
* Asserts that bindings may be added through composite ops.
*
* @throws Exception
*/
@Test
public void testCompositeBindingOps() throws Exception {
final KernelServices services = createKernelServicesBuilder(createAdditionalInitialization()).setSubsystemXml(getSubsystemXml()).build();
// add binding 'alookup' through composite op
// note that a binding-type of 'lookup' requires 'lookup' attr value, which in this case is set by a followup step
final ModelNode addr = Operations.createAddress(ModelDescriptionConstants.SUBSYSTEM, NamingExtension.SUBSYSTEM_NAME, NamingSubsystemModel.BINDING, "java:global/alookup");
final ModelNode addOp = Operations.createAddOperation(addr);
addOp.get(NamingSubsystemModel.BINDING_TYPE).set(NamingSubsystemModel.LOOKUP);
final ModelNode compositeOp = Operations.CompositeOperationBuilder.create()
.addStep(addOp)
.addStep(Operations.createWriteAttributeOperation(addr, NamingSubsystemModel.LOOKUP, "java:global/a"))
.build().getOperation();
ModelTestUtils.checkOutcome(services.executeOperation(compositeOp));
}
/**
* Asserts that bindings may be updated through composite ops.
*
* @throws Exception
*/
@Test
public void testCompositeBindingUpdate() throws Exception {
final KernelServices services = createKernelServicesBuilder(createAdditionalInitialization()).setSubsystemXml(getSubsystemXml()).build();
// updates binding 'a' through composite op
// binding-type used is lookup, op should succeed even if lookup value is set by a followup step
final ModelNode addr = Operations.createAddress(ModelDescriptionConstants.SUBSYSTEM, NamingExtension.SUBSYSTEM_NAME, NamingSubsystemModel.BINDING, "java:global/a");
final ModelNode compositeOp = Operations.CompositeOperationBuilder.create()
.addStep(Operations.createWriteAttributeOperation(addr, NamingSubsystemModel.BINDING_TYPE, NamingSubsystemModel.LOOKUP))
.addStep(Operations.createWriteAttributeOperation(addr, NamingSubsystemModel.LOOKUP, "java:global/b"))
.build().getOperation();
ModelTestUtils.checkOutcome(services.executeOperation(compositeOp));
}
@Test
public void testExpressionInAttributeValue() throws Exception{
final KernelServices services = createKernelServicesBuilder(createAdditionalInitialization()).setSubsystemXml(readResource("subsystem_expression.xml")).build();
final ModelNode addr = Operations.createAddress("subsystem", "naming");
final ModelNode op = Operations.createReadResourceOperation(addr, true);
op.get(ModelDescriptionConstants.RESOLVE_EXPRESSIONS).set(true);
final ModelNode result = services.executeOperation(op).get("result");
ModelNode attribute = result.get(NamingSubsystemModel.BINDING).get("java:global/a");
final String value = attribute.get(NamingSubsystemModel.VALUE).asString();
assertEquals("100", value);
final String type = attribute.get(NamingSubsystemModel.TYPE).asString();
assertEquals("int", type);
attribute = result.get(NamingSubsystemModel.BINDING).get("java:global/b");
final String objclass = attribute.get(NamingSubsystemModel.CLASS).asString();
assertEquals("org.jboss.as.naming.ManagedReferenceObjectFactory", objclass);
final String module = attribute.get(NamingSubsystemModel.MODULE).asString();
assertEquals("org.jboss.as.naming", module);
attribute = result.get(NamingSubsystemModel.BINDING).get("java:global/c");
final String lookup = attribute.get(NamingSubsystemModel.LOOKUP).asString();
assertEquals("java:global/b", lookup);
}
@Override
protected AdditionalInitialization createAdditionalInitialization() {
return AdditionalInitialization.withCapabilities("org.wildfly.remoting.endpoint");
}
}
| 7,783 | 46.754601 | 239 |
java
|
null |
wildfly-main/naming/src/test/java/org/wildfly/naming/java/permission/JndiPermissionTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.naming.java.permission;
import static org.junit.Assert.*;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.Enumeration;
import org.junit.Test;
/**
* Big ol' JNDI permission test case.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public class JndiPermissionTestCase {
@Test
public void testNameImplies() {
// check the compat <<ALL BINDINGS>> name
assertEquals(new JndiPermission("<<ALL BINDINGS>>", "*"), new JndiPermission("-", "*"));
// check the root - name
assertTrue(new JndiPermission("-", "*").implies(new JndiPermission("-", "*")));
assertTrue(new JndiPermission("-", "*").implies(new JndiPermission("", "*")));
assertTrue(new JndiPermission("-", "*").implies(new JndiPermission("foo", "*")));
assertTrue(new JndiPermission("-", "*").implies(new JndiPermission("/foo", "*")));
assertTrue(new JndiPermission("-", "*").implies(new JndiPermission("foo/", "*")));
assertTrue(new JndiPermission("-", "*").implies(new JndiPermission("foo/bar/baz/zap", "*")));
assertTrue(new JndiPermission("-", "*").implies(new JndiPermission("java:foo", "*")));
// check the non-root - name
assertTrue(new JndiPermission("/-", "*").implies(new JndiPermission("/-", "*")));
assertTrue(new JndiPermission("/-", "*").implies(new JndiPermission("/", "*")));
assertTrue(new JndiPermission("/-", "*").implies(new JndiPermission("//", "*")));
assertTrue(new JndiPermission("/-", "*").implies(new JndiPermission("////", "*")));
assertTrue(new JndiPermission("/-", "*").implies(new JndiPermission("/foo", "*")));
assertTrue(new JndiPermission("/-", "*").implies(new JndiPermission("/foo", "*")));
assertTrue(new JndiPermission("/-", "*").implies(new JndiPermission("/foo/", "*")));
assertTrue(new JndiPermission("/-", "*").implies(new JndiPermission("/foo/bar/baz/zap", "*")));
assertTrue(new JndiPermission("/-", "*").implies(new JndiPermission("java:/foo", "*")));
assertTrue(new JndiPermission("foo/-", "*").implies(new JndiPermission("foo/-", "*")));
assertTrue(new JndiPermission("foo/-", "*").implies(new JndiPermission("foo/foo", "*")));
assertTrue(new JndiPermission("foo/-", "*").implies(new JndiPermission("foo/foo", "*")));
assertTrue(new JndiPermission("foo/-", "*").implies(new JndiPermission("foo/foo/", "*")));
assertTrue(new JndiPermission("foo/-", "*").implies(new JndiPermission("foo/foo/bar/baz/zap", "*")));
assertTrue(new JndiPermission("foo/-", "*").implies(new JndiPermission("java:foo/foo", "*")));
// check the * name
assertTrue(new JndiPermission("*", "*").implies(new JndiPermission("", "*")));
assertTrue(new JndiPermission("*", "*").implies(new JndiPermission("foo", "*")));
assertFalse(new JndiPermission("*", "*").implies(new JndiPermission("foo/bar", "*")));
assertFalse(new JndiPermission("*", "*").implies(new JndiPermission("foo/", "*")));
assertFalse(new JndiPermission("*", "*").implies(new JndiPermission("/foo", "*")));
assertTrue(new JndiPermission("*/*", "*").implies(new JndiPermission("/foo", "*")));
assertTrue(new JndiPermission("/*", "*").implies(new JndiPermission("/foo", "*")));
assertTrue(new JndiPermission("*/foo", "*").implies(new JndiPermission("/foo", "*")));
// check java: support
assertEquals(new JndiPermission("java:", "*"), new JndiPermission("", "*"));
assertEquals(new JndiPermission("java:/", "*"), new JndiPermission("/", "*"));
assertEquals(new JndiPermission("java:-", "*"), new JndiPermission("-", "*"));
assertEquals(new JndiPermission("java:*", "*"), new JndiPermission("*", "*"));
}
@Test
public void testActions() {
assertEquals(new JndiPermission("foo", "*"), new JndiPermission("foo", "all"));
assertEquals(new JndiPermission("foo", "*"), new JndiPermission("foo", "lookup,bind,rebind,unbind,list,listBindings,createSubcontext,destroySubcontext,addNamingListener"));
assertEquals(new JndiPermission("foo", "*"), new JndiPermission("foo", "unbind,list,listBindings,createSubcontext,destroySubcontext,addNamingListener,lookup,bind,rebind"));
assertTrue(new JndiPermission("foo", "*").implies(new JndiPermission("foo", "lookup")));
assertTrue(new JndiPermission("foo", "").implies(new JndiPermission("foo", "")));
assertTrue(new JndiPermission("foo", "*").implies(new JndiPermission("foo", "")));
assertFalse(new JndiPermission("foo", "").implies(new JndiPermission("foo", "bind")));
assertTrue(new JndiPermission("foo", "").withActions("bind").implies(new JndiPermission("foo", "bind")));
assertFalse(new JndiPermission("foo", "unbind").withoutActions("unbind").implies(new JndiPermission("foo", "unbind")));
}
@Test
public void testCollection() {
final PermissionCollection permissionCollection = new JndiPermission("", "").newPermissionCollection();
Enumeration<Permission> e;
permissionCollection.add(new JndiPermission("foo/bar", "lookup,bind"));
assertTrue(permissionCollection.implies(new JndiPermission("foo/bar", "lookup,bind")));
assertFalse(permissionCollection.implies(new JndiPermission("foo/bar", "lookup,bind,unbind")));
assertFalse(permissionCollection.implies(new JndiPermission("foo/bar", "unbind")));
assertNotNull(e = permissionCollection.elements());
assertTrue(e.hasMoreElements());
assertEquals(new JndiPermission("foo/bar", "lookup,bind"), e.nextElement());
assertFalse(e.hasMoreElements());
permissionCollection.add(new JndiPermission("foo/bar", "unbind"));
assertTrue(permissionCollection.implies(new JndiPermission("foo/bar", "lookup,bind")));
assertTrue(permissionCollection.implies(new JndiPermission("foo/bar", "lookup,bind,unbind")));
assertTrue(permissionCollection.implies(new JndiPermission("foo/bar", "unbind")));
assertNotNull(e = permissionCollection.elements());
assertTrue(e.hasMoreElements());
assertEquals(new JndiPermission("foo/bar", "lookup,bind,unbind"), e.nextElement());
assertFalse(e.hasMoreElements());
permissionCollection.add(new JndiPermission("-", "lookup"));
assertTrue(permissionCollection.implies(new JndiPermission("foo/bar", "lookup,bind")));
assertTrue(permissionCollection.implies(new JndiPermission("foo/bar", "lookup,bind,unbind")));
assertTrue(permissionCollection.implies(new JndiPermission("foo/bar", "unbind")));
assertTrue(permissionCollection.implies(new JndiPermission("baz/zap", "lookup")));
assertTrue(permissionCollection.implies(new JndiPermission("", "lookup")));
assertFalse(permissionCollection.implies(new JndiPermission("baz/zap", "lookup,bind,unbind")));
assertFalse(permissionCollection.implies(new JndiPermission("baz/zap", "unbind")));
assertNotNull(e = permissionCollection.elements());
assertTrue(e.hasMoreElements());
assertEquals(new JndiPermission("foo/bar", "lookup,bind,unbind"), e.nextElement());
assertTrue(e.hasMoreElements());
assertEquals(new JndiPermission("-", "lookup"), e.nextElement());
assertFalse(e.hasMoreElements());
permissionCollection.add(new JndiPermission("-", "bind,unbind"));
assertTrue(permissionCollection.implies(new JndiPermission("foo/bar", "lookup,bind")));
assertTrue(permissionCollection.implies(new JndiPermission("foo/bar", "lookup,bind,unbind")));
assertTrue(permissionCollection.implies(new JndiPermission("foo/bar", "unbind")));
assertTrue(permissionCollection.implies(new JndiPermission("baz/zap", "lookup")));
assertTrue(permissionCollection.implies(new JndiPermission("", "lookup")));
assertTrue(permissionCollection.implies(new JndiPermission("baz/zap", "lookup,bind,unbind")));
assertTrue(permissionCollection.implies(new JndiPermission("baz/zap", "unbind")));
assertNotNull(e = permissionCollection.elements());
assertTrue(e.hasMoreElements());
assertEquals(new JndiPermission("-", "lookup,bind,unbind"), e.nextElement());
assertFalse(e.hasMoreElements());
}
@Test
public void testSecurity() {
assertEquals(new JndiPermission("-", Integer.MAX_VALUE).getActionBits(), JndiPermission.ACTION_ALL);
assertEquals(new JndiPermission("-", Integer.MAX_VALUE), new JndiPermission("-", "*"));
}
@Test
public void testSerialization() {
final JndiPermission jndiPermission = new JndiPermission("foo/blap/-", "bind,lookup");
assertEquals(jndiPermission, ((SerializedJndiPermission)jndiPermission.writeReplace()).readResolve());
}
@Test
public void testCollectionSecurity() {
final PermissionCollection permissionCollection = new JndiPermission("", "").newPermissionCollection();
permissionCollection.add(new JndiPermission("foo/bar", "unbind,rebind"));
permissionCollection.setReadOnly();
try {
permissionCollection.add(new JndiPermission("fob/baz", "unbind,rebind"));
fail("Expected exception");
} catch (SecurityException ignored) {
}
}
@Test
public void testCollectionSerialization() {
final PermissionCollection permissionCollection = new JndiPermission("", "").newPermissionCollection();
permissionCollection.add(new JndiPermission("foo/bar", "createSubcontext,rebind"));
permissionCollection.add(new JndiPermission("foo", "addNamingListener"));
permissionCollection.add(new JndiPermission("-", "lookup,rebind"));
final PermissionCollection other = (PermissionCollection) ((SerializedJndiPermissionCollection) ((JndiPermissionCollection)permissionCollection).writeReplace()).readResolve();
Enumeration<Permission> e;
assertNotNull(e = other.elements());
assertTrue(e.hasMoreElements());
assertEquals(new JndiPermission("foo/bar", "createSubcontext,rebind"), e.nextElement());
assertTrue(e.hasMoreElements());
assertEquals(new JndiPermission("foo", "addNamingListener"), e.nextElement());
assertTrue(e.hasMoreElements());
assertEquals(new JndiPermission("-", "lookup,rebind"), e.nextElement());
assertFalse(e.hasMoreElements());
}
}
| 11,583 | 59.333333 | 183 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ManagedReferenceObjectFactory.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import org.jboss.msc.service.ServiceName;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.Reference;
import java.util.Hashtable;
/**
* @author John Bailey
*/
public class ManagedReferenceObjectFactory extends ServiceReferenceObjectFactory {
public static Reference createReference(final ServiceName serviceName) {
return ServiceReferenceObjectFactory.createReference(serviceName, ManagedReferenceObjectFactory.class);
}
public Object getObjectInstance(final Object serviceValue, final Object obj, final Name name, final Context nameCtx, final Hashtable<?, ?> environment) throws Exception {
final ManagedReferenceFactory managedReferenceFactory = ManagedReferenceFactory.class.cast(serviceValue);
return managedReferenceFactory.getReference().getInstance();
}
}
| 1,889 | 40.086957 | 174 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/WritableServiceBasedNamingStore.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import org.jboss.as.naming.deployment.JndiNamingDependencyProcessor;
import org.jboss.as.naming.deployment.RuntimeBindReleaseService;
import org.jboss.as.naming.logging.NamingLogger;
import org.jboss.as.naming.service.BinderService;
import org.jboss.msc.service.LifecycleEvent;
import org.jboss.msc.service.LifecycleListener;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.common.function.ThreadLocalStack;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.OperationNotSupportedException;
import java.util.Hashtable;
import java.util.concurrent.CountDownLatch;
import static org.jboss.as.naming.util.NamingUtils.isLastComponentEmpty;
import static org.jboss.as.naming.util.NamingUtils.namingException;
/**
* @author John Bailey
* @author Eduardo Martins
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class WritableServiceBasedNamingStore extends ServiceBasedNamingStore implements WritableNamingStore {
private static final ThreadLocalStack WRITE_OWNER = new ThreadLocalStack();
private final ServiceTarget serviceTarget;
public WritableServiceBasedNamingStore(ServiceRegistry serviceRegistry, ServiceName serviceNameBase, ServiceTarget serviceTarget) {
super(serviceRegistry, serviceNameBase);
this.serviceTarget = serviceTarget;
}
public void bind(final Name name, final Object object, final Class<?> bindType) throws NamingException {
bind(name, object);
}
public void bind(final Name name, final Object object) throws NamingException {
final Object owner = requireOwner();
final ServiceName bindName = buildServiceName(name);
bind(name, object, owner, bindName);
}
private void bind(Name name, Object object, Object owner, ServiceName bindName) throws NamingException {
ServiceTarget serviceTarget = this.serviceTarget;
ServiceName deploymentUnitServiceName = null;
if (owner instanceof ServiceName) {
deploymentUnitServiceName = (ServiceName) owner;
} else {
serviceTarget = (ServiceTarget) owner;
}
try {
// unlike on deployment processors, we may assume here it's a shareable bind if the owner is a deployment, because deployment unshareable namespaces are readonly stores
final BinderService binderService = new BinderService(name.toString(), null, deploymentUnitServiceName != null);
binderService.getManagedObjectInjector().inject(new ImmediateManagedReferenceFactory(object));
final ServiceBuilder<?> builder = serviceTarget.addService(bindName, binderService)
.addDependency(getServiceNameBase(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector());
final ServiceController<?> binderServiceController = builder.install();
try {
binderServiceController.awaitValue();
} catch (final IllegalStateException t) {
final Exception startException = binderServiceController.getStartException();
if (startException != null) {
throw startException;
}
}
if (deploymentUnitServiceName != null) {
binderService.acquire();
final RuntimeBindReleaseService.References duBindingReferences = (RuntimeBindReleaseService.References) binderServiceController.getServiceContainer().getService(JndiNamingDependencyProcessor.serviceName(deploymentUnitServiceName)).getValue();
duBindingReferences.add(binderService);
}
} catch (Exception e) {
throw namingException("Failed to bind [" + object + "] at location [" + bindName + "]", e);
}
}
public void rebind(Name name, Object object) throws NamingException {
final Object owner = requireOwner();
// re-set the existent binder service injected value
final ServiceName bindName = buildServiceName(name);
final ServiceController<?> controller = getServiceRegistry().getService(bindName);
if (controller == null) {
bind(name, object, owner, bindName);
} else {
final BinderService binderService = (BinderService) controller.getService();
if (owner instanceof ServiceName) {
final ServiceName deploymentUnitServiceName = (ServiceName) owner;
binderService.acquire();
final RuntimeBindReleaseService.References duBindingReferences = (RuntimeBindReleaseService.References) controller.getServiceContainer().getService(JndiNamingDependencyProcessor.serviceName(deploymentUnitServiceName)).getValue();
duBindingReferences.add(binderService);
}
binderService.getManagedObjectInjector().setValue(() -> new ImmediateManagedReferenceFactory(object));
}
}
public void rebind(final Name name, final Object object, final Class<?> bindType) throws NamingException {
rebind(name, object);
}
public void unbind(final Name name) throws NamingException {
requireOwner();
final ServiceName bindName = buildServiceName(name);
final ServiceController<?> controller = getServiceRegistry().getService(bindName);
if (controller == null) {
throw NamingLogger.ROOT_LOGGER.cannotResolveService(bindName);
}
final CountDownLatch latch = new CountDownLatch(1);
controller.addListener(new LifecycleListener() {
@Override
public void handleEvent(final ServiceController<?> controller, final LifecycleEvent event) {
if (event == LifecycleEvent.REMOVED) latch.countDown();
}
});
try {
controller.setMode(ServiceController.Mode.REMOVE);
latch.await();
} catch (Exception e) {
throw namingException("Failed to unbind [" + bindName + "]", e);
}
}
public Context createSubcontext(final Name name) throws NamingException {
requireOwner();
if (isLastComponentEmpty(name)) {
throw NamingLogger.ROOT_LOGGER.emptyNameNotAllowed();
}
return new NamingContext(name, WritableServiceBasedNamingStore.this, new Hashtable<String, Object>());
}
private Object requireOwner() throws OperationNotSupportedException {
final Object owner = WRITE_OWNER.peek();
if (owner == null) {
throw NamingLogger.ROOT_LOGGER.readOnlyNamingContext();
}
return owner;
}
public static void pushOwner(final ServiceName deploymentUnitServiceName) {
WRITE_OWNER.push(deploymentUnitServiceName);
}
public static void pushOwner(final ServiceTarget serviceTarget) {
WRITE_OWNER.push(serviceTarget);
}
public static void popOwner() {
WRITE_OWNER.pop();
}
}
| 8,207 | 44.6 | 258 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/RequireResolveException.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import javax.naming.Name;
import javax.naming.NamingException;
/**
* Indicates that a naming store encountered a reference or a link when
* performing a list operation. This saves the store from having to know
* how to resolve the reference/link.
*
* @author Jason T. Greene
*/
public class RequireResolveException extends NamingException {
private Name resolve;
public RequireResolveException(Name resolve) {
this.resolve = resolve;
}
public Name getResolve() {
return resolve;
}
}
| 1,581 | 34.155556 | 72 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/NamingEventCoordinator.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import java.security.PrivilegedAction;
import java.util.concurrent.ThreadFactory;
import org.jboss.as.naming.util.FastCopyHashMap;
import javax.naming.Binding;
import javax.naming.Name;
import javax.naming.event.EventContext;
import javax.naming.event.NamespaceChangeListener;
import javax.naming.event.NamingEvent;
import javax.naming.event.NamingListener;
import javax.naming.event.ObjectChangeListener;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.jboss.threads.JBossThreadFactory;
import static java.security.AccessController.doPrivileged;
/**
* Coordinator responsible for passing @(code NamingEvent} instances to registered @{code NamingListener} instances. Two
* maps are used to managed a mapping between a listener and its configuration as well as a mapping from target name to a list
* of listener configurations. These maps are updated atomically on listener add and remove.
*
* @author John E. Bailey
*/
public class NamingEventCoordinator {
private volatile Map<TargetScope, List<ListenerHolder>> holdersByTarget = Collections.emptyMap();
private volatile Map<NamingListener, ListenerHolder> holdersByListener = Collections.emptyMap();
private final ThreadFactory threadFactory = doPrivileged(new PrivilegedAction<JBossThreadFactory>() {
public JBossThreadFactory run() {
return new JBossThreadFactory(new ThreadGroup("NamingEventCoordinator-threads"), Boolean.FALSE, null, "%G - %t", null, null);
}
});
private final Executor executor = Executors.newSingleThreadExecutor(threadFactory);
static final Integer[] DEFAULT_SCOPES = {EventContext.OBJECT_SCOPE, EventContext.ONELEVEL_SCOPE, EventContext.SUBTREE_SCOPE};
/**
* Add a listener to the coordinator with a given target name and event scope. This information is used when an
* event is fired to determine whether or not to fire this listener.
*
* @param target The target name to lister
* @param scope The event scope
* @param namingListener The listener
*/
synchronized void addListener(final String target, final int scope, final NamingListener namingListener) {
final TargetScope targetScope = new TargetScope(target, scope);
// Do we have a holder for this listener
ListenerHolder holder = holdersByListener.get(namingListener);
if (holder == null) {
holder = new ListenerHolder(namingListener, targetScope);
final Map<NamingListener, ListenerHolder> byListenerCopy = new FastCopyHashMap<NamingListener, ListenerHolder>(holdersByListener);
byListenerCopy.put(namingListener, holder);
holdersByListener = byListenerCopy;
} else {
holder.addTarget(targetScope);
}
List<ListenerHolder> holdersForTarget = holdersByTarget.get(targetScope);
if (holdersForTarget == null) {
holdersForTarget = new CopyOnWriteArrayList<ListenerHolder>();
final Map<TargetScope, List<ListenerHolder>> byTargetCopy = new FastCopyHashMap<TargetScope, List<ListenerHolder>>(holdersByTarget);
byTargetCopy.put(targetScope, holdersForTarget);
holdersByTarget = byTargetCopy;
}
holdersForTarget.add(holder);
}
/**
* Remove a listener. Will remove it from all target mappings. Once this method returns, the listener will no longer
* receive any events.
*
* @param namingListener The listener
*/
synchronized void removeListener(final NamingListener namingListener) {
// Do we have a holder for this listener
final ListenerHolder holder = holdersByListener.get(namingListener);
if (holder == null) {
return;
}
final Map<NamingListener, ListenerHolder> byListenerCopy = new FastCopyHashMap<NamingListener, ListenerHolder>(holdersByListener);
byListenerCopy.remove(namingListener);
holdersByListener = byListenerCopy;
final Map<TargetScope, List<ListenerHolder>> byTargetCopy = new FastCopyHashMap<TargetScope, List<ListenerHolder>>(holdersByTarget);
for (TargetScope targetScope : holder.targets) {
final List<ListenerHolder> holders = holdersByTarget.get(targetScope);
holders.remove(holder);
if (holders.isEmpty()) {
byTargetCopy.remove(targetScope);
}
}
holdersByTarget = byTargetCopy;
}
/**
* Fire a naming event. An event will be created with the provided information and sent to each listener that matches
* the target and scope information.
*
* @param context The event context generating the event.
* @param name The target name the event represents
* @param existingBinding The existing binding at the provided name
* @param newBinding The new binding at the provided name
* @param type The event type
* @param changeInfo The change info for the event
* @param scopes The scopes this event should be fired against
*/
void fireEvent(final EventContext context, final Name name, final Binding existingBinding, final Binding newBinding, int type, final String changeInfo, final Integer... scopes) {
final String target = name.toString();
final Set<Integer> scopeSet = new HashSet<Integer>(Arrays.asList(scopes));
final NamingEvent event = new NamingEvent(context, type, newBinding, existingBinding, changeInfo);
final Set<ListenerHolder> holdersToFire = new HashSet<ListenerHolder>();
// Check for OBJECT_SCOPE based listeners
if (scopeSet.contains(EventContext.OBJECT_SCOPE)) {
final TargetScope targetScope = new TargetScope(target, EventContext.OBJECT_SCOPE);
final List<ListenerHolder> holders = holdersByTarget.get(targetScope);
if (holders != null) {
for (ListenerHolder holder : holders) {
holdersToFire.add(holder);
}
}
}
// Check for ONELEVEL_SCOPE based listeners
if (scopeSet.contains(EventContext.ONELEVEL_SCOPE) && !name.isEmpty()) {
final TargetScope targetScope = new TargetScope(name.getPrefix(name.size() - 1).toString(), EventContext.ONELEVEL_SCOPE);
final List<ListenerHolder> holders = holdersByTarget.get(targetScope);
if (holders != null) {
for (ListenerHolder holder : holders) {
holdersToFire.add(holder);
}
}
}
// Check for SUBTREE_SCOPE based listeners
if (scopeSet.contains(EventContext.SUBTREE_SCOPE) && !name.isEmpty()) {
for (int i = 1; i < name.size(); i++) {
final Name parentName = name.getPrefix(i);
final TargetScope targetScope = new TargetScope(parentName.toString(), EventContext.SUBTREE_SCOPE);
final List<ListenerHolder> holders = holdersByTarget.get(targetScope);
if (holders != null) {
for (ListenerHolder holder : holders) {
holdersToFire.add(holder);
}
}
}
}
executor.execute(new FireEventTask(holdersToFire, event));
}
private class FireEventTask implements Runnable {
private final Set<ListenerHolder> listenerHolders;
private final NamingEvent event;
private FireEventTask(Set<ListenerHolder> listenerHolders, NamingEvent event) {
this.listenerHolders = listenerHolders;
this.event = event;
}
@Override
public void run() {
for (ListenerHolder holder : listenerHolders) {
final NamingListener listener = holder.listener;
switch (event.getType()) {
case NamingEvent.OBJECT_ADDED:
if (listener instanceof NamespaceChangeListener)
((NamespaceChangeListener) listener).objectAdded(event);
break;
case NamingEvent.OBJECT_REMOVED:
if (listener instanceof NamespaceChangeListener)
((NamespaceChangeListener) listener).objectRemoved(event);
break;
case NamingEvent.OBJECT_RENAMED:
if (listener instanceof NamespaceChangeListener)
((NamespaceChangeListener) listener).objectRenamed(event);
break;
case NamingEvent.OBJECT_CHANGED:
if (listener instanceof ObjectChangeListener)
((ObjectChangeListener) listener).objectChanged(event);
break;
}
}
}
}
private class ListenerHolder {
private volatile Set<TargetScope> targets = new HashSet<TargetScope>();
private final NamingListener listener;
private ListenerHolder(final NamingListener listener, final TargetScope initialTarget) {
this.listener = listener;
addTarget(initialTarget);
}
private synchronized void addTarget(final TargetScope targetScope) {
targets.add(targetScope);
}
}
private class TargetScope {
private final String target;
private final int scope;
private TargetScope(String target, int scope) {
this.target = target;
this.scope = scope;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TargetScope that = (TargetScope) o;
if (scope != that.scope) return false;
if (target != null ? !target.equals(that.target) : that.target != null) return false;
return true;
}
@Override
public int hashCode() {
int result = target != null ? target.hashCode() : 0;
result = 31 * result + scope;
return result;
}
}
}
| 11,458 | 42.078947 | 182 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/WritableNamingStore.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
/**
* A {@code NamingStore} that allows entries to be written as well as retrieved.
*
* @author John Bailey
*/
public interface WritableNamingStore extends NamingStore {
/**
* Bind and object into the naming store, creating parent contexts if needed. All parent contexts must be
* created before this can be executed. The bind object type will be determined by the class of the object being passed in.
*
* @param name The entry name
* @param object The entry object
* @throws javax.naming.NamingException If any problems occur
*/
void bind(Name name, Object object) throws NamingException;
/**
* Bind and object into the naming store, creating parent contexts if needed. All parent contexts must be
* created before this can be executed.
*
* @param name The entry name
* @param object The entry object
* @param bindType The entry class
* @throws NamingException If any problems occur
*/
void bind(Name name, Object object, Class<?> bindType) throws NamingException;
/**
* Re-bind and object into the naming store. All parent contexts must be created before this can be executed.
* The bind object type will be determined by the class of the object being passed in.
*
* @param name The entry name
* @param object The entry object
* @throws NamingException If any problems occur
*/
void rebind(Name name, Object object) throws NamingException;
/**
* Re-bind and object into the naming store. All parent contexts must be created before this can be executed.
*
* @param name The entry name
* @param object The entry object
* @param bindType The entry class
* @throws NamingException If any problems occur
*/
void rebind(Name name, Object object, Class<?> bindType) throws NamingException;
/**
* Unbind an object from the naming store. An entry for the name must exist.
*
* @param name The entry name
* @throws NamingException If any problems occur
*/
void unbind(Name name) throws NamingException;
/**
* Create a sub-context for the provided name.
*
* @param name The entry name
* @return The new sub-context
* @throws NamingException If any errors occur
*/
Context createSubcontext(Name name) throws NamingException;
}
| 3,547 | 36.347368 | 128 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/StaticManagedObject.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* A JNDI injectable which returns a static object and takes no action when the value is returned.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
* @author Eduardo Martins
*/
public final class StaticManagedObject implements ContextListManagedReferenceFactory,JndiViewManagedReferenceFactory {
private final Object value;
/**
* Construct a new instance.
*
* @param value the value to wrap
*/
public StaticManagedObject(final Object value) {
this.value = value;
}
@Override
public ManagedReference getReference() {
return new ManagedReference() {
@Override
public void release() {
}
@Override
public Object getInstance() {
return value;
}
};
}
@Override
public String getInstanceClassName() {
return value != null ? value.getClass().getName() : ContextListManagedReferenceFactory.DEFAULT_INSTANCE_CLASS_NAME;
}
@Override
public String getJndiViewInstanceValue() {
if (value == null) {
return "null";
}
final ClassLoader cl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(value.getClass().getClassLoader());
return value.toString();
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(cl);
}
}
}
| 2,645 | 32.075 | 123 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ContextListManagedReferenceFactory.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
/**
* A {@link ManagedReferenceFactory} which knows the class name of its {@link ManagedReference} object instance. This type of
* {@link ManagedReferenceFactory} should be used for JNDI bindings, the {@link ServiceBasedNamingStore} relies on it to provide
* proper support for {@link javax.naming.Context} list operations.
*
* @author Eduardo Martins
*
*/
public interface ContextListManagedReferenceFactory extends ManagedReferenceFactory {
String DEFAULT_INSTANCE_CLASS_NAME = Object.class.getName();
/**
* Retrieves the reference's object instance class name.
*
* If it's impossible to obtain such data, the factory should return the static attribute DEFAULT_INSTANCE_CLASS_NAME,
* exposed by this interface.
*
* @return
*/
String getInstanceClassName();
}
| 1,864 | 38.680851 | 128 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ImmediateManagedReference.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import java.io.Serializable;
/**
* A simple immediately-available {@link ManagedReference}'s instance.
*
* @author Eduardo Martins
*
*/
public class ImmediateManagedReference implements ManagedReference, Serializable {
private final Object instance;
public ImmediateManagedReference(final Object instance) {
this.instance = instance;
}
@Override
public void release() {
}
@Override
public Object getInstance() {
return instance;
}
}
| 1,542 | 29.86 | 82 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ImmediateManagedReferenceFactory.java
|
package org.jboss.as.naming;
/**
* @author Stuart Douglas
*/
public class ImmediateManagedReferenceFactory implements ManagedReferenceFactory {
private final ManagedReference reference;
public ImmediateManagedReferenceFactory(final Object value) {
this.reference = new ImmediateManagedReference(value);
}
@Override
public ManagedReference getReference() {
return reference;
}
}
| 424 | 21.368421 | 82 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/JndiViewManagedReferenceFactory.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
/**
* A {@link ManagedReferenceFactory} which supports JNDI View lookups, which are done without the proper invocation context set.
*
* @author Eduardo Martins
*
*/
public interface JndiViewManagedReferenceFactory extends ManagedReferenceFactory {
String DEFAULT_JNDI_VIEW_INSTANCE_VALUE = "?";
/**
* Retrieves the reference's object instance JNDI View value.
*
* If it's not possible to obtain such data, the factory should return the static attribute
* DEFAULT_JNDI_VIEW_INSTANCE_VALUE, exposed by this interface.
*
* @return
*/
String getJndiViewInstanceValue();
}
| 1,669 | 36.111111 | 128 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/InMemoryNamingStore.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import static org.jboss.as.naming.util.NamingUtils.cannotProceedException;
import static org.jboss.as.naming.util.NamingUtils.emptyNameException;
import static org.jboss.as.naming.util.NamingUtils.getLastComponent;
import static org.jboss.as.naming.util.NamingUtils.isEmpty;
import static org.jboss.as.naming.util.NamingUtils.isLastComponentEmpty;
import static org.jboss.as.naming.util.NamingUtils.nameAlreadyBoundException;
import static org.jboss.as.naming.util.NamingUtils.nameNotFoundException;
import static org.jboss.as.naming.util.NamingUtils.notAContextException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.ReentrantLock;
import javax.naming.Binding;
import javax.naming.CannotProceedException;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameNotFoundException;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.event.EventContext;
import javax.naming.event.NamingEvent;
import javax.naming.event.NamingListener;
import javax.naming.spi.ResolveResult;
import org.jboss.as.naming.logging.NamingLogger;
/**
* In-memory implementation of the NamingStore. The backing for the entries is a basic tree structure with either context
* nodes or binding nodes. The context nodes are allowed to have children and can be represented by a NamingContext. A
* binding node is only allowed to have a normal object binding.
*
* @author John E. Bailey
*/
public class InMemoryNamingStore implements WritableNamingStore {
/* The root node of the tree. Represents a JNDI name of "" */
private final ContextNode root = new ContextNode(null, null, new CompositeName(), new NamingContext(this, null));
/* Naming Event Coordinator */
private final NamingEventCoordinator eventCoordinator;
private final ReentrantLock writeLock = new ReentrantLock();
private final Name baseName;
/**
* Construct instance with no event support, and an empty base name.
*/
public InMemoryNamingStore() {
this(null, new CompositeName());
}
/**
* Construct instance with an event coordinator, and an empty base name.
*
* @param eventCoordinator The event coordinator
*/
public InMemoryNamingStore(final NamingEventCoordinator eventCoordinator) {
this(eventCoordinator, new CompositeName());
}
/**
* Construct instance with no event support, and the specified base name.
*
* @param baseName
*/
public InMemoryNamingStore(final Name baseName) {
this(null, baseName);
}
/**
* Construct instance with an event coordinator, and the specified base name.
*
* @param eventCoordinator
* @param baseName
*/
public InMemoryNamingStore(final NamingEventCoordinator eventCoordinator, final Name baseName) {
this.eventCoordinator = eventCoordinator;
if(baseName == null) {
throw new NullPointerException(NamingLogger.ROOT_LOGGER.cannotBeNull("baseName"));
}
this.baseName = baseName;
}
/** {@inheritDoc} */
public Name getBaseName() throws NamingException {
return baseName;
}
/** {@inheritDoc} */
public void bind(Name name, Object object) throws NamingException {
bind(name, object, object.getClass());
}
/** {@inheritDoc} */
public void bind(final Name name, final Object object, final Class<?> bindType) throws NamingException {
if (isLastComponentEmpty(name)) {
throw emptyNameException();
}
writeLock.lock();
try {
root.accept(new BindVisitor(true, name, object, bindType.getName()));
} finally {
writeLock.unlock();
}
}
/** {@inheritDoc} */
public void rebind(Name name, Object object) throws NamingException {
rebind(name, object, object.getClass());
}
/** {@inheritDoc} */
public void rebind(final Name name, final Object object, final Class<?> bindType) throws NamingException {
if (isLastComponentEmpty(name)) {
throw emptyNameException();
}
writeLock.lock();
try {
root.accept(new RebindVisitor(name, object, bindType.getName()));
} finally {
writeLock.unlock();
}
}
/**
* Unbind the entry in the provided location. This will remove the node in the tree and no longer manage it.
*
* @param name The entry name
* @throws NamingException
*/
public void unbind(final Name name) throws NamingException {
if (isLastComponentEmpty(name)) {
throw emptyNameException();
}
writeLock.lock();
try {
root.accept(new UnbindVisitor(name));
} finally {
writeLock.unlock();
}
}
/**
* Lookup the object value of a binding node in the tree.
*
* @param name The entry name
* @return The object value of the binding
* @throws NamingException
*/
public Object lookup(final Name name) throws NamingException {
if (isEmpty(name)) {
final Name emptyName = new CompositeName("");
return new NamingContext(emptyName, this, new Hashtable<String, Object>());
}
return root.accept(new LookupVisitor(name));
}
@Override
public Object lookup(Name name, boolean dereference) throws NamingException {
// ignoring dereference arg, it's not relevant to this store impl
return lookup(name);
}
/**
* List all NameClassPair instances at a given location in the tree.
*
* @param name The entry name
* @return The NameClassPair instances
* @throws NamingException
*/
public List<NameClassPair> list(final Name name) throws NamingException {
final Name nodeName = name.isEmpty() ? new CompositeName("") : name;
return root.accept(new ListVisitor(nodeName));
}
/**
* List all the Binding instances at a given location in the tree.
*
* @param name The entry name
* @return The Binding instances
* @throws NamingException
*/
public List<Binding> listBindings(final Name name) throws NamingException {
final Name nodeName = name.isEmpty() ? new CompositeName("") : name;
return root.accept(new ListBindingsVisitor(nodeName));
}
public Context createSubcontext(final Name name) throws NamingException {
if (isLastComponentEmpty(name)) {
throw emptyNameException();
}
return root.accept(new CreateSubContextVisitor(name));
}
/**
* Close the store. This will clear all children from the root node.
*
* @throws NamingException
*/
public void close() throws NamingException {
writeLock.lock();
try {
root.clear();
} finally {
writeLock.unlock();
}
}
/**
* Add a {@code NamingListener} to the naming event coordinator.
*
* @param target The target name to add the listener to
* @param scope The listener scope
* @param listener The listener
*/
public void addNamingListener(final Name target, final int scope, final NamingListener listener) {
final NamingEventCoordinator coordinator = eventCoordinator;
if (coordinator != null) {
coordinator.addListener(target.toString(), scope, listener);
}
}
/**
* Remove a {@code NamingListener} from the naming event coordinator.
*
* @param listener The listener
*/
public void removeNamingListener(final NamingListener listener) {
final NamingEventCoordinator coordinator = eventCoordinator;
if (coordinator != null) {
coordinator.removeListener(listener);
}
}
private void fireEvent(final ContextNode contextNode, final Name name, final Binding existingBinding, final Binding newBinding, final int type, final String changeInfo) {
final NamingEventCoordinator coordinator = eventCoordinator;
if (eventCoordinator != null) {
final Context context = Context.class.cast(contextNode.binding.getObject());
if(context instanceof EventContext) {
coordinator.fireEvent(EventContext.class.cast(context), name, existingBinding, newBinding, type, changeInfo, NamingEventCoordinator.DEFAULT_SCOPES);
}
}
}
private void checkReferenceForContinuation(final Name name, final Object object) throws CannotProceedException {
if (object instanceof Reference
&& ((Reference) object).get("nns") != null) {
throw cannotProceedException(object, name);
}
}
private abstract class TreeNode {
protected final Name fullName;
protected final Binding binding;
private TreeNode(final Name fullName, final Binding binding) {
this.fullName = fullName;
this.binding = binding;
}
protected abstract <T> T accept(NodeVisitor<T> visitor) throws NamingException;
}
private static final AtomicMapFieldUpdater<ContextNode, String, TreeNode> childrenUpdater = AtomicMapFieldUpdater.newMapUpdater(AtomicReferenceFieldUpdater.newUpdater(ContextNode.class, Map.class, "children"));
private class ContextNode extends TreeNode {
volatile Map<String, TreeNode> children = Collections.emptyMap();
protected final String name;
protected final ContextNode parentNode;
private ContextNode(final ContextNode parentNode, final String name, final Name fullName, final NamingContext context) {
super(fullName, new Binding(getLastComponent(fullName), Context.class.getName(), context));
this.name = name;
this.parentNode = parentNode;
}
private void addChild(final String childName, final TreeNode childNode) throws NamingException {
if (childrenUpdater.putIfAbsent(this, childName, childNode) != null) {
throw nameAlreadyBoundException(fullName.add(childName));
}
}
private TreeNode replaceChild(final String childName, final TreeNode childNode) throws NamingException {
return childrenUpdater.put(this, childName, childNode);
}
private TreeNode removeChild(final String childName) throws NameNotFoundException {
TreeNode old = childrenUpdater.remove(this, childName);
if (old == null) {
throw nameNotFoundException(childName, fullName);
}
if(parentNode != null && children.isEmpty()) {
childrenUpdater.remove(parentNode, name);
}
return old;
}
private void clear() {
childrenUpdater.clear(this);
}
protected final <T> T accept(NodeVisitor<T> visitor) throws NamingException {
return visitor.visit(this);
}
public TreeNode addOrGetChild(final String childName, final TreeNode childNode) {
TreeNode appearing = childrenUpdater.putIfAbsent(this, childName, childNode);
return appearing == null ? childNode : appearing;
}
}
private class BindingNode extends TreeNode {
private BindingNode(final Name fullName, final Binding binding) {
super(fullName, binding);
}
protected final <T> T accept(NodeVisitor<T> visitor) throws NamingException {
return visitor.visit(this);
}
}
private interface NodeVisitor<T> {
T visit(BindingNode bindingNode) throws NamingException;
T visit(ContextNode contextNode) throws NamingException;
}
private abstract class NodeTraversingVisitor<T> implements NodeVisitor<T> {
private final boolean createIfMissing;
private Name currentName;
private Name traversedName;
protected final Name targetName;
protected NodeTraversingVisitor(final boolean createIfMissing, final Name targetName) {
this.createIfMissing = createIfMissing;
this.targetName = currentName = targetName;
this.traversedName = new CompositeName();
}
protected NodeTraversingVisitor(final Name targetName) {
this(false, targetName);
}
public final T visit(final BindingNode bindingNode) throws NamingException {
if (isEmpty(currentName)) {
return found(bindingNode);
}
return foundReferenceInsteadOfContext(bindingNode);
}
public final T visit(final ContextNode contextNode) throws NamingException {
if (isEmpty(currentName)) {
return found(contextNode);
}
final String childName = currentName.get(0);
traversedName.add(childName);
currentName = currentName.getSuffix(1);
final TreeNode node = contextNode.children.get(childName);
if (node == null) {
if (createIfMissing) {
final NamingContext subContext = new NamingContext((Name)traversedName.clone(), InMemoryNamingStore.this, new Hashtable<String, Object>());
return contextNode.addOrGetChild(childName, new ContextNode(contextNode, childName, (Name)traversedName.clone(), subContext)).accept(this);
} else {
throw nameNotFoundException(childName, contextNode.fullName);
}
}
return node.accept(this);
}
protected abstract T found(ContextNode contextNode) throws NamingException;
protected abstract T found(BindingNode bindingNode) throws NamingException;
protected T foundReferenceInsteadOfContext(BindingNode bindingNode) throws NamingException {
final Object object = bindingNode.binding.getObject();
checkReferenceForContinuation(currentName, object);
throw notAContextException(bindingNode.fullName);
}
}
private abstract class BindingContextVisitor<T> extends NodeTraversingVisitor<T> {
protected final Name targetName;
protected BindingContextVisitor(final boolean createIfMissing, final Name targetName) {
super(createIfMissing, targetName.getPrefix(targetName.size() - 1));
this.targetName = targetName;
}
protected BindingContextVisitor(final Name targetName) {
this(false, targetName);
}
protected final T found(final ContextNode contextNode) throws NamingException {
return foundBindContext(contextNode);
}
protected final T found(final BindingNode bindingNode) throws NamingException {
checkReferenceForContinuation(targetName.getSuffix(bindingNode.fullName.size()), bindingNode.binding.getObject());
throw notAContextException(targetName);
}
protected abstract T foundBindContext(final ContextNode contextNode) throws NamingException;
}
private final class BindVisitor extends BindingContextVisitor<Void> {
private final Object object;
private final String className;
private BindVisitor(final boolean createIfMissing, final Name name, final Object object, final String className) {
super(createIfMissing, name);
this.object = object;
this.className = className;
}
protected Void foundBindContext(final ContextNode contextNode) throws NamingException {
final String childName = getLastComponent(targetName);
final Binding binding = new Binding(childName, className, object, true);
final BindingNode bindingNode = new BindingNode(targetName, binding);
contextNode.addChild(childName, bindingNode);
fireEvent(contextNode, targetName, null, binding, NamingEvent.OBJECT_ADDED, "bind");
return null;
}
}
private final class RebindVisitor extends BindingContextVisitor<Void> {
private final Object object;
private final String className;
private RebindVisitor(final Name name, final Object object, final String className) {
super(name);
this.object = object;
this.className = className;
}
protected Void foundBindContext(final ContextNode contextNode) throws NamingException {
final String childName = getLastComponent(targetName);
final Binding binding = new Binding(childName, className, object, true);
final BindingNode bindingNode = new BindingNode(targetName, binding);
final TreeNode previous = contextNode.replaceChild(childName, bindingNode);
final Binding previousBinding = previous != null ? previous.binding : null;
fireEvent(contextNode, targetName, previousBinding, binding, previousBinding != null ? NamingEvent.OBJECT_CHANGED : NamingEvent.OBJECT_ADDED, "rebind");
return null;
}
}
private final class UnbindVisitor extends BindingContextVisitor<Void> {
private UnbindVisitor(final Name targetName) throws NamingException {
super(targetName);
}
protected Void foundBindContext(final ContextNode contextNode) throws NamingException {
final TreeNode previous = contextNode.removeChild(getLastComponent(targetName));
fireEvent(contextNode, targetName, previous.binding, null, NamingEvent.OBJECT_REMOVED, "unbind");
return null;
}
}
private final class LookupVisitor extends NodeTraversingVisitor<Object> {
private LookupVisitor(final Name targetName) {
super(targetName);
}
protected Object found(final ContextNode contextNode) throws NamingException {
return contextNode.binding.getObject();
}
protected Object found(final BindingNode bindingNode) throws NamingException {
return bindingNode.binding.getObject();
}
protected Object foundReferenceInsteadOfContext(final BindingNode bindingNode) throws NamingException {
final Name remainingName = targetName.getSuffix(bindingNode.fullName.size());
final Object boundObject = bindingNode.binding.getObject();
checkReferenceForContinuation(remainingName, boundObject);
return new ResolveResult(boundObject, remainingName);
}
}
private final class ListVisitor extends NodeTraversingVisitor<List<NameClassPair>> {
private ListVisitor(final Name targetName) {
super(targetName);
}
protected List<NameClassPair> found(final ContextNode contextNode) throws NamingException {
final List<NameClassPair> nameClassPairs = new ArrayList<NameClassPair>();
for (TreeNode childNode : contextNode.children.values()) {
final Binding binding = childNode.binding;
nameClassPairs.add(new NameClassPair(binding.getName(), binding.getClassName(), true));
}
return nameClassPairs;
}
protected List<NameClassPair> found(final BindingNode bindingNode) throws NamingException {
checkReferenceForContinuation(new CompositeName(), bindingNode.binding.getObject());
throw notAContextException(targetName);
}
}
private final class ListBindingsVisitor extends NodeTraversingVisitor<List<Binding>> {
private ListBindingsVisitor(final Name targetName) {
super(targetName);
}
protected List<Binding> found(final ContextNode contextNode) throws NamingException {
final List<Binding> bindings = new ArrayList<Binding>();
for (TreeNode childNode : contextNode.children.values()) {
bindings.add(childNode.binding);
}
return bindings;
}
protected List<Binding> found(final BindingNode bindingNode) throws NamingException {
checkReferenceForContinuation(new CompositeName(), bindingNode.binding.getObject());
throw notAContextException(targetName);
}
}
private final class CreateSubContextVisitor extends BindingContextVisitor<Context> {
private CreateSubContextVisitor(final Name targetName) throws NamingException {
super(targetName);
}
protected Context foundBindContext(ContextNode contextNode) throws NamingException {
final NamingContext subContext = new NamingContext(targetName, InMemoryNamingStore.this, new Hashtable<String, Object>());
final String childName = getLastComponent(targetName);
final ContextNode subContextNode = new ContextNode(contextNode, childName, targetName, subContext);
contextNode.addChild(getLastComponent(targetName), subContextNode);
fireEvent(contextNode, targetName, null, subContextNode.binding, NamingEvent.OBJECT_ADDED, "createSubcontext");
return subContext;
}
}
}
| 22,434 | 38.428822 | 214 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ContextListAndJndiViewManagedReferenceFactory.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
/**
* A {@link ManagedReferenceFactory} which properly supports {@link javax.naming.Context} list operations, and JNDI View lookups.
*
* @author Eduardo Martins
*
*/
public interface ContextListAndJndiViewManagedReferenceFactory extends ContextListManagedReferenceFactory,
JndiViewManagedReferenceFactory {
}
| 1,370 | 38.171429 | 129 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ContextManagedReferenceFactory.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import javax.naming.Name;
import javax.naming.NamingException;
import org.jboss.as.naming.util.NameParser;
import org.jboss.msc.value.InjectedValue;
/**
* Managed reference factory used for binding a context.
*
* @author Stuart Douglas
* @author Eduardo Martins
*/
public class ContextManagedReferenceFactory implements ContextListAndJndiViewManagedReferenceFactory {
private final String name;
private final InjectedValue<NamingStore> namingStoreInjectedValue = new InjectedValue<NamingStore>();
public ContextManagedReferenceFactory(final String name) {
this.name = name;
}
@Override
public ManagedReference getReference() {
final NamingStore namingStore = namingStoreInjectedValue.getValue();
try {
final Name name = NameParser.INSTANCE.parse(this.name);
final NamingContext context = new NamingContext(name, namingStore, null);
return new ManagedReference() {
@Override
public void release() {
}
@Override
public Object getInstance() {
return context;
}
};
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
public InjectedValue<NamingStore> getNamingStoreInjectedValue() {
return namingStoreInjectedValue;
}
@Override
public String getInstanceClassName() {
return NamingContext.class.getName();
}
@Override
public String getJndiViewInstanceValue() {
return name;
}
}
| 2,656 | 31.402439 | 105 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ServiceAwareObjectFactory.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import javax.naming.spi.ObjectFactory;
import org.jboss.msc.service.ServiceRegistry;
/**
* Interface the should be implemented by {@link javax.naming.spi.ObjectFactory}s that require access to the {@link ServiceRegistry}.
* <p>
* After the object is created the {@link org.jboss.as.naming.context.ObjectFactoryBuilder} will inject the {@link ServiceRegistry}
*
* @author Stuart Douglas
*
*/
public interface ServiceAwareObjectFactory extends ObjectFactory {
void injectServiceRegistry(ServiceRegistry registry);
}
| 1,575 | 37.439024 | 133 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ManagedReferenceInjector.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import org.jboss.msc.inject.InjectionException;
import org.jboss.msc.inject.Injector;
/**
* A n adaptor between value injectors and ManagedReferenceFactory
*
* @author Stuart Douglas
*/
public class ManagedReferenceInjector<T> implements Injector<T> {
private final Injector<ManagedReferenceFactory> injectable;
public ManagedReferenceInjector(Injector<ManagedReferenceFactory> injectable) {
this.injectable = injectable;
}
@Override
public void inject(T value) throws InjectionException {
injectable.inject(new ValueManagedReferenceFactory(value));
}
@Override
public void uninject() {
injectable.uninject();
}
}
| 1,729 | 33.6 | 83 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ExternalContextObjectFactory.java
|
package org.jboss.as.naming;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Hashtable;
import java.util.concurrent.atomic.AtomicInteger;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.spi.ObjectFactory;
import org.jboss.as.server.deployment.ModuleClassFactory;
import org.jboss.invocation.proxy.ProxyConfiguration;
import org.jboss.invocation.proxy.ProxyFactory;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* An ObjectFactory that binds an arbitrary InitialContext into JNDI.
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class ExternalContextObjectFactory implements ObjectFactory {
private static final AtomicInteger PROXY_ID = new AtomicInteger();
public static final String CACHE_CONTEXT = "cache-context";
public static final String INITIAL_CONTEXT_CLASS = "initial-context-class";
public static final String INITIAL_CONTEXT_MODULE = "initial-context-module";
/**
* If this property is set to {@code true} in the {@code Context} environment, objects will be looked up
* by calling its {@link javax.naming.Context#lookup(String)} instead of {@link javax.naming.Context#lookup(javax.naming.Name)}.
*/
private static final String LOOKUP_BY_STRING = "org.jboss.as.naming.lookup.by.string";
private volatile Context cachedObject;
@Override
public Object getObjectInstance(final Object obj, final Name name, final Context nameCtx, final Hashtable<?, ?> environment) throws Exception {
String cacheString = (String) environment.get(CACHE_CONTEXT);
boolean cache = cacheString != null && cacheString.toLowerCase().equals("true");
if (cache) {
if (cachedObject == null) {
synchronized (this) {
if (cachedObject == null) {
cachedObject = createContext(environment, true);
}
}
}
return cachedObject;
} else {
return createContext(environment, false);
}
}
private Context createContext(final Hashtable<?, ?> environment, boolean useProxy) throws NamingException, ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException, ModuleLoadException {
String initialContextClassName = (String) environment.get(INITIAL_CONTEXT_CLASS);
String initialContextModule = (String) environment.get(INITIAL_CONTEXT_MODULE);
final boolean useStringLokup = useStringLookup(environment);
final Hashtable<?, ?> newEnvironment = new Hashtable<>(environment);
newEnvironment.remove(CACHE_CONTEXT);
newEnvironment.remove(INITIAL_CONTEXT_CLASS);
newEnvironment.remove(INITIAL_CONTEXT_MODULE);
newEnvironment.remove(LOOKUP_BY_STRING);
ClassLoader loader;
if (! WildFlySecurityManager.isChecking()) {
loader = getClass().getClassLoader();
} else {
loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return getClass().getClassLoader();
}
});
}
Class initialContextClass = null;
final Context loadedContext;
if (initialContextModule == null) {
initialContextClass = Class.forName(initialContextClassName);
Constructor ctor = initialContextClass.getConstructor(Hashtable.class);
loadedContext = (Context) ctor.newInstance(newEnvironment);
} else {
Module module = Module.getBootModuleLoader().loadModule(ModuleIdentifier.fromString(initialContextModule));
loader = module.getClassLoader();
final ClassLoader currentClassLoader = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(loader);
initialContextClass = Class.forName(initialContextClassName, true, loader);
Constructor ctor = initialContextClass.getConstructor(Hashtable.class);
loadedContext = (Context) ctor.newInstance(newEnvironment);
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(currentClassLoader);
}
}
final Context context;
if (useStringLokup) {
context = new LookupByStringContext(loadedContext);
} else {
context = loadedContext;
}
if (!useProxy) {
return context;
}
ProxyConfiguration config = new ProxyConfiguration();
config.setClassLoader(loader);
config.setSuperClass(initialContextClass);
config.setClassFactory(ModuleClassFactory.INSTANCE);
config.setProxyName(initialContextClassName + "$$$$Proxy" + PROXY_ID.incrementAndGet());
config.setProtectionDomain(context.getClass().getProtectionDomain());
ProxyFactory<?> factory = new ProxyFactory<Object>(config);
return (Context) factory.newInstance(new CachedContext(context));
}
/**
* A proxy implementation of Context that simply intercepts the
* close() method and ignores it since the underlying Context
* object is being maintained in memory.
*/
static class CachedContext implements InvocationHandler {
Context externalCtx;
CachedContext(Context externalCtx) {
this.externalCtx = externalCtx;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object value = null;
if (method.getName().equals("close")) {
// We just ignore the close method
} else {
try {
value = method.invoke(externalCtx, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
return value;
}
}
/**
* @return {@code true} if the environment contains a {@code LOOKUP_BY_STRING} property with a value corresponding to a {@code true} boolean, or {@code false} in any other case.
* @param environment
*/
private static boolean useStringLookup(Hashtable<?, ?> environment) {
Object val = environment.get(LOOKUP_BY_STRING);
if (val instanceof String) {
return Boolean.parseBoolean((String) val);
}
return false;
}
/**
* A wrapper around a {@code Context} that delegates {@link javax.naming.Name}-based lookup to
* their corresponding {@code String}-based method.
*/
private static class LookupByStringContext implements Context {
private final Context context;
LookupByStringContext(Context context) {
this.context = context;
}
@Override
public Object lookup(Name name) throws NamingException {
return context.lookup(name.toString());
}
@Override
public Object lookup(String name) throws NamingException {
return context.lookup(name);
}
@Override
public void bind(Name name, Object obj) throws NamingException {
context.bind(name, obj);
}
@Override
public void bind(String name, Object obj) throws NamingException {
context.bind(name, obj);
}
@Override
public void rebind(Name name, Object obj) throws NamingException {
context.rebind(name, obj);
}
@Override
public void rebind(String name, Object obj) throws NamingException {
context.rebind(name, obj);
}
@Override
public void unbind(Name name) throws NamingException {
context.unbind(name);
}
@Override
public void unbind(String name) throws NamingException {
context.unbind(name);
}
@Override
public void rename(Name oldName, Name newName) throws NamingException {
context.rename(oldName, newName);
}
@Override
public void rename(String oldName, String newName) throws NamingException {
context.rename(oldName, newName);
}
@Override
public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
return context.list(name);
}
@Override
public NamingEnumeration<NameClassPair> list(String name) throws NamingException {
return context.list(name);
}
@Override
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
return context.listBindings(name);
}
@Override
public NamingEnumeration<Binding> listBindings(String name) throws NamingException {
return context.listBindings(name);
}
@Override
public void destroySubcontext(Name name) throws NamingException {
context.destroySubcontext(name);
}
@Override
public void destroySubcontext(String name) throws NamingException {
context.destroySubcontext(name);
}
@Override
public Context createSubcontext(Name name) throws NamingException {
return context.createSubcontext(name);
}
@Override
public Context createSubcontext(String name) throws NamingException {
return context.createSubcontext(name);
}
@Override
public Object lookupLink(Name name) throws NamingException {
return context.lookupLink(name.toString());
}
@Override
public Object lookupLink(String name) throws NamingException {
return context.lookupLink(name);
}
@Override
public NameParser getNameParser(Name name) throws NamingException {
return context.getNameParser(name.toString());
}
@Override
public NameParser getNameParser(String name) throws NamingException {
return context.getNameParser(name);
}
@Override
public Name composeName(Name name, Name prefix) throws NamingException {
return context.composeName(name, prefix);
}
@Override
public String composeName(String name, String prefix) throws NamingException {
return context.composeName(name, prefix);
}
@Override
public Object addToEnvironment(String propName, Object propVal) throws NamingException {
return context.addToEnvironment(propName, propVal);
}
@Override
public Object removeFromEnvironment(String propName) throws NamingException {
return context.removeFromEnvironment(propName);
}
@Override
public Hashtable<?, ?> getEnvironment() throws NamingException {
return context.getEnvironment();
}
@Override
public void close() throws NamingException {
context.close();
}
@Override
public String getNameInNamespace() throws NamingException {
return context.getNameInNamespace();
}
}
}
| 11,903 | 35.40367 | 254 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/InitialContextFactoryBuilder.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import javax.naming.NamingException;
import java.util.Hashtable;
/**
* Initial context factory builder which ensures the proper naming context factory.
*
* @author John E. Bailey
* @author Eduardo Martins
*/
public class InitialContextFactoryBuilder implements javax.naming.spi.InitialContextFactoryBuilder {
private static final javax.naming.spi.InitialContextFactory DEFAULT_FACTORY = new InitialContextFactory();
/**
* Retrieves the default JBoss naming context factory.
*
* @param environment The environment
* @return An initial context factory
* @throws NamingException If an error occurs loading the factory class.
*/
public javax.naming.spi.InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) throws NamingException {
// return our default factory, the initial context it creates must be the responsible for handling a
// custom initial context factory in env, to ensure that URL factories are processed first, as the JDK does
return DEFAULT_FACTORY;
}
}
| 2,122 | 40.627451 | 131 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ManagedReference.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
/**
* A reference to a container managed object
*
* @author Stuart Douglas
*/
public interface ManagedReference {
/**
* Release the reference. Depending on the implementation this may destroy
* the underlying object.
* <p/>
* Implementers should take care to make this method idempotent,
* as it may be called multiple times.
*/
void release();
/**
* Get the object instance.
*
* @return the object this reference refers to
*/
Object getInstance();
}
| 1,568 | 33.108696 | 78 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ValueManagedReference.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import java.util.function.Supplier;
import org.jboss.msc.value.Value;
/**
* A ManagedReference that simply holds a value.
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public final class ValueManagedReference implements ManagedReference {
private final Supplier<?> value;
/**
* Construct a new instance.
*
* @param value the value to wrap
* @deprecated use {@link ValueManagedReference#ValueManagedReference(Object)} instead. This constructor will be removed in the future.
*/
@Deprecated
public ValueManagedReference(final Value<?> value) {
this.value = () -> value.getValue();
}
/**
* Construct a new instance.
*
* @param value the value to wrap
*/
public ValueManagedReference(final Object value) {
this.value = () -> value;
}
@Override
public void release() {
}
@Override
public Object getInstance() {
return value.get();
}
}
| 2,062 | 29.791045 | 139 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ManagedReferenceFactory.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
/**
* Creates container managed references.
* <p/>
* Usages of these references is very much implementation specific, however implementers should be
* careful to make sure that the references are idempotent.
*
* @author Stuart Douglas
*/
public interface ManagedReferenceFactory {
/**
* Get a new managed instance reference.
*
* @return a reference to a managed object
*/
ManagedReference getReference();
}
| 1,489 | 35.341463 | 98 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/NamingContext.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import static org.jboss.as.naming.logging.NamingLogger.ROOT_LOGGER;
import static org.jboss.as.naming.util.NamingUtils.isEmpty;
import static org.jboss.as.naming.util.NamingUtils.namingEnumeration;
import static org.jboss.as.naming.util.NamingUtils.namingException;
import static org.jboss.as.naming.util.NamingUtils.notAContextException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Hashtable;
import javax.naming.Binding;
import javax.naming.CannotProceedException;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.LinkRef;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.Referenceable;
import javax.naming.event.EventContext;
import javax.naming.event.NamingListener;
import javax.naming.spi.NamingManager;
import javax.naming.spi.ObjectFactory;
import javax.naming.spi.ResolveResult;
import org.wildfly.naming.java.permission.JndiPermission;
import org.jboss.as.naming.context.ObjectFactoryBuilder;
import org.jboss.as.naming.logging.NamingLogger;
import org.jboss.as.naming.util.NameParser;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Naming context implementation which proxies calls to a {@code NamingStore} instance. This context is
* read-only.
*
* @author John E. Bailey
*/
public class NamingContext implements EventContext {
/**
* A {@link org.jboss.as.naming.NamingPermission} needed to set the active {@link org.jboss.as.naming.NamingStore}. The name of the permission is "{@code setActiveNamingStore}."
*/
private static final NamingPermission SET_ACTIVE_NAMING_STORE = new NamingPermission("setActiveNamingStore");
/*
* The active naming store to use for any context created without a name store.
*/
private static volatile NamingStore ACTIVE_NAMING_STORE = new InMemoryNamingStore();
/**
* Set the active naming store
*
* @param namingStore The naming store
*/
public static void setActiveNamingStore(final NamingStore namingStore) {
if(WildFlySecurityManager.isChecking()) {
System.getSecurityManager().checkPermission(SET_ACTIVE_NAMING_STORE);
}
ACTIVE_NAMING_STORE = namingStore;
}
private static final String PACKAGE_PREFIXES = "org.jboss.as.naming.interfaces";
static {
try {
NamingManager.setObjectFactoryBuilder(ObjectFactoryBuilder.INSTANCE);
} catch(Throwable t) {
ROOT_LOGGER.failedToSet(t, "ObjectFactoryBuilder");
}
}
/**
* Initialize the naming components required by {@link javax.naming.spi.NamingManager}.
*/
public static void initializeNamingManager() {
// Setup naming environment
final String property = WildFlySecurityManager.getPropertyPrivileged(Context.URL_PKG_PREFIXES, null);
if(property == null || property.isEmpty()) {
WildFlySecurityManager.setPropertyPrivileged(Context.URL_PKG_PREFIXES, PACKAGE_PREFIXES);
} else if(!Arrays.asList(property.split(":")).contains(PACKAGE_PREFIXES)) {
WildFlySecurityManager.setPropertyPrivileged(Context.URL_PKG_PREFIXES, PACKAGE_PREFIXES + ":" + property);
}
try {
//If we are reusing the JVM. e.g. in tests we should not set this again
if (!NamingManager.hasInitialContextFactoryBuilder())
NamingManager.setInitialContextFactoryBuilder(new InitialContextFactoryBuilder());
} catch (NamingException e) {
ROOT_LOGGER.failedToSet(e, "InitialContextFactoryBuilder");
}
}
/* The naming store providing the back-end storage */
private final NamingStore namingStore;
/* The name prefix the context represents. */
private final Name prefix;
/* The environment configuration */
private final Hashtable environment;
/**
* Create a new naming context with no prefix or naming store. This will default to a prefix of "" and
* the active naming store.
*
* @param environment The naming environment
*/
public NamingContext(final Hashtable environment) {
this(new CompositeName(), ACTIVE_NAMING_STORE, environment);
}
/**
* Create a context with a prefix name.
*
* @param prefix The prefix for this context
* @param environment The naming environment
* @throws NamingException if an error occurs
*/
public NamingContext(final Name prefix, final Hashtable environment) throws NamingException {
this(prefix, ACTIVE_NAMING_STORE, environment);
}
/**
* Create a new naming context with a prefix name and a NamingStore instance to use as a backing.
*
* @param prefix The prefix for this context
* @param namingStore The NamingStore
* @param environment The naming environment
*/
public NamingContext(final Name prefix, final NamingStore namingStore, final Hashtable environment) {
if(prefix == null) {
throw NamingLogger.ROOT_LOGGER.nullVar("Naming prefix");
}
this.prefix = prefix;
if(namingStore == null) {
throw NamingLogger.ROOT_LOGGER.nullVar("NamingStore");
}
this.namingStore = namingStore;
if(environment != null) {
this.environment = new Hashtable(environment);
} else {
this.environment = new Hashtable();
}
}
/**
* Create a new naming context with the given namingStore and an empty name.
*
* @param namingStore the naming store to use
* @param environment the environment to use
*/
public NamingContext(final NamingStore namingStore, final Hashtable environment) {
this(new CompositeName(), namingStore, environment);
}
/** {@inheritDoc} */
public Object lookup(final Name name) throws NamingException {
return lookup(name, true);
}
/** {@inheritDoc} */
public Object lookup(final String name) throws NamingException {
return lookup(name, true);
}
public Object lookup(final String name, boolean dereference) throws NamingException {
return lookup(parseName(name), dereference);
}
public Object lookup(final Name name, boolean dereference) throws NamingException {
check(name, JndiPermission.ACTION_LOOKUP);
if (isEmpty(name)) {
return new NamingContext(prefix, namingStore, environment);
}
final Name absoluteName = getAbsoluteName(name);
Object result;
try {
result = namingStore.lookup(absoluteName,dereference);
} catch(CannotProceedException cpe) {
final Context continuationContext = NamingManager.getContinuationContext(cpe);
if (continuationContext instanceof NamingContext) {
result = ((NamingContext)continuationContext).lookup(cpe.getRemainingName(), dereference);
} else {
result = continuationContext.lookup(cpe.getRemainingName());
}
}
if (result instanceof ResolveResult) {
final ResolveResult resolveResult = (ResolveResult) result;
final Object resolvedObject = resolveResult.getResolvedObj();
Object context;
if (resolvedObject instanceof Context){
context = resolvedObject;
} else if (resolvedObject instanceof LinkRef) {
context = resolveLink(resolvedObject,dereference);
} else {
context = getObjectInstance(resolvedObject, absoluteName, environment);
}
if (!(context instanceof Context)) {
throw notAContextException(absoluteName.getPrefix(absoluteName.size() - resolveResult.getRemainingName().size()));
}
final Context namingContext = (Context) context;
if (namingContext instanceof NamingContext) {
return ((NamingContext)namingContext).lookup(resolveResult.getRemainingName(), dereference);
} else {
return namingContext.lookup(resolveResult.getRemainingName());
}
} else if (result instanceof LinkRef) {
result = resolveLink(result,dereference);
} else if (result instanceof Reference) {
result = getObjectInstance(result, absoluteName, environment);
if (result instanceof LinkRef) {
result = resolveLink(result,dereference);
}
}
return result;
}
/** {@inheritDoc} */
public void bind(final Name name, final Object object) throws NamingException {
check(name, JndiPermission.ACTION_BIND);
if(namingStore instanceof WritableNamingStore) {
final Name absoluteName = getAbsoluteName(name);
final Object value;
if (object instanceof Referenceable) {
value = ((Referenceable) object).getReference();
} else {
value = object;
}
if (System.getSecurityManager() == null) {
getWritableNamingStore().bind(absoluteName, value);
} else {
// The permissions check has already happened for the binding further permissions should be allowed
final NamingException e = AccessController.doPrivileged(new PrivilegedAction<NamingException>() {
@Override
public NamingException run() {
try {
getWritableNamingStore().bind(absoluteName, value);
} catch (NamingException e) {
return e;
}
return null;
}
});
// Check that a NamingException wasn't thrown during the bind
if (e != null) {
throw e;
}
}
} else {
throw NamingLogger.ROOT_LOGGER.readOnlyNamingContext();
}
}
/** {@inheritDoc} */
public void bind(final String name, final Object obj) throws NamingException {
bind(parseName(name), obj);
}
/** {@inheritDoc} */
public void rebind(final Name name, Object object) throws NamingException {
check(name, JndiPermission.ACTION_REBIND);
if(namingStore instanceof WritableNamingStore) {
final Name absoluteName = getAbsoluteName(name);
if (object instanceof Referenceable) {
object = ((Referenceable) object).getReference();
}
getWritableNamingStore().rebind(absoluteName, object);
} else {
throw NamingLogger.ROOT_LOGGER.readOnlyNamingContext();
}
}
/** {@inheritDoc} */
public void rebind(final String name, final Object object) throws NamingException {
rebind(parseName(name), object);
}
/** {@inheritDoc} */
public void unbind(final Name name) throws NamingException {
check(name, JndiPermission.ACTION_UNBIND);
if(namingStore instanceof WritableNamingStore) {
final Name absoluteName = getAbsoluteName(name);
getWritableNamingStore().unbind(absoluteName);
} else {
throw NamingLogger.ROOT_LOGGER.readOnlyNamingContext();
}
}
/** {@inheritDoc} */
public void unbind(final String name) throws NamingException {
unbind(parseName(name));
}
/** {@inheritDoc} */
public void rename(final Name oldName, final Name newName) throws NamingException {
//check for appropriate permissions first so that no other info leaks from this context
//in case of insufficient perms (like the fact if it is readonly or not)
check(oldName, JndiPermission.ACTION_LOOKUP | JndiPermission.ACTION_UNBIND);
check(newName, JndiPermission.ACTION_BIND);
if (namingStore instanceof WritableNamingStore) {
bind(newName, lookup(oldName));
unbind(oldName);
} else {
throw NamingLogger.ROOT_LOGGER.readOnlyNamingContext();
}
}
/** {@inheritDoc} */
public void rename(final String oldName, final String newName) throws NamingException {
rename(parseName(oldName), parseName(newName));
}
/** {@inheritDoc} */
public NamingEnumeration<NameClassPair> list(final Name name) throws NamingException {
check(name, JndiPermission.ACTION_LIST);
try {
return namingEnumeration(namingStore.list(getAbsoluteName(name)));
} catch(CannotProceedException cpe) {
final Context continuationContext = NamingManager.getContinuationContext(cpe);
return continuationContext.list(cpe.getRemainingName());
} catch (RequireResolveException r) {
final Object o = lookup(r.getResolve());
if (o instanceof Context) {
return ((Context)o).list(name.getSuffix(r.getResolve().size()));
}
throw notAContextException(r.getResolve());
}
}
/** {@inheritDoc} */
public NamingEnumeration<NameClassPair> list(final String name) throws NamingException {
return list(parseName(name));
}
/** {@inheritDoc} */
public NamingEnumeration<Binding> listBindings(final Name name) throws NamingException {
check(name, JndiPermission.ACTION_LIST_BINDINGS);
try {
return namingEnumeration(namingStore.listBindings(getAbsoluteName(name)));
} catch(CannotProceedException cpe) {
final Context continuationContext = NamingManager.getContinuationContext(cpe);
return continuationContext.listBindings(cpe.getRemainingName());
} catch (RequireResolveException r) {
final Object o = lookup(r.getResolve());
if (o instanceof Context) {
return ((Context)o).listBindings(name.getSuffix(r.getResolve().size()));
}
throw notAContextException(r.getResolve());
}
}
/** {@inheritDoc} */
public NamingEnumeration<Binding> listBindings(final String name) throws NamingException {
return listBindings(parseName(name));
}
/** {@inheritDoc} */
public void destroySubcontext(final Name name) throws NamingException {
check(name, JndiPermission.ACTION_DESTROY_SUBCONTEXT);
if(!(namingStore instanceof WritableNamingStore)) {
throw NamingLogger.ROOT_LOGGER.readOnlyNamingContext();
}
}
/** {@inheritDoc} */
public void destroySubcontext(String name) throws NamingException {
destroySubcontext(parseName(name));
}
/** {@inheritDoc} */
public Context createSubcontext(Name name) throws NamingException {
check(name, JndiPermission.ACTION_CREATE_SUBCONTEXT);
if(namingStore instanceof WritableNamingStore) {
final Name absoluteName = getAbsoluteName(name);
return getWritableNamingStore().createSubcontext(absoluteName);
} else {
throw NamingLogger.ROOT_LOGGER.readOnlyNamingContext();
}
}
/** {@inheritDoc} */
public Context createSubcontext(String name) throws NamingException {
return createSubcontext(parseName(name));
}
/** {@inheritDoc} */
public Object lookupLink(Name name) throws NamingException {
check(name, JndiPermission.ACTION_LOOKUP);
if (name.isEmpty()) {
return lookup(name);
}
try {
final Name absoluteName = getAbsoluteName(name);
Object link = namingStore.lookup(absoluteName);
if (!(link instanceof LinkRef) && link instanceof Reference) {
link = getObjectInstance(link, name, null);
}
return link;
} catch (Exception e) {
throw namingException(NamingLogger.ROOT_LOGGER.cannotLookupLink(), e, name);
}
}
/** {@inheritDoc} */
public Object lookupLink(String name) throws NamingException {
return lookupLink(parseName(name));
}
/** {@inheritDoc} */
public NameParser getNameParser(Name name) throws NamingException {
return NameParser.INSTANCE;
}
/** {@inheritDoc} */
public NameParser getNameParser(String name) throws NamingException {
return NameParser.INSTANCE;
}
/** {@inheritDoc} */
public Name composeName(Name name, Name prefix) throws NamingException {
final Name result = (Name) prefix.clone();
if (name instanceof CompositeName) {
if (name.size() == 1) {
// name could be a nested name
final String firstComponent = name.get(0);
result.addAll(parseName(firstComponent));
} else {
result.addAll(name);
}
} else {
result.addAll(new CompositeName(name.toString()));
}
return result;
}
/** {@inheritDoc} */
public String composeName(String name, String prefix) throws NamingException {
return composeName(parseName(name), parseName(prefix)).toString();
}
/** {@inheritDoc} */
public Object addToEnvironment(String propName, Object propVal) throws NamingException {
final Object existing = environment.get(propName);
environment.put(propName, propVal);
return existing;
}
/** {@inheritDoc} */
public Object removeFromEnvironment(String propName) throws NamingException {
return environment.remove(propName);
}
/** {@inheritDoc} */
public Hashtable<?, ?> getEnvironment() throws NamingException {
return environment;
}
/** {@inheritDoc} */
public void close() throws NamingException {
// NO-OP
}
/** {@inheritDoc} */
public String getNameInNamespace() throws NamingException {
return prefix.toString();
}
/** {@inheritDoc} */
public void addNamingListener(final Name target, final int scope, final NamingListener listener) throws NamingException {
check(target, JndiPermission.ACTION_ADD_NAMING_LISTENER);
namingStore.addNamingListener(target, scope, listener);
}
/** {@inheritDoc} */
public void addNamingListener(final String target, final int scope, final NamingListener listener) throws NamingException {
addNamingListener(parseName(target), scope, listener);
}
/** {@inheritDoc} */
public void removeNamingListener(final NamingListener listener) throws NamingException {
namingStore.removeNamingListener(listener);
}
/** {@inheritDoc} */
public boolean targetMustExist() throws NamingException {
return false;
}
private Name parseName(final String name) throws NamingException {
return getNameParser(name).parse(name);
}
private Name getAbsoluteName(final Name name) throws NamingException {
if(name.isEmpty()) {
return composeName(name, prefix);
}
final String firstComponent = name.get(0);
if(firstComponent.startsWith("java:")) {
final String cleaned = firstComponent.substring(5);
final Name suffix = name.getSuffix(1);
if(cleaned.isEmpty()) {
return suffix;
}
return suffix.add(0, cleaned);
} else if(firstComponent.isEmpty()) {
return name.getSuffix(1);
} else {
return composeName(name, prefix);
}
}
private Object getObjectInstance(final Object object, final Name name, final Hashtable<?, ?> environment) throws NamingException {
try {
final ObjectFactoryBuilder factoryBuilder = ObjectFactoryBuilder.INSTANCE;
final ObjectFactory objectFactory = factoryBuilder.createObjectFactory(object, environment);
return objectFactory == null ? null : objectFactory.getObjectInstance(object, name, this, environment);
} catch(NamingException e) {
throw e;
} catch(Throwable t) {
throw NamingLogger.ROOT_LOGGER.cannotDeferenceObject(t);
}
}
private Object resolveLink(Object result, boolean dereference) throws NamingException {
final Object linkResult;
try {
final LinkRef linkRef = (LinkRef) result;
final String referenceName = linkRef.getLinkName();
if (referenceName.startsWith("./")) {
linkResult = lookup(parseName(referenceName.substring(2)) ,dereference);
} else {
linkResult = new InitialContext().lookup(referenceName);
}
} catch (Throwable t) {
throw NamingLogger.ROOT_LOGGER.cannotDeferenceObject(t);
}
return linkResult;
}
private void check(Name name, int actions) throws NamingException {
final SecurityManager sm = System.getSecurityManager();
if (sm != null && WildFlySecurityManager.isChecking()) {
// build absolute name (including store's base name)
Name absoluteName = (Name) namingStore.getBaseName().clone();
if (name.isEmpty()) {
absoluteName.addAll(prefix);
} else {
final String firstComponent = name.get(0);
if (firstComponent.startsWith("java:")) {
absoluteName = name;
} else if (firstComponent.isEmpty()) {
absoluteName.addAll(name.getSuffix(1));
} else {
absoluteName.addAll(prefix);
if(name instanceof CompositeName) {
if (name.size() == 1) {
// name could be a nested name
absoluteName.addAll(parseName(firstComponent));
} else {
absoluteName.addAll(name);
}
} else {
absoluteName.addAll(new CompositeName(name.toString()));
}
}
}
sm.checkPermission(new JndiPermission(absoluteName.toString(), actions));
}
}
Name getPrefix() {
return prefix;
}
NamingStore getNamingStore() {
return namingStore;
}
WritableNamingStore getWritableNamingStore() {
return WritableNamingStore.class.cast(getNamingStore());
}
}
| 23,743 | 36.929712 | 181 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/InitialContext.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.spi.ObjectFactory;
import org.jboss.as.naming.context.NamespaceContextSelector;
import org.jboss.as.naming.logging.NamingLogger;
import org.wildfly.naming.client.WildFlyInitialContextFactory;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* @author Eduardo Martins
* @author John Bailey
*/
public class InitialContext extends InitialLdapContext {
/**
* Map of any additional naming schemes
*/
private static volatile Map<String, ObjectFactory> urlContextFactories = Collections.emptyMap();
private final WildFlyInitialContextFactory delegate = new WildFlyInitialContextFactory();
/**
* Add an ObjectFactory to handle requests for a specific URL scheme.
* @param scheme The URL scheme to handle.
* @param factory The ObjectFactory that can handle the requests.
*/
public static synchronized void addUrlContextFactory(final String scheme, ObjectFactory factory) {
Map<String, ObjectFactory> factories = new HashMap<String, ObjectFactory>(urlContextFactories);
factories.put(scheme, factory);
urlContextFactories = Collections.unmodifiableMap(factories);
}
/**
* Remove an ObjectFactory from the map of registered ones. To make sure that not anybody can remove an
* ObjectFactory both the scheme as well as the actual object factory itself need to be supplied. So you
* can only remove the factory if you have the factory object.
* @param scheme The URL scheme for which the handler is registered.
* @param factory The factory object associated with the scheme
* @throws IllegalArgumentException if the requested scheme/factory combination is not registered.
*/
public static synchronized void removeUrlContextFactory(final String scheme, ObjectFactory factory) {
Map<String, ObjectFactory> factories = new HashMap<String, ObjectFactory>(urlContextFactories);
ObjectFactory f = factories.get(scheme);
if (f == factory) {
factories.remove(scheme);
urlContextFactories = Collections.unmodifiableMap(factories);
return;
} else {
throw new IllegalArgumentException();
}
}
public InitialContext(Hashtable<?,?> environment) throws NamingException {
super(environment, null);
}
@SuppressWarnings("unchecked")
@Override
protected void init(Hashtable<?,?> environment) throws NamingException {
// the jdk initial context already worked out the env, no need to do it again
myProps = (Hashtable<Object, Object>) environment;
if (myProps != null && myProps.get(Context.INITIAL_CONTEXT_FACTORY) != null) {
// user has specified initial context factory; try to get it
getDefaultInitCtx();
}
}
@Override
protected Context getDefaultInitCtx() throws NamingException {
if (!gotDefault) {
// if there is an initial context factory prop in the env use it to create the default ctx
final String factoryClassName = myProps != null ? (String) myProps.get(Context.INITIAL_CONTEXT_FACTORY) : null;
if(factoryClassName == null || InitialContextFactory.class.getName().equals(factoryClassName)) {
defaultInitCtx = new DefaultInitialContext(myProps);
} else {
final ClassLoader classLoader = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
final Class<?> factoryClass = Class.forName(factoryClassName, true, classLoader);
defaultInitCtx = ((javax.naming.spi.InitialContextFactory)factoryClass.newInstance()).getInitialContext(myProps);
} catch (NamingException e) {
throw e;
} catch (Exception e) {
throw NamingLogger.ROOT_LOGGER.failedToInstantiate(e, "InitialContextFactory", factoryClassName, classLoader);
}
}
gotDefault = true;
}
return defaultInitCtx;
}
@Override
protected Context getURLOrDefaultInitCtx(String name) throws NamingException {
String scheme = getURLScheme(name);
if (scheme != null && !scheme.equals("java")) {
ObjectFactory factory = urlContextFactories.get(scheme);
if (factory != null) {
try {
return (Context) factory.getObjectInstance(null, null, null, myProps);
}catch(NamingException e) {
throw e;
} catch (Exception e) {
NamingException n = new NamingException(e.getMessage());
n.initCause(e);
throw n;
}
} else {
Context ctx = delegate.getInitialContext(myProps);
if(ctx!=null) {
return ctx;
}
}
}
return getDefaultInitCtx();
}
@Override
protected Context getURLOrDefaultInitCtx(Name name) throws NamingException {
if (name.size() > 0) {
return getURLOrDefaultInitCtx(name.get(0));
}
return getDefaultInitCtx();
}
public static String getURLScheme(String str) {
int colon_posn = str.indexOf(':');
int slash_posn = str.indexOf('/');
if (colon_posn > 0 && (slash_posn == -1 || colon_posn < slash_posn))
return str.substring(0, colon_posn);
return null;
}
private interface ParsedName {
String namespace();
Name remaining();
}
static class DefaultInitialContext extends NamingContext {
DefaultInitialContext(Hashtable<Object,Object> environment) {
super(environment);
}
private Context findContext(final Name name, final ParsedName parsedName) throws NamingException {
if (parsedName.namespace() == null || parsedName.namespace().equals("")) {
return null;
}
final NamespaceContextSelector selector = NamespaceContextSelector.getCurrentSelector();
if (selector == null) {
throw new NameNotFoundException(name.toString());
}
final Context namespaceContext = selector.getContext(parsedName.namespace());
if (namespaceContext == null) {
throw new NameNotFoundException(name.toString());
}
return namespaceContext;
}
private ParsedName parse(final Name name) throws NamingException {
final Name remaining;
final String namespace;
if (name.isEmpty()) {
namespace = null;
remaining = name;
} else {
final String first = name.get(0);
if (first.startsWith("java:")) {
final String theRest = first.substring(5);
if (theRest.startsWith("/")) {
namespace = null;
remaining = getNameParser(theRest).parse(theRest);
} else if (theRest.equals("jboss") && name.size() > 1 && name.get(1).equals("exported")) {
namespace = "jboss/exported";
remaining = name.getSuffix(2);
} else {
namespace = theRest;
remaining = name.getSuffix(1);
}
} else {
namespace = null;
remaining = name;
}
}
return new ParsedName() {
public String namespace() {
return namespace;
}
public Name remaining() {
return remaining;
}
};
}
public Object lookup(final Name name, boolean dereference) throws NamingException {
final ParsedName parsedName = parse(name);
final Context namespaceContext = findContext(name, parsedName);
if (namespaceContext == null)
return super.lookup(parsedName.remaining(),dereference);
else
return namespaceContext.lookup(parsedName.remaining());
}
public NamingEnumeration<Binding> listBindings(final Name name) throws NamingException {
final ParsedName parsedName = parse(name);
final Context namespaceContext = findContext(name, parsedName);
if (namespaceContext == null)
return super.listBindings(parsedName.remaining());
else
return namespaceContext.listBindings(parsedName.remaining());
}
public NamingEnumeration<NameClassPair> list(final Name name) throws NamingException {
final ParsedName parsedName = parse(name);
final Context namespaceContext = findContext(name, parsedName);
if (namespaceContext == null)
return super.list(parsedName.remaining());
else
return namespaceContext.list(parsedName.remaining());
}
public void bind(Name name, Object object) throws NamingException {
final ParsedName parsedName = parse(name);
final Context namespaceContext = findContext(name, parsedName);
if (namespaceContext == null)
super.bind(parsedName.remaining(), object);
else
namespaceContext.bind(parsedName.remaining(), object);
}
public void rebind(Name name, Object object) throws NamingException {
final ParsedName parsedName = parse(name);
final Context namespaceContext = findContext(name, parsedName);
if (namespaceContext == null)
super.rebind(parsedName.remaining(), object);
else
namespaceContext.rebind(parsedName.remaining(), object);
}
public void unbind(Name name) throws NamingException {
final ParsedName parsedName = parse(name);
final Context namespaceContext = findContext(name, parsedName);
if (namespaceContext == null)
super.unbind(parsedName.remaining());
else
namespaceContext.unbind(parsedName.remaining());
}
public void destroySubcontext(Name name) throws NamingException {
final ParsedName parsedName = parse(name);
final Context namespaceContext = findContext(name, parsedName);
if (namespaceContext == null)
super.destroySubcontext(parsedName.remaining());
else
namespaceContext.destroySubcontext(parsedName.remaining());
}
public Context createSubcontext(Name name) throws NamingException {
final ParsedName parsedName = parse(name);
final Context namespaceContext = findContext(name, parsedName);
if (namespaceContext == null)
return super.createSubcontext(parsedName.remaining());
else
return namespaceContext.createSubcontext(parsedName.remaining());
}
}
}
| 12,704 | 40.519608 | 133 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/AtomicMapFieldUpdater.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import org.jboss.as.naming.logging.NamingLogger;
import org.jboss.as.naming.util.FastCopyHashMap;
/**
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
final class AtomicMapFieldUpdater<C, K, V> {
private final AtomicReferenceFieldUpdater<C, Map<K, V>> updater;
@SuppressWarnings( { "unchecked" })
public static <C, K, V> AtomicMapFieldUpdater<C, K, V> newMapUpdater(AtomicReferenceFieldUpdater<C, Map> updater) {
return new AtomicMapFieldUpdater<C, K, V>(updater);
}
@SuppressWarnings( { "unchecked" })
AtomicMapFieldUpdater(AtomicReferenceFieldUpdater<C, Map> updater) {
this.updater = (AtomicReferenceFieldUpdater) updater;
}
public void clear(C instance) {
updater.set(instance, Collections.<K, V>emptyMap());
}
public V get(C instance, Object key) {
return updater.get(instance).get(key);
}
public V put(C instance, K key, V value) {
if (key == null) {
throw NamingLogger.ROOT_LOGGER.nullVar("key");
}
for (;;) {
final Map<K, V> oldMap = updater.get(instance);
final Map<K, V> newMap;
final V oldValue;
final int oldSize = oldMap.size();
if (oldSize == 0) {
oldValue = null;
newMap = Collections.singletonMap(key, value);
} else if (oldSize == 1) {
final Map.Entry<K, V> entry = oldMap.entrySet().iterator().next();
final K oldKey = entry.getKey();
if (oldKey.equals(key)) {
newMap = Collections.singletonMap(key, value);
oldValue = entry.getValue();
} else {
newMap = new FastCopyHashMap<K, V>(oldMap);
oldValue = newMap.put(key, value);
}
} else {
newMap = new FastCopyHashMap<K, V>(oldMap);
oldValue = newMap.put(key, value);
}
final boolean result = updater.compareAndSet(instance, oldMap, newMap);
if (result) {
return oldValue;
}
}
}
/**
* Put a value if and only if the map has not changed since the given snapshot was taken.
*
* @param instance the instance with the map field
* @param key the key
* @param value the value
* @param snapshot the map snapshot
* @return {@code value} if the snapshot is out of date, {@code null} if it succeeded, the existing value if the put failed
*/
public V putAtomic(C instance, K key, V value, Map<K, V> snapshot) {
if (key == null) {
throw NamingLogger.ROOT_LOGGER.nullVar("key");
}
final Map<K, V> newMap;
final int oldSize = snapshot.size();
if (oldSize == 0) {
newMap = Collections.singletonMap(key, value);
} else if (oldSize == 1) {
final Map.Entry<K, V> entry = snapshot.entrySet().iterator().next();
final K oldKey = entry.getKey();
if (oldKey.equals(key)) {
return entry.getValue();
} else {
newMap = new FastCopyHashMap<K, V>(snapshot);
newMap.put(key, value);
}
} else {
newMap = new FastCopyHashMap<K, V>(snapshot);
newMap.put(key, value);
}
if (updater.compareAndSet(instance, snapshot, newMap)) {
return null;
} else {
return value;
}
}
public V putIfAbsent(C instance, K key, V value) {
if (key == null) {
throw NamingLogger.ROOT_LOGGER.nullVar("key");
}
for (;;) {
final Map<K, V> oldMap = updater.get(instance);
final Map<K, V> newMap;
final int oldSize = oldMap.size();
if (oldSize == 0) {
newMap = Collections.singletonMap(key, value);
} else if (oldSize == 1) {
final Map.Entry<K, V> entry = oldMap.entrySet().iterator().next();
final K oldKey = entry.getKey();
if (oldKey.equals(key)) {
return entry.getValue();
} else {
newMap = new FastCopyHashMap<K, V>(oldMap);
newMap.put(key, value);
}
} else {
if (oldMap.containsKey(key)) {
return oldMap.get(key);
}
newMap = new FastCopyHashMap<K, V>(oldMap);
newMap.put(key, value);
}
if (updater.compareAndSet(instance, oldMap, newMap)) {
return null;
}
}
}
public V remove(C instance, K key) {
if (key == null) {
return null;
}
for (;;) {
final Map<K, V> oldMap = updater.get(instance);
final Map<K, V> newMap;
final V oldValue;
final int oldSize = oldMap.size();
if (oldSize == 0) {
return null;
} else if (oldSize == 1) {
final Map.Entry<K, V> entry = oldMap.entrySet().iterator().next();
if (entry.getKey().equals(key)) {
newMap = Collections.emptyMap();
oldValue = entry.getValue();
} else {
return null;
}
} else if (oldSize == 2) {
final Iterator<Map.Entry<K,V>> i = oldMap.entrySet().iterator();
final Map.Entry<K, V> entry = i.next();
final Map.Entry<K, V> next = i.next();
if (entry.getKey().equals(key)) {
newMap = Collections.singletonMap(next.getKey(), next.getValue());
oldValue = entry.getValue();
} else if (next.getKey().equals(key)) {
newMap = Collections.singletonMap(entry.getKey(), entry.getValue());
oldValue = next.getValue();
} else {
return null;
}
} else {
if (! oldMap.containsKey(key)) {
return null;
}
newMap = new FastCopyHashMap<K, V>(oldMap);
oldValue = newMap.remove(key);
}
if (updater.compareAndSet(instance, oldMap, newMap)) {
return oldValue;
}
}
}
public Map<K, V> get(final C subregistry) {
return updater.get(subregistry);
}
public Map<K, V> getReadOnly(final C subregistry) {
final Map<K, V> snapshot = updater.get(subregistry);
return snapshot instanceof FastCopyHashMap ? Collections.unmodifiableMap(snapshot) : snapshot;
}
}
| 8,028 | 36.694836 | 127 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ServiceReferenceObjectFactory.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.RefAddr;
import javax.naming.Reference;
import org.jboss.as.naming.context.ModularReference;
import org.jboss.as.naming.logging.NamingLogger;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceNotFoundException;
import org.jboss.msc.service.ServiceRegistry;
/**
* Abstract object factory that allows for the creation of service references. Object factories that subclass
* {@link ServiceReferenceObjectFactory} can get access to the value of the service described by the reference.
* <p/>
* If the factory state is no {@link State#UP} then the factory will block. If the state is {@link State#START_FAILED} or
* {@link State#REMOVED} (or the state transactions to one of these states while blocking) an exception is thrown.
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class ServiceReferenceObjectFactory implements ServiceAwareObjectFactory {
private volatile ServiceRegistry serviceRegistry;
/**
* Create a reference to a sub class of {@link ServiceReferenceObjectFactory} that injects the value of the given service.
*/
public static Reference createReference(final ServiceName service, Class<? extends ServiceReferenceObjectFactory> factory) {
return ModularReference.create(Context.class, new ServiceNameRefAdr("srof", service), factory);
}
@Override
public void injectServiceRegistry(ServiceRegistry registry) {
this.serviceRegistry = registry;
}
@SuppressWarnings("unchecked")
@Override
public final Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
final Reference reference = (Reference) obj;
final ServiceNameRefAdr nameAdr = (ServiceNameRefAdr) reference.get("srof");
if (nameAdr == null) {
throw NamingLogger.ROOT_LOGGER.invalidContextReference("srof");
}
final ServiceName serviceName = (ServiceName)nameAdr.getContent();
try {
final ServiceController<?> controller = serviceRegistry.getRequiredService(serviceName);
return getObjectInstance(controller.awaitValue(), obj, name, nameCtx, environment);
} catch (ServiceNotFoundException e) {
throw NamingLogger.ROOT_LOGGER.cannotResolveService(serviceName);
} catch (InterruptedException e) {
throw NamingLogger.ROOT_LOGGER.threadInterrupt(serviceName);
} catch (Throwable t) {
throw NamingLogger.ROOT_LOGGER.cannotResolveService(serviceName, getClass().getName(), "START_FAILED");
}
}
/**
* Handles the service reference. The parameters are the same as
* {@link javax.naming.spi.ObjectFactory#getObjectInstance(Object, Name, Context, Hashtable)}, but with the addition of the service value as
* the first parameter.
*/
public Object getObjectInstance(Object serviceValue, Object obj, Name name, Context nameCtx,
Hashtable<?, ?> environment) throws Exception {
return serviceValue;
}
private static final class ServiceNameRefAdr extends RefAddr {
private static final long serialVersionUID = 3677121114687908679L;
private final ServiceName serviceName;
private ServiceNameRefAdr(String s, ServiceName serviceName) {
super(s);
this.serviceName = serviceName;
}
public Object getContent() {
return serviceName;
}
}
}
| 4,747 | 42.163636 | 144 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ValueManagedReferenceFactory.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import java.io.Serializable;
import java.util.function.Supplier;
import org.jboss.msc.value.Value;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* A JNDI injectable which simply uses a value and takes no action when the value is returned.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
* @author Eduardo Martins
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public final class ValueManagedReferenceFactory implements ContextListAndJndiViewManagedReferenceFactory {
private final Supplier<?> value;
/**
* Construct a new instance.
*
* @param value the value to wrap
* @deprecated use {@link ValueManagedReferenceFactory#ValueManagedReferenceFactory(Object)} instead. This constructor will be removed in the future.
*/
@Deprecated
public ValueManagedReferenceFactory(final Value<?> value) {
this.value = () -> value.getValue();
}
/**
* Construct a new instance.
*
* @param value the value to wrap
*/
public ValueManagedReferenceFactory(final Object value) {
this.value = () -> value;
}
@Override
public ManagedReference getReference() {
return new ValueManagedReference(value.get());
}
@Override
public String getInstanceClassName() {
final Object instance = value != null ? value.get() : null;
if(instance == null) {
return ContextListManagedReferenceFactory.DEFAULT_INSTANCE_CLASS_NAME;
}
return instance.getClass().getName();
}
@Override
public String getJndiViewInstanceValue() {
final Object instance = value != null ? value.get() : null;
if (instance == null) {
return "null";
}
final ClassLoader cl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(instance.getClass().getClassLoader());
return instance.toString();
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(cl);
}
}
public static class ValueManagedReference implements ManagedReference, Serializable {
private static final long serialVersionUID = 1L;
private ValueManagedReference(final Object instance) {
this.instance = instance;
}
private volatile Object instance;
@Override
public void release() {
this.instance = null;
}
@Override
public Object getInstance() {
return this.instance;
}
}
}
| 3,713 | 32.459459 | 153 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ConstructorManagedReferenceFactory.java
|
package org.jboss.as.naming;
import java.lang.reflect.Constructor;
/**
* Managed reference that creates an instance from the constructor.
*
* @author Stuart Douglas
*/
public class ConstructorManagedReferenceFactory implements ManagedReferenceFactory {
private final Constructor<?> constructor;
public ConstructorManagedReferenceFactory(Constructor<?> constructor) {
this.constructor = constructor;
}
@Override
public ManagedReference getReference() {
try {
return new ImmediateManagedReference(constructor.newInstance());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 674 | 23.107143 | 84 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/InitialContextFactory.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import javax.naming.Context;
import javax.naming.NamingException;
import java.util.Hashtable;
/**
* Initial context factory which returns {@code NamingContext} instances.
*
* @author John E. Bailey
*/
public class InitialContextFactory implements javax.naming.spi.InitialContextFactory {
/**
* Get an initial context instance.
*
* @param environment The naming environment
* @return A naming context instance
* @throws NamingException
*/
public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
return new InitialContext(environment);
}
}
| 1,678 | 35.5 | 90 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/ServiceBasedNamingStore.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.NavigableSet;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;
import javax.naming.Binding;
import javax.naming.CannotProceedException;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.InvalidNameException;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameNotFoundException;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.event.NamingListener;
import javax.naming.spi.ResolveResult;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.logging.NamingLogger;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* @author John Bailey
* @author Jason T. Greene
* @author Eduardo Martins
*/
public class ServiceBasedNamingStore implements NamingStore {
private final Name EMPTY_NAME = new CompositeName();
private Name baseName;
private final ServiceRegistry serviceRegistry;
private final ServiceName serviceNameBase;
private ConcurrentSkipListSet<ServiceName> boundServices = new ConcurrentSkipListSet<ServiceName>();
public ServiceBasedNamingStore(final ServiceRegistry serviceRegistry, final ServiceName serviceNameBase) {
this.serviceRegistry = serviceRegistry;
this.serviceNameBase = serviceNameBase;
}
@Override
public Object lookup(Name name) throws NamingException {
return lookup(name, true);
}
public Object lookup(final Name name, boolean dereference) throws NamingException {
if (name.isEmpty()) {
return new NamingContext(EMPTY_NAME, this, null);
}
final ServiceName lookupName = buildServiceName(name);
Object obj = lookup(name.toString(), lookupName, dereference);
if (obj == null) {
final ServiceName lower = boundServices.lower(lookupName);
if (lower != null && lower.isParentOf(lookupName)) {
// Parent might be a reference or a link
obj = lookup(name.toString(), lower, dereference);
//if the lower is a context that has been explicitly bound then
//we do not return a resolve result, as this will result in an
//infinite loop
if (!(obj instanceof NamingContext)) {
checkReferenceForContinuation(name, obj);
return new ResolveResult(obj, suffix(lower, lookupName));
}
}
final ServiceName ceiling = boundServices.ceiling(lookupName);
if (ceiling != null && lookupName.isParentOf(ceiling)) {
if (lookupName.equals(ceiling)) {
//the binder service returned null
return null;
}
return new NamingContext((Name) name.clone(), this, null);
}
throw new NameNotFoundException(name.toString() + " -- " + lookupName);
}
return obj;
}
private void checkReferenceForContinuation(final Name name, final Object object) throws CannotProceedException {
if (object instanceof Reference
&& ((Reference) object).get("nns") != null) {
throw cannotProceedException(object, name);
}
}
private static CannotProceedException cannotProceedException(final Object resolvedObject, final Name remainingName) {
final CannotProceedException cpe = new CannotProceedException();
cpe.setResolvedObj(resolvedObject);
cpe.setRemainingName(remainingName);
return cpe;
}
private Object lookup(final String name, final ServiceName lookupName, boolean dereference) throws NamingException {
try {
final ServiceController<?> controller = serviceRegistry.getService(lookupName);
if (controller != null) {
final Object object = controller.getValue();
if (dereference && object instanceof ManagedReferenceFactory) {
if(WildFlySecurityManager.isChecking()) {
//WFLY-3487 JNDI lookups should be executed in a clean access control context
return AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
final ManagedReference managedReference = ManagedReferenceFactory.class.cast(object).getReference();
return managedReference != null ? managedReference.getInstance() : null;
}
});
} else {
final ManagedReference managedReference = ManagedReferenceFactory.class.cast(object).getReference();
return managedReference != null ? managedReference.getInstance() : null;
}
} else {
return object;
}
} else {
return null;
}
} catch (IllegalStateException e) {
NameNotFoundException n = new NameNotFoundException(name);
n.initCause(e);
throw n;
} catch (SecurityException ex) {
throw ex;
} catch (Throwable t) {
throw NamingLogger.ROOT_LOGGER.lookupError(t, name);
}
}
public List<NameClassPair> list(final Name name) throws NamingException {
final ServiceName lookupName = buildServiceName(name);
final ServiceName floor = boundServices.floor(lookupName);
boolean isContextBinding = false;
if (floor != null && floor.isParentOf(lookupName)) {
// Parent might be a reference or a link
Object obj = lookup(name.toString(), floor, true);
if (obj instanceof NamingContext) {
isContextBinding = true;
} else if (obj != null) {
throw new RequireResolveException(convert(floor));
}
}
final List<ServiceName> children = listChildren(lookupName, isContextBinding);
final String[] lookupParts = lookupName.toArray();
final Set<String> childContexts = new HashSet<String>();
final List<NameClassPair> results = new ArrayList<NameClassPair>();
for (ServiceName child : children) {
final String[] childParts = child.toArray();
if (childParts.length > lookupParts.length + 1) {
childContexts.add(childParts[lookupParts.length]);
} else {
final Object binding = lookup(name.toString(), child, false);
if (binding != null) {
final String bindingType;
if (binding instanceof ContextListManagedReferenceFactory) {
bindingType = ContextListManagedReferenceFactory.class.cast(binding).getInstanceClassName();
} else {
if (binding instanceof ManagedReferenceFactory) {
bindingType = ContextListManagedReferenceFactory.DEFAULT_INSTANCE_CLASS_NAME;
} else {
bindingType = binding.getClass().getName();
}
}
results.add(new NameClassPair(childParts[childParts.length - 1], bindingType));
}
}
}
for (String contextName : childContexts) {
results.add(new NameClassPair(contextName, Context.class.getName()));
}
return results;
}
public List<Binding> listBindings(final Name name) throws NamingException {
final ServiceName lookupName = buildServiceName(name);
final ServiceName floor = boundServices.floor(lookupName);
boolean isContextBinding = false;
if (floor != null && floor.isParentOf(lookupName)) {
// Parent might be a reference or a link
Object obj = lookup(name.toString(), floor, true);
if (obj instanceof NamingContext) {
isContextBinding = true;
} else if (obj != null) {
throw new RequireResolveException(convert(floor));
}
}
final List<ServiceName> children = listChildren(lookupName, isContextBinding);
final String[] lookupParts = lookupName.toArray();
final Set<String> childContexts = new HashSet<String>();
final List<Binding> results = new ArrayList<Binding>();
for (ServiceName child : children) {
final String[] childParts = child.toArray();
if (childParts.length > lookupParts.length + 1) {
childContexts.add(childParts[lookupParts.length]);
} else {
final Object binding = lookup(name.toString(), child, true);
results.add(new Binding(childParts[childParts.length - 1], binding));
}
}
for (String contextName : childContexts) {
results.add(new Binding(contextName, new NamingContext(((Name) name.clone()).add(contextName), this, null)));
}
return results;
}
private List<ServiceName> listChildren(final ServiceName name, boolean isContextBinding) throws NamingException {
final ConcurrentSkipListSet<ServiceName> boundServices = this.boundServices;
if (!isContextBinding && boundServices.contains(name)) {
throw NamingLogger.ROOT_LOGGER.cannotListNonContextBinding();
}
final NavigableSet<ServiceName> tail = boundServices.tailSet(name);
final List<ServiceName> children = new ArrayList<ServiceName>();
for (ServiceName next : tail) {
if (name.isParentOf(next)) {
if (!name.equals(next)) {
children.add(next);
}
} else {
break;
}
}
return children;
}
public void close() throws NamingException {
boundServices.clear();
}
public void addNamingListener(Name target, int scope, NamingListener listener) {
}
public void removeNamingListener(NamingListener listener) {
}
public void add(final ServiceName serviceName) {
final ConcurrentSkipListSet<ServiceName> boundServices = this.boundServices;
if (boundServices.contains(serviceName)) {
throw NamingLogger.ROOT_LOGGER.serviceAlreadyBound(serviceName);
}
boundServices.add(serviceName);
}
public void remove(final ServiceName serviceName) {
boundServices.remove(serviceName);
}
protected ServiceName buildServiceName(final Name name) {
final Enumeration<String> parts = name.getAll();
ServiceName current = serviceNameBase;
while (parts.hasMoreElements()) {
final String currentPart = parts.nextElement();
if (!currentPart.isEmpty()) {
current = current.append(currentPart);
}
}
return current;
}
private Name convert(ServiceName serviceName) {
String[] c = serviceName.toArray();
CompositeName name = new CompositeName();
int baseIndex = serviceNameBase.toArray().length;
for (int i = baseIndex; i < c.length; i++) {
try {
name.add(c[i]);
} catch (InvalidNameException e) {
throw new IllegalStateException(e);
}
}
return name;
}
private Name suffix(ServiceName parent, ServiceName child) {
String[] p = parent.toArray();
String[] c = child.toArray();
CompositeName name = new CompositeName();
for (int i = p.length; i < c.length; i++) {
try {
name.add(c[i]);
} catch (InvalidNameException e) {
throw new IllegalStateException(e);
}
}
return name;
}
protected ServiceName getServiceNameBase() {
return serviceNameBase;
}
protected ServiceRegistry getServiceRegistry() {
return serviceRegistry;
}
@Override
public Name getBaseName() throws NamingException {
if (baseName == null) {
baseName = setBaseName();
}
return baseName;
}
private Name setBaseName() throws NamingException {
if (serviceNameBase.equals(ContextNames.EXPORTED_CONTEXT_SERVICE_NAME)
|| ContextNames.EXPORTED_CONTEXT_SERVICE_NAME.isParentOf(serviceNameBase)) {
return new CompositeName("java:jboss/exported");
}
if (serviceNameBase.equals(ContextNames.JBOSS_CONTEXT_SERVICE_NAME)
|| ContextNames.JBOSS_CONTEXT_SERVICE_NAME.isParentOf(serviceNameBase)) {
return new CompositeName("java:jboss");
}
if (serviceNameBase.equals(ContextNames.APPLICATION_CONTEXT_SERVICE_NAME)
|| ContextNames.APPLICATION_CONTEXT_SERVICE_NAME.isParentOf(serviceNameBase)) {
return new CompositeName("java:app");
}
if (serviceNameBase.equals(ContextNames.MODULE_CONTEXT_SERVICE_NAME)
|| ContextNames.MODULE_CONTEXT_SERVICE_NAME.isParentOf(serviceNameBase)) {
return new CompositeName("java:module");
}
if (serviceNameBase.equals(ContextNames.COMPONENT_CONTEXT_SERVICE_NAME)
|| ContextNames.COMPONENT_CONTEXT_SERVICE_NAME.isParentOf(serviceNameBase)) {
return new CompositeName("java:comp");
}
if (serviceNameBase.equals(ContextNames.GLOBAL_CONTEXT_SERVICE_NAME)
|| ContextNames.GLOBAL_CONTEXT_SERVICE_NAME.isParentOf(serviceNameBase)) {
return new CompositeName("java:global");
}
if (serviceNameBase.equals(ContextNames.JAVA_CONTEXT_SERVICE_NAME)
|| ContextNames.JAVA_CONTEXT_SERVICE_NAME.isParentOf(serviceNameBase)) {
return new CompositeName("java:");
}
return new CompositeName();
}
}
| 15,464 | 40.684636 | 132 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/NamingPermission.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import java.security.BasicPermission;
/**
* <p>
* This class is for WildFly Naming's permissions. A permission
* contains a name (also referred to as a "target name") but
* no actions list; you either have the named permission
* or you don't.
* </p>
*
* <p>
* The naming convention follows the hierarchical property naming convention.
* An asterisk may appear by itself, or if immediately preceded by a "."
* may appear at the end of the name, to signify a wildcard match.
* </p>
*
* <p>
* The target name is the name of the permission. The following table lists all the possible permission target names,
* and for each provides a description of what the permission allows.
* </p>
*
* <p>
* <table border=1 cellpadding=5 summary="permission target name,
* what the target allows">
* <tr>
* <th>Permission Target Name</th>
* <th>What the Permission Allows</th>
* </tr>
*
* <tr>
* <td>setActiveNamingStore</td>
* <td>Set the active {@link org.jboss.as.naming.NamingStore}</td>
* </tr>
*
* </table>
* </p>
* @author Eduardo Martins
*/
public class NamingPermission extends BasicPermission {
/**
* Creates a new permission with the specified name.
* The name is the symbolic name of the permission, such as
* "setActiveNamingStore".
*
* @param name the name of the permission.
*
* @throws NullPointerException if <code>name</code> is <code>null</code>.
* @throws IllegalArgumentException if <code>name</code> is empty.
*/
public NamingPermission(String name) {
super(name);
}
/**
* Creates a new permission object with the specified name.
* The name is the symbolic name of the permission, and the
* actions String is currently unused and should be null.
*
* @param name the name of the permission.
* @param actions should be null.
*
* @throws NullPointerException if <code>name</code> is <code>null</code>.
* @throws IllegalArgumentException if <code>name</code> is empty.
*/
public NamingPermission(String name, String actions) {
super(name, actions);
}
}
| 3,185 | 33.630435 | 117 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/NamingStore.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import java.util.List;
import javax.naming.Binding;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NamingException;
import javax.naming.event.NamingListener;
/**
* Interface to layout a contract for naming entry back-end storage. This will be used by {@code NamingContext} instances
* to manage naming entries.
*
* @author John E. Bailey
* @author Eduardo Martins
*/
public interface NamingStore {
/**
* Retrieves the store's base name, which is the prefix for the absolute name of each entry in the store.
* @return
* @throws NamingException
*/
Name getBaseName() throws NamingException;
/**
* Look up an object from the naming store. An entry for this name must already exist.
*
* @param name The entry name
* @return The object from the store.
* @throws NamingException If any errors occur.
*/
Object lookup(Name name) throws NamingException;
/**
* Look up an object from the naming store. An entry for this name must already exist.
*
* @param name The entry name
* @param dereference if true indicates that managed references should retrieve the instance.
* @return The object from the store.
* @throws NamingException If any errors occur.
*/
Object lookup(Name name, boolean dereference) throws NamingException;
/**
* List the NameClassPair instances for the provided name. An entry for this name must already exist and be bound
* to a valid context.
*
* @param name The entry name
* @return The NameClassPair instances
* @throws NamingException If any errors occur
*/
List<NameClassPair> list(Name name) throws NamingException;
/**
* List the binding objects for a specified name. An entry for this name must already exist and be bound
* to a valid context.
*
* @param name The entry name
* @return The bindings
* @throws NamingException If any errors occur
*/
List<Binding> listBindings(Name name) throws NamingException;
/**
* Close the naming store and cleanup any resource used by the store.
*
* @throws NamingException If any errors occur
*/
void close() throws NamingException;
/**
* Add a {@code NamingListener} for a specific target and scope.
*
* @param target The target name to add the listener to
* @param scope The listener scope
* @param listener The listener
*/
void addNamingListener(Name target, int scope, NamingListener listener);
/**
* Remove a {@code NamingListener} from all targets and scopes
*
* @param listener The listener
*/
void removeNamingListener(NamingListener listener);
}
| 3,815 | 33.378378 | 122 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/service/DefaultNamespaceContextSelectorService.java
|
package org.jboss.as.naming.service;
import org.jboss.as.naming.NamingStore;
import org.jboss.as.naming.context.NamespaceContextSelector;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.NamingException;
/**
* @author Eduardo Martins
*/
public class DefaultNamespaceContextSelectorService implements Service<Void> {
public static final ServiceName SERVICE_NAME = ContextNames.NAMING.append("defaultNamespaceContextSelector");
private static final CompositeName EMPTY_NAME = new CompositeName();
private final InjectedValue<NamingStore> globalNamingStore;
private final InjectedValue<NamingStore> jbossNamingStore;
private final InjectedValue<NamingStore> remoteExposedNamingStore;
public DefaultNamespaceContextSelectorService() {
this.globalNamingStore = new InjectedValue<>();
this.jbossNamingStore = new InjectedValue<>();
this.remoteExposedNamingStore = new InjectedValue<>();
}
public InjectedValue<NamingStore> getGlobalNamingStore() {
return globalNamingStore;
}
public InjectedValue<NamingStore> getJbossNamingStore() {
return jbossNamingStore;
}
public InjectedValue<NamingStore> getRemoteExposedNamingStore() {
return remoteExposedNamingStore;
}
@Override
public void start(StartContext startContext) throws StartException {
NamespaceContextSelector.setDefault(new NamespaceContextSelector() {
public Context getContext(String identifier) {
final NamingStore namingStore;
if (identifier.equals("global")) {
namingStore = globalNamingStore.getValue();
} else if (identifier.equals("jboss")) {
namingStore = jbossNamingStore.getValue();
} else if (identifier.equals("jboss/exported")) {
namingStore = remoteExposedNamingStore.getValue();
} else {
namingStore = null;
}
if (namingStore != null) {
try {
return (Context) namingStore.lookup(EMPTY_NAME);
} catch (NamingException e) {
throw new IllegalStateException(e);
}
} else {
return null;
}
}
});
}
@Override
public void stop(StopContext stopContext) {
}
@Override
public Void getValue() throws IllegalStateException, IllegalArgumentException {
return null;
}
}
| 2,913 | 33.282353 | 113 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/service/ExternalContextBinderService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.service;
import org.jboss.as.naming.context.external.ExternalContexts;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
/**
* A binder service for external contexts.
* @author Eduardo Martins
*/
public class ExternalContextBinderService extends BinderService {
private final InjectedValue<ExternalContexts> externalContextsInjectedValue;
/**
*
* @param name
* @param source
*/
public ExternalContextBinderService(String name, Object source) {
super(name, source);
this.externalContextsInjectedValue = new InjectedValue<>();
}
public InjectedValue<ExternalContexts> getExternalContextsInjector() {
return externalContextsInjectedValue;
}
@Override
public synchronized void start(StartContext context) throws StartException {
super.start(context);
externalContextsInjectedValue.getValue().addExternalContext(context.getController().getName());
}
@Override
public synchronized void stop(StopContext context) {
super.stop(context);
externalContextsInjectedValue.getValue().removeExternalContext(context.getController().getName());
}
}
| 2,341 | 34.484848 | 106 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/service/NamingStoreService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.service;
import javax.naming.NamingException;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.WritableServiceBasedNamingStore;
import org.jboss.as.naming.logging.NamingLogger;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* Service responsible for managing the creation and life-cycle of a service based naming store.
*
* @author John E. Bailey
* @author Stuart Douglas
* @author Eduardo Martins
*/
public class NamingStoreService implements Service<ServiceBasedNamingStore> {
private final boolean readOnly;
private volatile ServiceBasedNamingStore store;
public NamingStoreService() {
this(false);
}
public NamingStoreService(boolean readOnly) {
this.readOnly = readOnly;
}
/**
* Creates the naming store if not provided by the constructor.
*
* @param context The start context
* @throws StartException If any problems occur creating the context
*/
public void start(final StartContext context) throws StartException {
if(store == null) {
final ServiceRegistry serviceRegistry = context.getController().getServiceContainer();
final ServiceName serviceNameBase = context.getController().getName();
final ServiceTarget serviceTarget = context.getChildTarget();
store = readOnly ? new ServiceBasedNamingStore(serviceRegistry, serviceNameBase) : new WritableServiceBasedNamingStore(serviceRegistry, serviceNameBase, serviceTarget);
}
}
/**
* Destroys the naming store.
*
* @param context The stop context
*/
public void stop(StopContext context) {
if(store != null) {
try {
store.close();
store = null;
} catch (NamingException e) {
throw NamingLogger.ROOT_LOGGER.failedToDestroyRootContext(e);
}
}
}
/**
* Get the context value.
*
* @return The naming store
* @throws IllegalStateException
*/
public ServiceBasedNamingStore getValue() throws IllegalStateException {
return store;
}
}
| 3,457 | 33.929293 | 180 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/service/BinderService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.service;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import java.util.concurrent.atomic.AtomicInteger;
import static org.jboss.as.naming.logging.NamingLogger.ROOT_LOGGER;
/**
* Service responsible for binding and unbinding an entry into a naming context. This service can be used as a dependency for
* any service that needs to retrieve this entry from the context.
*
* @author John E. Bailey
* @author Eduardo Martins
*/
public class BinderService implements Service<ManagedReferenceFactory> {
private final InjectedValue<ServiceBasedNamingStore> namingStoreValue = new InjectedValue<ServiceBasedNamingStore>();
private final String name;
private final InjectedValue<ManagedReferenceFactory> managedReferenceFactory = new InjectedValue<ManagedReferenceFactory>();
private volatile Object source;
private final AtomicInteger refcnt;
private volatile ServiceController<?> controller;
/**
* Construct new instance.
*
* @param name The JNDI name to use for binding. May be either an absolute or relative name
* @param source
* @param shared indicates if the bind may be shared among multiple deployments, if true the service tracks references indicated through acquire(), and automatically stops once all deployments unreference it through release()
*/
public BinderService(final String name, Object source, boolean shared) {
if (name.startsWith("java:")) {
//this is an absolute reference
this.name = name.substring(name.indexOf('/') + 1);
} else {
this.name = name;
}
this.source = source;
refcnt = shared ? new AtomicInteger(0) : null;
}
/**
* Construct new instance.
*
* @param name The JNDI name to use for binding. May be either an absolute or relative name
*/
public BinderService(final String name, Object source) {
this(name, source, false);
}
public BinderService(final String name) {
this(name, null, false);
}
public Object getSource() {
return source;
}
public void setSource(Object source) {
this.source = source;
}
public void acquire() {
if (refcnt != null) {
refcnt.incrementAndGet();
}
}
/**
* Releases the service, returns <code>true</code> if the service is removed as a result, or false otherwise
* @return
*/
public boolean release() {
if (refcnt != null && refcnt.decrementAndGet() <= 0 && controller != null) {
controller.setMode(ServiceController.Mode.REMOVE);
return true;
}
return false;
}
public ServiceName getServiceName() {
final ServiceController<?> serviceController = this.controller;
return serviceController != null ? serviceController.getName() : null;
}
/**
* Bind the entry into the injected context.
*
* @param context The start context
* @throws StartException If the entity can not be bound
*/
public void start(StartContext context) throws StartException {
final ServiceBasedNamingStore namingStore = namingStoreValue.getValue();
controller = context.getController();
namingStore.add(controller.getName());
ROOT_LOGGER.tracef("Bound resource %s into naming store %s (service name %s)", name, namingStore, controller.getName());
}
/**
* Unbind the entry from the injected context.
*
* @param context The stop context
*/
public void stop(StopContext context) {
final ServiceBasedNamingStore namingStore = namingStoreValue.getValue();
namingStore.remove(controller.getName());
ROOT_LOGGER.tracef("Unbound resource %s into naming store %s (service name %s)", name, namingStore, context.getController().getName());
}
/**
* Get the value from the injected context.
*
* @return The value of the named entry
* @throws IllegalStateException
*/
public ManagedReferenceFactory getValue() throws IllegalStateException {
return managedReferenceFactory.getValue();
}
/**
* Get the injector for the item to be bound.
*
* @return the injector
*/
public InjectedValue<ManagedReferenceFactory> getManagedObjectInjector() {
return managedReferenceFactory;
}
/**
* Get the naming store injector.
*
* @return the injector
*/
public InjectedValue<ServiceBasedNamingStore> getNamingStoreInjector() {
return namingStoreValue;
}
@Override
public String toString() {
return "BinderService[name=" + name + ", source=" + source + ", refcnt=" + (refcnt != null ? refcnt.get() : "n/a") +"]";
}
public String getName() {
return name;
}
}
| 6,237 | 34.044944 | 229 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/service/ExternalContextsService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.service;
import org.jboss.as.naming.logging.NamingLogger;
import org.jboss.as.naming.context.external.ExternalContexts;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* A service containing the subsystem's {@link ExternalContexts}.
* @author Eduardo Martins
*/
public class ExternalContextsService implements Service<ExternalContexts> {
public static final ServiceName SERVICE_NAME = ContextNames.NAMING.append("externalcontexts");
private final ExternalContexts externalContexts;
private volatile boolean started = false;
public ExternalContextsService(ExternalContexts externalContexts) {
this.externalContexts = externalContexts;
}
@Override
public void start(StartContext context) throws StartException {
started = true;
}
@Override
public void stop(StopContext context) {
started = false;
}
@Override
public ExternalContexts getValue() throws IllegalStateException, IllegalArgumentException {
if(!started) {
throw NamingLogger.ROOT_LOGGER.serviceNotStarted(SERVICE_NAME);
}
return externalContexts;
}
}
| 2,405 | 35.454545 | 98 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/service/NamingService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.service;
import org.jboss.as.naming.NamingContext;
import org.jboss.as.naming.NamingStore;
import org.jboss.as.naming.logging.NamingLogger;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import static org.jboss.as.naming.logging.NamingLogger.ROOT_LOGGER;
/**
* Service responsible for creating and managing the life-cycle of the Naming Server.
*
* @author John E. Bailey
* @author Eduardo Martins
*/
public class NamingService implements Service<NamingStore> {
public static final String CAPABILITY_NAME = "org.wildfly.naming";
/**
* @deprecated Dependent subsystem should instead register a requirement on the {@link #CAPABILITY_NAME} capability.
*/
@Deprecated
public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("naming");
private final InjectedValue<NamingStore> namingStore;
/**
* Construct a new instance.
*
*/
public NamingService() {
this.namingStore = new InjectedValue<>();
}
/**
* Retrieves the naming store's InjectedValue.
* @return
*/
public InjectedValue<NamingStore> getNamingStore() {
return namingStore;
}
/**
* Creates a new NamingServer and sets the naming context to use the naming server.
*
* @param context The start context
* @throws StartException If any errors occur setting up the naming server
*/
public void start(StartContext context) throws StartException {
ROOT_LOGGER.startingService();
try {
NamingContext.setActiveNamingStore(namingStore.getValue());
} catch (Throwable t) {
throw new StartException(NamingLogger.ROOT_LOGGER.failedToStart("naming service"), t);
}
}
/**
* Removes the naming server from the naming context.
*
* @param context The stop context.
*/
public void stop(StopContext context) {
NamingContext.setActiveNamingStore(null);
}
/**
* Get the naming store value.
*
* @return The naming store.
* @throws IllegalStateException
*/
public NamingStore getValue() throws IllegalStateException {
return namingStore.getValue();
}
}
| 3,445 | 32.784314 | 120 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/management/JndiViewOperation.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.management;
import javax.naming.Context;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.Reference;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.naming.JndiViewManagedReferenceFactory;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.NamingContext;
import org.jboss.as.naming.logging.NamingLogger;
import org.jboss.as.naming.NamingStore;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceRegistry;
/**
* @author John Bailey
*/
public class JndiViewOperation implements OperationStepHandler {
public static final JndiViewOperation INSTANCE = new JndiViewOperation();
public static final String OPERATION_NAME = "jndi-view";
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
final ModelNode resultNode = context.getResult();
if (context.isNormalServer()) {
context.addStep(new OperationStepHandler() {
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
final ServiceRegistry serviceRegistry = context.getServiceRegistry(false);
final ModelNode contextsNode = resultNode.get("java: contexts");
final ServiceController<?> javaContextService = serviceRegistry.getService(ContextNames.JAVA_CONTEXT_SERVICE_NAME);
final NamingStore javaContextNamingStore = NamingStore.class.cast(javaContextService.getValue());
try {
addEntries(contextsNode.get("java:"), new NamingContext(javaContextNamingStore, null));
} catch (NamingException e) {
throw new OperationFailedException(e, new ModelNode().set(NamingLogger.ROOT_LOGGER.failedToReadContextEntries("java:")));
}
final ServiceController<?> jbossContextService = serviceRegistry.getService(ContextNames.JBOSS_CONTEXT_SERVICE_NAME);
final NamingStore jbossContextNamingStore = NamingStore.class.cast(jbossContextService.getValue());
try {
addEntries(contextsNode.get("java:jboss"), new NamingContext(jbossContextNamingStore, null));
} catch (NamingException e) {
throw new OperationFailedException(e, new ModelNode().set(NamingLogger.ROOT_LOGGER.failedToReadContextEntries("java:jboss")));
}
final ServiceController<?> exportedContextService = serviceRegistry.getService(ContextNames.EXPORTED_CONTEXT_SERVICE_NAME);
final NamingStore exportedContextNamingStore = NamingStore.class.cast(exportedContextService.getValue());
try {
addEntries(contextsNode.get("java:jboss/exported"), new NamingContext(exportedContextNamingStore, null));
} catch (NamingException e) {
throw new OperationFailedException(e, new ModelNode().set(NamingLogger.ROOT_LOGGER.failedToReadContextEntries("java:jboss/exported")));
}
final ServiceController<?> globalContextService = serviceRegistry.getService(ContextNames.GLOBAL_CONTEXT_SERVICE_NAME);
final NamingStore globalContextNamingStore = NamingStore.class.cast(globalContextService.getValue());
try {
addEntries(contextsNode.get("java:global"), new NamingContext(globalContextNamingStore, null));
} catch (NamingException e) {
throw new OperationFailedException(e, new ModelNode().set(NamingLogger.ROOT_LOGGER.failedToReadContextEntries("java:global")));
}
final ServiceController<?> extensionRegistryController = serviceRegistry.getService(JndiViewExtensionRegistry.SERVICE_NAME);
if(extensionRegistryController != null) {
final JndiViewExtensionRegistry extensionRegistry = JndiViewExtensionRegistry.class.cast(extensionRegistryController.getValue());
for (JndiViewExtension extension : extensionRegistry.getExtensions()) {
extension.execute(new JndiViewExtensionContext() {
public OperationContext getOperationContext() {
return context;
}
public ModelNode getResult() {
return resultNode;
}
public void addEntries(ModelNode current, Context context) throws NamingException{
JndiViewOperation.this.addEntries(current, context);
}
});
}
}
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
}, OperationContext.Stage.RUNTIME);
} else {
throw new OperationFailedException(NamingLogger.ROOT_LOGGER.jndiViewNotAvailable());
}
}
private void addEntries(final ModelNode current, final Context context) throws NamingException {
final NamingEnumeration<NameClassPair> entries = context.list("");
while (entries.hasMore()) {
final NameClassPair pair = entries.next();
final ModelNode node = current.get(pair.getName());
node.get("class-name").set(pair.getClassName());
try {
final Object value;
if(context instanceof NamingContext) {
value = ((NamingContext)context).lookup(pair.getName(), false);
} else {
value = context.lookup(pair.getName());
}
if (value instanceof Context) {
addEntries(node.get("children"), Context.class.cast(value));
} else if (value instanceof Reference) {
//node.get("value").set(value.toString());
} else {
String jndiViewValue = JndiViewManagedReferenceFactory.DEFAULT_JNDI_VIEW_INSTANCE_VALUE;
if (value instanceof JndiViewManagedReferenceFactory) {
try {
jndiViewValue = JndiViewManagedReferenceFactory.class.cast(value)
.getJndiViewInstanceValue();
}
catch (Throwable e) {
// just log, don't stop the operation
NamingLogger.ROOT_LOGGER.failedToLookupJndiViewValue(pair.getName(),e);
}
} else if (!(value instanceof ManagedReferenceFactory)) {
jndiViewValue = String.valueOf(value);
}
node.get("value").set(jndiViewValue);
}
} catch (NamingException e) {
// just log, don't stop the operation
NamingLogger.ROOT_LOGGER.failedToLookupJndiViewValue(pair.getName(),e);
}
}
}
}
| 8,681 | 52.592593 | 159 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/management/JndiViewExtensionContext.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.management;
import javax.naming.Context;
import javax.naming.NamingException;
import org.jboss.as.controller.OperationContext;
import org.jboss.dmr.ModelNode;
/**
* Context providing required information for JndiView extensions.
*
* @author John Bailey
*/
public interface JndiViewExtensionContext {
/**
* Get the operation context.
*
* @return The operation context.
*/
OperationContext getOperationContext();
/**
* Get the operation result.
*
* @return The operation result.
*/
ModelNode getResult();
/**
* Add all the entries from the provided context into the provided model node.
*
* @param current The current result node.
* @param context The current naming context.
*/
void addEntries(final ModelNode current, final Context context) throws NamingException;
}
| 1,916 | 32.051724 | 91 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/management/JndiViewExtensionRegistry.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.management;
import java.util.ArrayList;
import java.util.List;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* Registry for Jndi view extensions.
*
* @author John Bailey
*/
public class JndiViewExtensionRegistry implements Service<JndiViewExtensionRegistry> {
public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("jndi-view", "extension", "registry");
private List<JndiViewExtension> extensions;
public synchronized void start(StartContext startContext) throws StartException {
this.extensions = new ArrayList<JndiViewExtension>();
}
public synchronized void stop(StopContext stopContext) {
this.extensions = null;
}
public JndiViewExtensionRegistry getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
List<JndiViewExtension> getExtensions() {
return this.extensions;
}
public void addExtension(final JndiViewExtension extension) {
this.extensions.add(extension);
}
public void removeExtension(final JndiViewExtension extension) {
this.extensions.remove(extension);
}
}
| 2,356 | 34.712121 | 114 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/management/JndiViewExtension.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.management;
import org.jboss.as.controller.OperationFailedException;
/**
* An extension to the JndiViewOperation. This will be executed along with the normal JndiViewOperation.
*
* @author John Bailey
*/
public interface JndiViewExtension {
/**
* Execute the extension and provide additional JNDI information in the result.
*
* @param context The extension context.
* @throws OperationFailedException
*/
void execute(final JndiViewExtensionContext context) throws OperationFailedException;
}
| 1,584 | 37.658537 | 105 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/logging/NamingLogger.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.logging;
import static org.jboss.logging.Logger.Level.ERROR;
import static org.jboss.logging.Logger.Level.INFO;
import static org.jboss.logging.Logger.Level.WARN;
import java.security.Permission;
import javax.naming.Context;
import javax.naming.InvalidNameException;
import javax.naming.Name;
import javax.naming.NameNotFoundException;
import javax.naming.NamingException;
import javax.naming.OperationNotSupportedException;
import javax.naming.spi.ObjectFactory;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.naming.deployment.JndiName;
import org.jboss.as.naming.subsystem.BindingType;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.msc.service.ServiceName;
/**
* Date: 17.06.2011
*
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
@SuppressWarnings("deprecation")
@MessageLogger(projectCode = "WFLYNAM", length = 4)
public interface NamingLogger extends BasicLogger {
/**
* The root logger with a category of the package name.
*/
NamingLogger ROOT_LOGGER = Logger.getMessageLogger(NamingLogger.class, "org.jboss.as.naming");
/**
* Logs an informational message indicating the naming subsystem is being activated.
*/
@LogMessage(level = INFO)
@Message(id = 1, value = "Activating Naming Subsystem")
void activatingSubsystem();
/**
* Logs a warning message indicating the {@code name} failed to get set.
*
* @param cause the cause of the error.
* @param name the name of the object that didn't get set.
*/
@LogMessage(level = WARN)
@Message(id = 2, value = "Failed to set %s")
void failedToSet(@Cause Throwable cause, String name);
/**
* Logs an informational message indicating the naming service is starting.
*/
@LogMessage(level = INFO)
@Message(id = 3, value = "Starting Naming Service")
void startingService();
// @LogMessage(level = ERROR)
// @Message(id = 4, value = "Unable to send header, closing channel")
// void failedToSendHeader(@Cause IOException exception);
//
// @LogMessage(level = ERROR)
// @Message(id = 5, value = "Error determining version selected by client.")
// void failedToDetermineClientVersion(@Cause IOException exception);
//
// @LogMessage(level = ERROR)
// @Message(id = 6, value = "Closing channel %s due to an error")
// void closingChannel(Channel channel, @Cause Throwable t);
//
// @LogMessage(level = DEBUG)
// @Message(id = 7, value = "Channel end notification received, closing channel %s")
// void closingChannelOnChannelEnd(Channel channel);
//
// @LogMessage(level = ERROR)
// @Message(id = 8, value = "Unexpected internal error")
// void unexpectedError(@Cause Throwable t);
//
// @LogMessage(level = ERROR)
// @Message(id = 9, value = "Null correlationId so error not sent to client")
// void nullCorrelationId(@Cause Throwable t);
//
// @LogMessage(level = ERROR)
// @Message(id = 10, value = "Failed to send exception response to client")
// void failedToSendExceptionResponse(@Cause IOException ioe);
//
//
// @LogMessage(level = ERROR)
// @Message(id = 11, value = "Unexpected parameter type - expected: %d received: %d")
// void unexpectedParameterType(byte expected, byte actual);
/**
* Creates an exception indicating that a class is not an {@link ObjectFactory} instance, from the specified module.
* @param cause the cause
*/
@LogMessage(level = ERROR)
@Message(id = 12, value = "Failed to release binder service, used for a runtime made JNDI binding")
void failedToReleaseBinderService(@Cause Throwable cause);
/**
* A message indicating that the lookup of an entry's JNDI view value failed.
*
* @param cause the cause of the error.
* @param entry the jndi name of the entry
*/
@LogMessage(level = ERROR)
@Message(id = 13, value = "Failed to obtain jndi view value for entry %s.")
void failedToLookupJndiViewValue(String entry, @Cause Throwable cause);
/**
* Creates an exception indicating you cannot add a {@link Permission} to a read-only
* {@link java.security.PermissionCollection}.
*
* @return A {@link SecurityException} for the error.
*/
@Message(id = 14, value = "Attempt to add a Permission to a readonly PermissionCollection")
SecurityException cannotAddToReadOnlyPermissionCollection();
/**
* A message indicating the {@code name} cannot be {@code null}.
*
* @param name the name.
*
* @return the message.
*/
@Message(id = 15, value = "%s cannot be null.")
String cannotBeNull(String name);
/**
* Creates an exception indicating the object dereference to the object failed.
*
* @param cause the cause of the error.
*
* @return a {@link NamingException} for the error.
*/
@Message(id = 16, value = "Could not dereference object")
NamingException cannotDeferenceObject(@Cause Throwable cause);
/**
* Creates an exception indicating the inability to list a non-context binding.
*
* @return a {@link NamingException} for the error.
*/
@Message(id = 17, value = "Unable to list a non Context binding.")
NamingException cannotListNonContextBinding();
/**
* A message indicating the link could not be looked up.
*
* @return the message.
*/
@Message(id = 18, value = "Could not lookup link")
String cannotLookupLink();
// /**
// * Creates an exception indicating the {@code name} could not be obtained.
// *
// * @param cause the cause of the error.
// * @param name the name of the object.
// *
// * @return an {@link IllegalStateException} for the error.
// */
// @Message(id = 19, value = "Cannot obtain %s")
// IllegalStateException cannotObtain(@Cause Throwable cause, String name);
/**
* Creates an exception indicating the service name could not be resolved.
*
* @param serviceName the service name.
*
* @return a {@link NamingException} for the error.
*/
@Message(id = 20, value = "Could not resolve service %s")
NamingException cannotResolveService(ServiceName serviceName);
/**
* Creates an exception indicating the service name could not be resolved.
*
* @param serviceName the service name.
* @param className the factory class name.
* @param state the state of the service.
*
* @return a {@link NamingException} for the error.
*/
@Message(id = 21, value = "Could not resolve service reference to %s in factory %s. Service was in state %s.")
NamingException cannotResolveService(ServiceName serviceName, String className, String state);
/**
* Creates an exception indicating the service name could not be resolved and here is a bug.
*
* @param serviceName the service name.
* @param className the factory class name.
* @param state the state of the service.
*
* @return a {@link NamingException} for the error.
*/
@Message(id = 22, value = "Could not resolve service reference to %s in factory %s. This is a bug in ServiceReferenceObjectFactory. State was %s.")
NamingException cannotResolveServiceBug(ServiceName serviceName, String className, String state);
/**
* A message indicating duplicate JNDI bindings were found.
*
* @param jndiName the JNDI name.
* @param existing the existing object.
* @param value the new object.
*
* @return the message.
*/
@Message(id = 23, value = "Duplicate JNDI bindings for '%s' are not compatible. [%s] != [%s]")
String duplicateBinding(JndiName jndiName, Object existing, Object value);
/**
* Creates an exception indicating an empty name is not allowed.
*
* @return an {@link InvalidNameException} for the error.
*/
@Message(id = 24, value = "An empty name is not allowed")
InvalidNameException emptyNameNotAllowed();
/**
* Creates an exception indicating the JNDI entry is not yet registered in the context.
*
* @param cause the cause of the error.
* @param contextName the context name.
* @param context the context.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 25, value = "Jndi entry '%s' is not yet registered in context '%s'")
IllegalStateException entryNotRegistered(@Cause Throwable cause, String contextName, Context context);
/**
* Creates an exception indicating a failure to destroy the root context.
*
* @param cause the cause of the failure.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 26, value = "Failed to destroy root context")
IllegalStateException failedToDestroyRootContext(@Cause Throwable cause);
/**
* Creates an exception indicating the {@code className} could not be instantiated from the {@code classLoader}.
*
* @param description a description.
* @param className the class name.
* @param classLoader the class loader
*
* @return a {@link NamingException} for the error.
*/
@Message(id = 27, value = "Failed instantiate %s %s from classloader %s")
NamingException failedToInstantiate(@Cause Throwable cause, String description, String className, ClassLoader classLoader);
/**
* A message indicating the context entries could not be read from the binding name represented by the
* {@code bindingName} parameter.
*
* @param bindingName the binding name parameter.
*
* @return the message.
*/
@Message(id = 28, value = "Failed to read %s context entries.")
String failedToReadContextEntries(String bindingName);
/**
* A message indicating a failure to start the {@code name} service.
*
* @param name the name of the service.
*
* @return the message.
*/
@Message(id = 29, value = "Failed to start %s")
String failedToStart(String name);
/**
* Creates an exception indicating there was an illegal context in the name.
*
* @param jndiName the JNDI name.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 30, value = "Illegal context in name: %s")
RuntimeException illegalContextInName(String jndiName);
// /**
// * Creates an exception indicating the actions mask is invalid.
// *
// * @return an {@link IllegalArgumentException} for the error.
// */
// @Message(id = 31, value = "invalid actions mask")
// IllegalArgumentException invalidActionMask();
/**
* Creates an exception indicating the context reference is invalid.
*
* @param referenceName the reference name.
*
* @return a {@link NamingException} for the error.
*/
@Message(id = 32, value = "Invalid context reference. Not a '%s' reference.")
NamingException invalidContextReference(String referenceName);
/**
* Creates an exception indicating the JNDI name is invalid.
*
* @param jndiName the invalid JNDI name.
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 33, value = "A valid JNDI name must be provided: %s")
IllegalArgumentException invalidJndiName(String jndiName);
/**
* Creates an exception indicating the load factor must be greater than 0 and less then or equal 1.
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 34, value = "Load factor must be greater than 0 and less than or equal to 1")
IllegalArgumentException invalidLoadFactor();
/**
* Creates an exception indicating the permission is invalid.
*
* @param permission the permission.
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 35, value = "invalid permission, unknown action: %s")
IllegalArgumentException invalidPermission(Permission permission);
/**
* Creates an exception indicating the permission actions is unknown.
*
* @param permissionAction the permission action.
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 36, value = "invalid permission, unknown action: %s")
IllegalArgumentException invalidPermissionAction(String permissionAction);
/**
* Creates an exception indicating the table size cannot be negative.
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 37, value = "Can not have a negative size table!")
IllegalArgumentException invalidTableSize();
/**
* A message indicating that JNDI view is only available in runtime mode.
*
* @return the message.
*/
@Message(id = 38, value = "Jndi view is only available in runtime mode.")
String jndiViewNotAvailable();
/**
* Creates an exception indicating the name could not be found in the context.
*
* @param name the name that could not be found.
* @param contextName the context name.
*
* @return a {@link NameNotFoundException} for the error.
*/
@Message(id = 39, value = "Name '%s' not found in context '%s'")
NameNotFoundException nameNotFoundInContext(String name, Name contextName);
// /**
// * Creates an exception indicating there is nothing available to bind to.
// *
// * @return an {@link IllegalStateException} for the error.
// */
// @Message(id = 40, value = "Nothing available to bind to.")
// IllegalStateException noBindingsAvailable();
/**
* Creates an exception indicating the variable is {@code null}.
*
* @param varName the variable name.
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 41, value = "%s is null")
IllegalArgumentException nullVar(String varName);
/**
* Creates an exception indicating the object factory failed to create from the classloader.
*
* @param cause the cause of the failure.
*
* @return a {@link NamingException} for the error.
*/
@Message(id = 42, value = "Failed to create object factory from classloader.")
NamingException objectFactoryCreationFailure(@Cause Throwable cause);
/**
* Creates an exception indicating the naming context is read-only.
*
* @return an {@link OperationNotSupportedException} for the error.
*/
@Message(id = 43, value = "Naming context is read-only")
OperationNotSupportedException readOnlyNamingContext();
/**
* Creates an exception indicating the service name has already been bound.
*
* @param serviceName the service name.
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 44, value = "Service with name [%s] already bound.")
IllegalArgumentException serviceAlreadyBound(ServiceName serviceName);
/**
* Creates an exception indicating the table is full.
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 45, value = "Table is full!")
IllegalStateException tableIsFull();
/**
* Creates an exception indicating the thread was interrupted while retrieving the service.
*
* @param serviceName the service name.
*
* @return a {@link NamingException} for the error.
*/
@Message(id = 46, value = "Thread interrupted while retrieving service reference for service %s")
NamingException threadInterrupt(ServiceName serviceName);
@Message(id = 47, value = "Invalid name for context binding %s")
DeploymentUnitProcessingException invalidNameForContextBinding(String name);
@Message(id = 48, value = "Invalid binding name %s, name must start with one of %s")
OperationFailedException invalidNamespaceForBinding(String name, String namespaces);
/**
* Creates an exception indicating that the type for the binding to add is not known.
* @param type the unknown type
* @return the exception
*/
@Message(id = 49, value = "Unknown binding type %s")
OperationFailedException unknownBindingType(String type);
/**
* Creates an exception indicating that the type for the simple binding to add is not supported.
* @param type the unsupported type
* @return the exception
*/
@Message(id = 50, value = "Unsupported simple binding type %s")
OperationFailedException unsupportedSimpleBindingType(String type);
/**
* Creates an exception indicating that the string value for the simple URL binding failed to transform.
* @param value the URL value as string
* @param cause the original cause of failure
* @return the exception
*/
@Message(id = 51, value = "Unable to transform URL binding value %s")
OperationFailedException unableToTransformURLBindingValue(String value, @Cause Throwable cause);
/**
* Creates an exception indicating that a module could not be loaded.
* @param moduleID the module not loaded
* @return the exception
*/
@Message(id = 52, value = "Could not load module %s")
OperationFailedException couldNotLoadModule(ModuleIdentifier moduleID);
/**
* Creates an exception indicating that a class could not be loaded from a module.
* @param className the name of the class not loaded
* @param moduleID the module
* @return the exception
*/
@Message(id = 53, value = "Could not load class %s from module %s")
OperationFailedException couldNotLoadClassFromModule(String className, ModuleIdentifier moduleID);
/**
* Creates an exception indicating that a class instance could not be instantiate, from the specified module.
* @param className the name of the class not loaded
* @param moduleID the module
* @return the exception
*/
@Message(id = 54, value = "Could not instantiate instance of class %s from module %s")
OperationFailedException couldNotInstantiateClassInstanceFromModule(String className, ModuleIdentifier moduleID);
/**
* Creates an exception indicating that a class is not an {@link javax.naming.spi.ObjectFactory} instance, from the specified module.
* @param className the name of the class
* @param moduleID the module id
* @return the exception
*/
@Message(id = 55, value = "Class %s from module %s is not an instance of ObjectFactory")
OperationFailedException notAnInstanceOfObjectFactory(String className, ModuleIdentifier moduleID);
// /**
// * A "simple URL" binding add operation was failed by the operation transformer.
// * @param modelVersion the model version related with the transformer.
// * @return
// */
// @Message(id = 56, value = "Binding add operation for Simple URL not supported in Naming Subsystem model version %s")
// String failedToTransformSimpleURLNameBindingAddOperation(String modelVersion);
//
// /**
// * A "Object Factory With Environment" binding add operation was failed by the operation transformer.
// * @param modelVersion the model version related with the transformer.
// * @return
// */
// @Message(id = 57, value = "Binding add operation for Object Factory With Environment not supported in Naming Subsystem model version %s")
// String failedToTransformObjectFactoryWithEnvironmentNameBindingAddOperation(String modelVersion);
//
// /**
// * An external context binding add operation was failed by the operation transformer.
// * @param modelVersion the model version related with the transformer.
// * @return
// */
// @Message(id = 58, value = "Binding add operation for external context not supported in Naming Subsystem model version %s")
// String failedToTransformExternalContext(String modelVersion);
/**
* Creates an exception indicating a lookup failed, wrt {@link javax.annotation.Resource} injection.
*
* @param jndiName the JNDI name.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 59, value = "Resource lookup for injection failed: %s")
RuntimeException resourceLookupForInjectionFailed(String jndiName, @Cause Throwable cause);
/**
* Creates an exception indicating that a required attribute is not defined.
* @param bindingType binding type
* @param attributeName missing attribute
* @return the exception
*/
@Message(id = 60, value = "Binding type %s requires attribute named %s defined")
OperationFailedException bindingTypeRequiresAttributeDefined(BindingType bindingType, String attributeName);
@Message(id = 61, value = "Binding type %s can not take a 'cache' attribute")
OperationFailedException cacheNotValidForBindingType(BindingType type);
/**
* Creates an exception indicating a lookup failure.
*
* @param cause the cause of the error
* @param name the bind name.
*
* @return a {@link NamingException} for the error.
*/
@Message(id = 62, value = "Failed to lookup %s")
NamingException lookupError(@Cause Throwable cause, String name);
/**
* Indicates that a service is not started as expected.
* @return the exception
*/
@Message(id = 63, value = "%s service not started")
IllegalStateException serviceNotStarted(ServiceName serviceName);
@Message(id = 64, value = "Cannot rebind external context lookup")
OperationFailedException cannotRebindExternalContext();
@Message(id = 65, value = "Could not load module %s - the module or one of its dependencies is missing [%s]")
OperationFailedException moduleNotFound(ModuleIdentifier moduleID, String missingModule);
}
| 23,267 | 37.844741 | 151 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/deployment/DuplicateBindingException.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.deployment;
/**
* Exception thrown if a deployment contains duplicate non-compatible JNDI bindings.
*
* @author John E. Bailey
*/
public class DuplicateBindingException extends Exception {
private static final long serialVersionUID = 131033218044790395L;
public DuplicateBindingException(final String message) {
super(message);
}
}
| 1,410 | 37.135135 | 84 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/deployment/JndiNamingDependencyProcessor.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.deployment;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.naming.service.NamingService;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
/**
* Adds a service that depends on all JNDI bindings from the deployment to be up.
* <p/>
* As binding services are not children of the root deployment unit service this service
* is necessary to ensure the deployment is not considered complete until add bindings are up
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class JndiNamingDependencyProcessor implements DeploymentUnitProcessor {
private static final ServiceName JNDI_DEPENDENCY_SERVICE = ServiceName.of("jndiDependencyService");
private static final String JNDI_AGGREGATION_SERVICE_SUFFIX = "componentJndiDependencies";
@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
ServiceName namingStoreServiceName = support.getCapabilityServiceName(NamingService.CAPABILITY_NAME);
//this will always be up but we need to make sure the naming service is
//not shut down before the deployment is undeployed when the container is shut down
phaseContext.addToAttachmentList(Attachments.NEXT_PHASE_DEPS, namingStoreServiceName);
final ServiceName serviceName = serviceName(deploymentUnit.getServiceName());
final ServiceBuilder<?> serviceBuilder = phaseContext.getServiceTarget().addService(serviceName, new RuntimeBindReleaseService());
addAllDependencies(serviceBuilder, deploymentUnit.getAttachmentList(Attachments.JNDI_DEPENDENCIES));
Map<ServiceName, Set<ServiceName>> compJndiDeps = deploymentUnit.getAttachment(Attachments.COMPONENT_JNDI_DEPENDENCIES);
Set<ServiceName> aggregatingServices = installComponentJndiAggregatingServices(phaseContext.getServiceTarget(), compJndiDeps);
addAllDependencies(serviceBuilder, aggregatingServices);
if (deploymentUnit.getParent() != null) {
addAllDependencies(serviceBuilder, deploymentUnit.getParent().getAttachment(Attachments.JNDI_DEPENDENCIES));
compJndiDeps = deploymentUnit.getParent().getAttachment(Attachments.COMPONENT_JNDI_DEPENDENCIES);
aggregatingServices = installComponentJndiAggregatingServices(phaseContext.getServiceTarget(), compJndiDeps);
addAllDependencies(serviceBuilder, aggregatingServices);
}
serviceBuilder.requires(namingStoreServiceName);
serviceBuilder.install();
}
private static Set<ServiceName> installComponentJndiAggregatingServices(final ServiceTarget target, final Map<ServiceName, Set<ServiceName>> mappings) {
if (mappings == null) return Collections.emptySet();
final Set<ServiceName> retVal = new HashSet<>();
ServiceBuilder sb;
ServiceName sn;
for (final Map.Entry<ServiceName, Set<ServiceName>> mapping : mappings.entrySet()) {
sn = mapping.getKey().append(JNDI_AGGREGATION_SERVICE_SUFFIX);
retVal.add(sn);
sb = target.addService(sn);
for (final ServiceName depName : mapping.getValue()) sb.requires(depName);
sb.install();
}
return retVal;
}
private static void addAllDependencies(final ServiceBuilder sb, final Collection<ServiceName> dependencies) {
for (final ServiceName dependency : dependencies) {
sb.requires(dependency);
}
}
public static ServiceName serviceName(final ServiceName deploymentUnitServiceName) {
return deploymentUnitServiceName.append(JNDI_DEPENDENCY_SERVICE);
}
public static ServiceName serviceName(final DeploymentUnit deploymentUnit) {
return serviceName(deploymentUnit.getServiceName());
}
@Override
public void undeploy(final DeploymentUnit deploymentUnit) {
deploymentUnit.removeAttachment(Attachments.JNDI_DEPENDENCIES);
}
}
| 5,749 | 49 | 156 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/deployment/NamingLookupValue.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.deployment;
import org.jboss.as.naming.logging.NamingLogger;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.value.InjectedValue;
import org.jboss.msc.value.Value;
import javax.naming.Context;
import javax.naming.NamingException;
/**
* Value that is looked up from a naming context.
*
* @author John E. Bailey
*/
public class NamingLookupValue<T> implements Value<T> {
private final InjectedValue<Context> contextValue = new InjectedValue<Context>();
private final String contextName;
/**
* Create a new instance.
*
* @param contextName The context name to lookup if the value is not injected
*/
public NamingLookupValue(final String contextName) {
this.contextName = contextName;
}
/**
* Lookup the value from the naming context.
*
* @return the injected value if present, the value retrieved from the context if not.
* @throws IllegalStateException The name is not found in the context when called
*/
public T getValue() throws IllegalStateException {
final Context context = contextValue.getValue();
try {
return (T)context.lookup(contextName);
} catch (NamingException e) {
throw NamingLogger.ROOT_LOGGER.entryNotRegistered(e, contextName, context);
}
}
/**
* Get the naming context injector.
*
* @return The context injector
*/
public Injector<Context> getContextInjector() {
return contextValue;
}
}
| 2,560 | 33.146667 | 90 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/deployment/Attachments.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.deployment;
import org.jboss.as.naming.context.external.ExternalContexts;
import org.jboss.as.server.deployment.AttachmentKey;
/**
* The Naming subsystem's DU attachment keys.
* @author Eduardo Martins
*/
public final class Attachments {
/**
* The DU key where the subsystem's {@link ExternalContexts} instance may be found by DUPs.
*/
public static final AttachmentKey<ExternalContexts> EXTERNAL_CONTEXTS = AttachmentKey.create(ExternalContexts.class);
}
| 1,531 | 39.315789 | 121 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/deployment/ExternalContextsProcessor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.deployment;
import org.jboss.as.naming.context.external.ExternalContexts;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
/**
* A processor which adds the subsystem external contexts to deployment units attachments.
* @author Eduardo Martins
*/
public class ExternalContextsProcessor implements DeploymentUnitProcessor {
/**
*
*/
private final ExternalContexts externalContexts;
/**
*
* @param externalContexts
*/
public ExternalContextsProcessor(ExternalContexts externalContexts) {
this.externalContexts = externalContexts;
}
/**
*
* @return
*/
public ExternalContexts getExternalContexts() {
return externalContexts;
}
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
// add the external contexts to every DU attachments
phaseContext.getDeploymentUnit().putAttachment(Attachments.EXTERNAL_CONTEXTS, externalContexts);
}
}
| 2,211 | 34.677419 | 104 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/deployment/ContextNames.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.deployment;
import org.jboss.as.naming.ImmediateManagedReference;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.NamingContext;
import org.jboss.as.naming.NamingStore;
import org.jboss.as.naming.context.external.ExternalContexts;
import org.jboss.as.server.CurrentServiceContainer;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.naming.logging.NamingLogger;
import org.jboss.msc.inject.InjectionException;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceName;
import javax.naming.NamingException;
/**
* @author John Bailey
* @author Eduardo Martins
*/
public class ContextNames {
/**
* Parent ServiceName for all naming services.
*/
public static final ServiceName NAMING = ServiceName.JBOSS.append("naming");
/**
* ServiceName for java: namespace
*/
public static final ServiceName JAVA_CONTEXT_SERVICE_NAME = NAMING.append("context", "java");
/**
* Parent ServiceName for java:comp namespace
*/
public static final ServiceName COMPONENT_CONTEXT_SERVICE_NAME = JAVA_CONTEXT_SERVICE_NAME.append("comp");
/**
* ServiceName for java:jboss namespace
*/
public static final ServiceName JBOSS_CONTEXT_SERVICE_NAME = JAVA_CONTEXT_SERVICE_NAME.append("jboss");
/**
* ServiceName for java:global namespace
*/
public static final ServiceName GLOBAL_CONTEXT_SERVICE_NAME = JAVA_CONTEXT_SERVICE_NAME.append("global");
/**
* Parent ServiceName for java:app namespace
*/
public static final ServiceName APPLICATION_CONTEXT_SERVICE_NAME = JAVA_CONTEXT_SERVICE_NAME.append("app");
/**
* Parent ServiceName for java:module namespace
*/
public static final ServiceName MODULE_CONTEXT_SERVICE_NAME = JAVA_CONTEXT_SERVICE_NAME.append("module");
/**
* ServiceName for java:jboss/exported namespace
*/
public static final ServiceName EXPORTED_CONTEXT_SERVICE_NAME = JBOSS_CONTEXT_SERVICE_NAME.append("exported");
/**
* Get the base service name of a component's JNDI namespace.
*
* @param app the application name (must not be {@code null})
* @param module the module name (must not be {@code null})
* @param comp the component name (must not be {@code null})
* @return the base service name
*/
public static ServiceName contextServiceNameOfComponent(String app, String module, String comp) {
return COMPONENT_CONTEXT_SERVICE_NAME.append(app, module, comp);
}
/**
* Get the base service name of a module's JNDI namespace.
*
* @param app the application name (must not be {@code null})
* @param module the module name (must not be {@code null})
* @return the base service name
*/
public static ServiceName contextServiceNameOfModule(String app, String module) {
return MODULE_CONTEXT_SERVICE_NAME.append(app, module);
}
/**
* Get the base service name of an application's JNDI namespace.
*
* @param app the application name (must not be {@code null})
* @return the base service name
*/
public static ServiceName contextServiceNameOfApplication(String app) {
return APPLICATION_CONTEXT_SERVICE_NAME.append(app);
}
/**
* Get the service name of a context, or {@code null} if there is no service mapping for the context name.
*
* @param app the application name
* @param module the module name
* @param comp the component name
* @param context the context to check
* @return the BindInfo
*/
public static BindInfo bindInfoFor(String app, String module, String comp, String context) {
if (context.startsWith("java:")) {
final String namespace;
final int i = context.indexOf('/');
if (i == -1) {
namespace = context.substring(5);
} else if (i == 5) {
// Absolute path
return new BindInfo(JAVA_CONTEXT_SERVICE_NAME, context.substring(6));
} else {
namespace = context.substring(5, i);
}
sanitazeNameSpace(namespace,context);
if (namespace.equals("global")) {
return new BindInfo(GLOBAL_CONTEXT_SERVICE_NAME, context.substring(12));
} else if (namespace.equals("jboss")) {
String rest = context.substring(i);
if(rest.startsWith("/exported/")) {
return new BindInfo(EXPORTED_CONTEXT_SERVICE_NAME, context.substring(20));
} else {
return new BindInfo(JBOSS_CONTEXT_SERVICE_NAME, context.substring(11));
}
} else if (namespace.equals("app")) {
return new BindInfo(contextServiceNameOfApplication(app), context.substring(9));
} else if (namespace.equals("module")) {
return new BindInfo(contextServiceNameOfModule(app, module), context.substring(12));
} else if (namespace.equals("comp")) {
return new BindInfo(contextServiceNameOfComponent(app, module, comp), context.substring(10));
} else {
return new BindInfo(JBOSS_CONTEXT_SERVICE_NAME, context);
}
} else {
return null;
}
}
private static void sanitazeNameSpace(final String namespace, final String inContext) {
//URL might be:
// java:context/restOfURL - where nameSpace is part between ':' and '/'
if(namespace.contains(":")){
throw NamingLogger.ROOT_LOGGER.invalidJndiName(inContext);
}
}
/**
* Get the service name of an environment entry
*
* @param app the application name
* @param module the module name
* @param comp the component name
* @param useCompNamespace If the component has its own comp namespace
* @param envEntryName The env entry name
* @return the service name or {@code null} if there is no service
*/
public static BindInfo bindInfoForEnvEntry(String app, String module, String comp, boolean useCompNamespace, final String envEntryName) {
if (envEntryName.startsWith("java:")) {
if (useCompNamespace) {
return bindInfoFor(app, module, comp, envEntryName);
} else {
if (envEntryName.startsWith("java:comp")) {
return bindInfoFor(app, module, module, "java:module" + envEntryName.substring("java:comp".length()));
} else {
return bindInfoFor(app, module, module, envEntryName);
}
}
} else {
if (useCompNamespace) {
return bindInfoFor(app, module, comp, "java:comp/env/" + envEntryName);
} else {
return bindInfoFor(app, module, module, "java:module/env/" + envEntryName);
}
}
}
public static ServiceName buildServiceName(final ServiceName parentName, final String relativeName) {
return parentName.append(relativeName.split("/"));
}
public static class BindInfo {
private final ServiceName parentContextServiceName;
private final ServiceName binderServiceName;
private final String bindName;
// absolute jndi name inclusive of the namespace
private final String absoluteJndiName;
private BindInfo(final ServiceName parentContextServiceName, final String bindName) {
this.parentContextServiceName = parentContextServiceName;
this.binderServiceName = buildServiceName(parentContextServiceName, bindName);
this.bindName = bindName;
this.absoluteJndiName = this.generateAbsoluteJndiName();
}
/**
* The service name for the target namespace the binding will occur.
*
* @return The target service name
*/
public ServiceName getParentContextServiceName() {
return parentContextServiceName;
}
/**
* The service name for binder
*
* @return the binder service name
*/
public ServiceName getBinderServiceName() {
return binderServiceName;
}
/**
* The name for the binding
*
* @return The binding name
*/
public String getBindName() {
return bindName;
}
/**
* Returns the absolute jndi name of this {@link BindInfo}. The absolute jndi name is inclusive of the jndi namespace
*
* @return
*/
public String getAbsoluteJndiName() {
return this.absoluteJndiName;
}
public String toString() {
return "BindInfo{" +
"parentContextServiceName=" + parentContextServiceName +
", binderServiceName=" + binderServiceName +
", bindName='" + bindName + '\'' +
'}';
}
private String generateAbsoluteJndiName() {
final StringBuffer sb = new StringBuffer();
if (this.parentContextServiceName.equals(ContextNames.EXPORTED_CONTEXT_SERVICE_NAME)) {
sb.append("java:jboss/exported/");
} else if (this.parentContextServiceName.equals(ContextNames.JBOSS_CONTEXT_SERVICE_NAME)) {
sb.append("java:jboss/");
} else if (this.parentContextServiceName.equals(ContextNames.APPLICATION_CONTEXT_SERVICE_NAME)) {
sb.append("java:app/");
} else if (this.parentContextServiceName.equals(ContextNames.MODULE_CONTEXT_SERVICE_NAME)) {
sb.append("java:module/");
} else if (this.parentContextServiceName.equals(ContextNames.COMPONENT_CONTEXT_SERVICE_NAME)) {
sb.append("java:comp/");
} else if (this.parentContextServiceName.equals(ContextNames.GLOBAL_CONTEXT_SERVICE_NAME)) {
sb.append("java:global/");
} else if (this.parentContextServiceName.equals(ContextNames.JAVA_CONTEXT_SERVICE_NAME)) {
sb.append("java:/");
}
sb.append(this.bindName);
return sb.toString();
}
/**
* Setup a lookup with respect to {@link javax.annotation.Resource} injection.
*
* @param serviceBuilder the builder that should depend on the lookup
* @param targetInjector the injector which will receive the lookup result once the builded service starts
*/
public void setupLookupInjection(final ServiceBuilder<?> serviceBuilder,
final Injector<ManagedReferenceFactory> targetInjector, final DeploymentUnit deploymentUnit, final boolean optional) {
// set dependency to the binder or its parent external context's service name
final ExternalContexts externalContexts = deploymentUnit.getAttachment(Attachments.EXTERNAL_CONTEXTS);
final ServiceName parentExternalContextServiceName = externalContexts != null ? externalContexts.getParentExternalContext(getBinderServiceName()) : null;
final ServiceName dependencyServiceName = parentExternalContextServiceName == null ? getBinderServiceName() : parentExternalContextServiceName;
final ServiceContainer container = CurrentServiceContainer.getServiceContainer();
if (optional) {
if (container.getService(dependencyServiceName) != null) serviceBuilder.requires(dependencyServiceName);
} else {
serviceBuilder.requires(dependencyServiceName);
}
// an injector which upon being injected with the naming store, injects a factory - which does the lookup - to the
// target injector
final Injector<NamingStore> lookupInjector = new Injector<NamingStore>() {
@Override
public void uninject() {
targetInjector.uninject();
}
@Override
public void inject(final NamingStore value) throws InjectionException {
final NamingContext storeBaseContext = new NamingContext(value, null);
final ManagedReferenceFactory factory = new ManagedReferenceFactory() {
@Override
public ManagedReference getReference() {
try {
return new ImmediateManagedReference(storeBaseContext.lookup(getBindName()));
} catch (NamingException e) {
if(!optional) {
throw NamingLogger.ROOT_LOGGER.resourceLookupForInjectionFailed(getAbsoluteJndiName(), e);
} else {
NamingLogger.ROOT_LOGGER.tracef(e,"failed to lookup %s", getAbsoluteJndiName());
}
}
return null;
}
};
targetInjector.inject(factory);
}
};
// sets dependency to the parent context service (holds the naming store), which will trigger the lookup injector
serviceBuilder.addDependency(getParentContextServiceName(), NamingStore.class, lookupInjector);
}
}
/**
* Get the service name of a NamingStore
*
* @param jndiName the jndi name
* @return the bind info for the jndi name
*/
public static BindInfo bindInfoFor(final String jndiName) {
// TODO: handle non java: schemes
String bindName;
if (jndiName.startsWith("java:")) {
bindName = jndiName.substring(5);
} else if (!jndiName.startsWith("jboss") && !jndiName.startsWith("global") && !jndiName.startsWith("/")) {
bindName = "/" + jndiName;
} else {
bindName = jndiName;
}
final ServiceName parentContextName;
if(bindName.startsWith("jboss/exported/")) {
parentContextName = EXPORTED_CONTEXT_SERVICE_NAME;
bindName = bindName.substring(15);
} else if (bindName.startsWith("jboss/")) {
parentContextName = JBOSS_CONTEXT_SERVICE_NAME;
bindName = bindName.substring(6);
} else if (bindName.startsWith("global/")) {
parentContextName = GLOBAL_CONTEXT_SERVICE_NAME;
bindName = bindName.substring(7);
} else if (bindName.startsWith("/")) {
parentContextName = JAVA_CONTEXT_SERVICE_NAME;
bindName = bindName.substring(1);
} else {
throw NamingLogger.ROOT_LOGGER.illegalContextInName(jndiName);
}
return new BindInfo(parentContextName, bindName);
}
}
| 16,173 | 41.901857 | 165 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/deployment/JndiName.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.deployment;
import java.io.Serializable;
import org.jboss.as.naming.logging.NamingLogger;
/**
* Utility object used to easily manged the construction and management of JNDI names.
*
* @author John E. Bailey
*/
public class JndiName implements Serializable, Comparable<JndiName> {
private static final long serialVersionUID = 3748117883355718029L;
private static final String ENTRY_SEPARATOR = "/";
private final JndiName parent;
private final String local;
private JndiName(final JndiName parent, final String local) {
this.parent = parent;
this.local = local;
}
/**
* Get the local JNDI entry name. Eg. java:comp/enc => enc
*
* @return The local JNDI entry name
*/
public String getLocalName() {
return local;
}
/**
* Get the parent JNDI name. Eg. java:comp/enc => java:comp
*
* @return The parent JNDI name
*/
public JndiName getParent() {
return parent;
}
/**
* Get the absolute JNDI name as a string.
*
* @return The absolute JNDI name as a string
*/
public String getAbsoluteName() {
final StringBuilder absolute = new StringBuilder();
if (parent != null) {
absolute.append(parent).append(ENTRY_SEPARATOR);
}
absolute.append(local);
return absolute.toString();
}
/**
* Create a new JNDI name by appending a new local entry name to this name.
*
* @param local The new local part to append
* @return A new JNDI name
*/
public JndiName append(final String local) {
return new JndiName(this, local);
}
/**
* Create a new instance of the JndiName by breaking the provided string format into a JndiName parts.
*
* @param name The string representation of a JNDI name.
* @return The JndiName representation
*/
public static JndiName of(final String name) {
if(name == null || name.isEmpty()) throw NamingLogger.ROOT_LOGGER.invalidJndiName(name);
final String[] parts = name.split(ENTRY_SEPARATOR);
JndiName current = null;
for(String part : parts) {
current = new JndiName(current, part);
}
return current;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final JndiName jndiName = (JndiName) o;
return !(local != null ? !local.equals(jndiName.local) : jndiName.local != null) && !(parent != null ? !parent.equals(jndiName.parent) : jndiName.parent != null);
}
@Override
public int hashCode() {
int result = parent != null ? parent.hashCode() : 0;
result = 31 * result + (local != null ? local.hashCode() : 0);
return result;
}
public String toString() {
return getAbsoluteName();
}
@Override
public int compareTo(final JndiName other) {
return getAbsoluteName().compareTo(other.getAbsoluteName());
}
}
| 4,122 | 30.96124 | 170 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/deployment/RuntimeBindReleaseService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.deployment;
import org.jboss.as.naming.logging.NamingLogger;
import org.jboss.as.naming.service.BinderService;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import java.util.ArrayList;
import java.util.List;
/**
* A {@link Service} which on stop releases runtime installed {@link org.jboss.as.naming.service.BinderService}s.
*
* @author Eduardo Martins
*
*/
public class RuntimeBindReleaseService implements Service<RuntimeBindReleaseService.References> {
private final References references = new References();
@Override
public References getValue() throws IllegalStateException, IllegalArgumentException {
return references;
}
@Override
public void start(StartContext context) throws StartException {
}
@Override
public void stop(StopContext context) {
references.releaseAll();
}
public static class References {
// List instead of Set because binder services use a counter to track its references, which means that for instance, N rebinds will increase the binder service ref counter N times, thus the related BinderServices should have N entries too
private volatile List<BinderService> services;
private References() {
}
public void add(BinderService service) {
synchronized (this) {
if (services == null) {
services = new ArrayList<BinderService>();
}
services.add(service);
}
}
public boolean contains(ServiceName serviceName) {
synchronized (this) {
if (services != null) {
for (BinderService service : services) {
if (serviceName.equals(service.getServiceName())) {
return true;
}
}
}
return false;
}
}
public void releaseAll() {
synchronized (this) {
if (services != null) {
for (BinderService service : services) {
try {
service.release();
} catch (Throwable e) {
NamingLogger.ROOT_LOGGER.failedToReleaseBinderService(e);
}
}
services = null;
}
}
}
}
}
| 3,669 | 32.669725 | 246 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/remote/RemoteNamingServerService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.remote;
import java.io.IOException;
import java.util.Hashtable;
import java.util.function.Function;
import javax.naming.Context;
import org.jboss.as.naming.NamingContext;
import org.jboss.as.naming.NamingStore;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.jboss.remoting3.Endpoint;
import org.wildfly.naming.client.remote.RemoteNamingService;
/**
* @author John Bailey
*/
public class RemoteNamingServerService implements Service<RemoteNamingService> {
public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("naming", "remote");
// The only classes that need to be unmarshalled are the Name impls in javax.naming. We don't allow remote bind/rebind
// so no need for arbitrary classes.
private static final Function<String, Boolean> NAME_ONLY_CLASS_RESOLUTION_FILTER = name -> name.startsWith("javax.naming.");
private final InjectedValue<Endpoint> endpoint = new InjectedValue<Endpoint>();
private final InjectedValue<NamingStore> namingStore = new InjectedValue<NamingStore>();
private RemoteNamingService remoteNamingService;
public synchronized void start(StartContext context) throws StartException {
try {
final Context namingContext = new NamingContext(namingStore.getValue(), new Hashtable<String, Object>());
remoteNamingService = new RemoteNamingService(namingContext, NAME_ONLY_CLASS_RESOLUTION_FILTER);
remoteNamingService.start(endpoint.getValue());
} catch (Exception e) {
throw new StartException("Failed to start remote naming service", e);
}
}
public synchronized void stop(StopContext context) {
try {
remoteNamingService.stop();
} catch (IOException e) {
throw new IllegalStateException("Failed to stop remote naming service", e);
}
}
public synchronized RemoteNamingService getValue() throws IllegalStateException, IllegalArgumentException {
return remoteNamingService;
}
public Injector<Endpoint> getEndpointInjector() {
return endpoint;
}
public Injector<NamingStore> getNamingStoreInjector() {
return namingStore;
}
}
| 3,486 | 41.012048 | 128 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/remote/HttpRemoteNamingServerService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 2110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.remote;
import org.jboss.as.naming.NamingContext;
import org.jboss.as.naming.NamingStore;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import io.undertow.server.handlers.PathHandler;
import org.wildfly.httpclient.naming.HttpRemoteNamingService;
import javax.naming.Context;
import java.util.Hashtable;
import java.util.function.Function;
/**
* @author Stuart Douglas
*/
public class HttpRemoteNamingServerService implements Service<HttpRemoteNamingServerService> {
public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("naming", "http-remote");
public static final String NAMING = "/naming";
private static final Function<String, Boolean> REJECT_CLASS_RESOLUTION_FILTER = name -> Boolean.FALSE;
private final InjectedValue<PathHandler> pathHandlerInjectedValue = new InjectedValue<>();
private final InjectedValue<NamingStore> namingStore = new InjectedValue<NamingStore>();
@Override
public void start(StartContext startContext) throws StartException {
final Context namingContext = new NamingContext(namingStore.getValue(), new Hashtable<String, Object>());
HttpRemoteNamingService service = new HttpRemoteNamingService(namingContext, REJECT_CLASS_RESOLUTION_FILTER);
pathHandlerInjectedValue.getValue().addPrefixPath(NAMING, service.createHandler());
}
@Override
public void stop(StopContext stopContext) {
pathHandlerInjectedValue.getValue().removePrefixPath(NAMING);
}
@Override
public HttpRemoteNamingServerService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
public InjectedValue<PathHandler> getPathHandlerInjectedValue() {
return pathHandlerInjectedValue;
}
public InjectedValue<NamingStore> getNamingStore() {
return namingStore;
}
}
| 3,098 | 39.246753 | 117 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingSubsystem12Parser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.BINDING;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.BINDING_TYPE;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.CLASS;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.LOOKUP;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.MODULE;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.OBJECT_FACTORY;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.SIMPLE;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.TYPE;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.VALUE;
import java.util.EnumSet;
import java.util.List;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* @author Stuart Douglas
*/
public class NamingSubsystem12Parser implements XMLElementReader<List<ModelNode>> {
NamingSubsystem12Parser() {
}
/**
* {@inheritDoc}
*/
@Override
public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> operations) throws XMLStreamException {
operations.add(Util.createAddOperation(PathAddress.pathAddress(NamingExtension.SUBSYSTEM_PATH)));
// elements
final EnumSet<NamingSubsystemXMLElement> encountered = EnumSet.noneOf(NamingSubsystemXMLElement.class);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (NamingSubsystemNamespace.forUri(reader.getNamespaceURI())) {
case NAMING_1_2: {
final NamingSubsystemXMLElement element = NamingSubsystemXMLElement.forName(reader.getLocalName());
if (!encountered.add(element)) {
throw unexpectedElement(reader);
}
switch (element) {
case BINDINGS: {
parseBindings(reader, operations);
break;
}
case REMOTE_NAMING: {
parseRemoteNaming(reader, operations);
break;
}
default: {
throw unexpectedElement(reader);
}
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseRemoteNaming(final XMLExtendedStreamReader reader, final List<ModelNode> operations) throws XMLStreamException {
requireNoAttributes(reader);
requireNoContent(reader);
final ModelNode remoteNamingAdd = new ModelNode();
remoteNamingAdd.get(OP).set(ADD);
remoteNamingAdd.get(OP_ADDR).add(SUBSYSTEM, NamingExtension.SUBSYSTEM_NAME);
remoteNamingAdd.get(OP_ADDR).add(NamingSubsystemModel.SERVICE, NamingSubsystemModel.REMOTE_NAMING);
operations.add(remoteNamingAdd);
}
private void parseBindings(final XMLExtendedStreamReader reader, final List<ModelNode> operations) throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (NamingSubsystemXMLElement.forName(reader.getLocalName())) {
case SIMPLE: {
this.parseSimpleBinding(reader, operations);
break;
}
case OBJECT_FACTORY: {
this.parseObjectFactoryBinding(reader, operations);
break;
}
case LOOKUP: {
this.parseLookupBinding(reader, operations);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseSimpleBinding(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
final int attCount = reader.getAttributeCount();
String name = null;
String bindingValue = null;
String type = null;
final EnumSet<NamingSubsystemXMLAttribute> required = EnumSet.of(NamingSubsystemXMLAttribute.NAME, NamingSubsystemXMLAttribute.VALUE);
for (int i = 0; i < attCount; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final NamingSubsystemXMLAttribute attribute = NamingSubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
name = value.trim();
break;
case VALUE:
bindingValue = parse(NamingBindingResourceDefinition.VALUE, value, reader).asString();
break;
case TYPE:
type = parse(NamingBindingResourceDefinition.TYPE, value, reader).asString();
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
final ModelNode address = new ModelNode();
address.add(SUBSYSTEM, NamingExtension.SUBSYSTEM_NAME);
address.add(BINDING, name);
final ModelNode bindingAdd = new ModelNode();
bindingAdd.get(OP).set(ADD);
bindingAdd.get(OP_ADDR).set(address);
bindingAdd.get(BINDING_TYPE).set(SIMPLE);
bindingAdd.get(VALUE).set(bindingValue);
if (type != null) {
bindingAdd.get(TYPE).set(type);
}
operations.add(bindingAdd);
}
private void parseObjectFactoryBinding(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
final int attCount = reader.getAttributeCount();
String name = null;
String module = null;
String factory = null;
final EnumSet<NamingSubsystemXMLAttribute> required = EnumSet.of(NamingSubsystemXMLAttribute.NAME, NamingSubsystemXMLAttribute.MODULE, NamingSubsystemXMLAttribute.CLASS);
for (int i = 0; i < attCount; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final NamingSubsystemXMLAttribute attribute = NamingSubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
name = value.trim();
break;
case MODULE:
module = parse(NamingBindingResourceDefinition.MODULE, value, reader).asString();
break;
case CLASS:
factory = parse(NamingBindingResourceDefinition.CLASS, value, reader).asString();
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
final ModelNode address = new ModelNode();
address.add(SUBSYSTEM, NamingExtension.SUBSYSTEM_NAME);
address.add(BINDING, name);
final ModelNode bindingAdd = new ModelNode();
bindingAdd.get(OP).set(ADD);
bindingAdd.get(OP_ADDR).set(address);
bindingAdd.get(BINDING_TYPE).set(OBJECT_FACTORY);
bindingAdd.get(MODULE).set(module);
bindingAdd.get(CLASS).set(factory);
operations.add(bindingAdd);
}
private void parseLookupBinding(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
final int attCount = reader.getAttributeCount();
String name = null;
String lookup = null;
final EnumSet<NamingSubsystemXMLAttribute> required = EnumSet.of(NamingSubsystemXMLAttribute.NAME, NamingSubsystemXMLAttribute.LOOKUP);
for (int i = 0; i < attCount; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final NamingSubsystemXMLAttribute attribute = NamingSubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
name = value.trim();
break;
case LOOKUP:
lookup = parse(NamingBindingResourceDefinition.LOOKUP, value, reader).asString();
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
final ModelNode address = new ModelNode();
address.add(SUBSYSTEM, NamingExtension.SUBSYSTEM_NAME);
address.add(BINDING, name);
final ModelNode bindingAdd = new ModelNode();
bindingAdd.get(OP).set(ADD);
bindingAdd.get(OP_ADDR).set(address);
bindingAdd.get(BINDING_TYPE).set(LOOKUP);
bindingAdd.get(LOOKUP).set(lookup);
operations.add(bindingAdd);
}
protected static ModelNode parse(AttributeDefinition ad, String value, XMLStreamReader reader) throws XMLStreamException {
return ad.getParser().parse(ad, value, reader);
}
}
| 11,978 | 41.935484 | 178 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingSubsystemNamespace.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import java.util.HashMap;
import java.util.Map;
/**
* An enumeration of the supported Naming subsystem namespaces
*
* @author Jaikiran Pai
*/
public enum NamingSubsystemNamespace {
// must be first
UNKNOWN(null),
NAMING_1_0("urn:jboss:domain:naming:1.0"),
NAMING_1_1("urn:jboss:domain:naming:1.1"),
NAMING_1_2("urn:jboss:domain:naming:1.2"),
NAMING_1_3("urn:jboss:domain:naming:1.3"),
NAMING_1_4("urn:jboss:domain:naming:1.4"),
NAMING_2_0("urn:jboss:domain:naming:2.0"),
;
private final String name;
NamingSubsystemNamespace(final String name) {
this.name = name;
}
/**
* Get the URI of this namespace.
*
* @return the URI
*/
public String getUriString() {
return name;
}
private static final Map<String, NamingSubsystemNamespace> MAP;
static {
final Map<String, NamingSubsystemNamespace> map = new HashMap<String, NamingSubsystemNamespace>();
for (NamingSubsystemNamespace namespace : values()) {
final String name = namespace.getUriString();
if (name != null) map.put(name, namespace);
}
MAP = map;
}
public static NamingSubsystemNamespace forUri(String uri) {
final NamingSubsystemNamespace element = MAP.get(uri);
return element == null ? UNKNOWN : element;
}
}
| 2,432 | 30.192308 | 106 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingSubsystemXMLPersister.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.persistence.SubsystemMarshallingContext;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.staxmapper.XMLElementWriter;
import org.jboss.staxmapper.XMLExtendedStreamWriter;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.BINDING;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.BINDING_TYPE;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.EXTERNAL_CONTEXT;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.LOOKUP;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.OBJECT_FACTORY;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.REMOTE_NAMING;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.SERVICE;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.SIMPLE;
/**
* @author Eduardo Martins
*/
public class NamingSubsystemXMLPersister implements XMLElementWriter<SubsystemMarshallingContext> {
public static final NamingSubsystemXMLPersister INSTANCE = new NamingSubsystemXMLPersister();
private NamingSubsystemXMLPersister() {
}
/**
* {@inheritDoc}
*/
@Override
public void writeContent(final XMLExtendedStreamWriter writer, final SubsystemMarshallingContext context) throws XMLStreamException {
context.startSubsystemElement(NamingExtension.NAMESPACE_2_0, false);
ModelNode model = context.getModelNode();
// bindings
if (model.hasDefined(BINDING)) {
writer.writeStartElement(NamingSubsystemXMLElement.BINDINGS.getLocalName());
final ModelNode bindingModel = model.get(BINDING);
this.writeBindings(writer, bindingModel);
// </timer-service>
writer.writeEndElement();
}
if (model.hasDefined(SERVICE)) {
final ModelNode service = model.get(SERVICE);
if (service.has(REMOTE_NAMING)) {
writer.writeEmptyElement(REMOTE_NAMING);
}
}
// write the subsystem end element
writer.writeEndElement();
}
private void writeBindings(final XMLExtendedStreamWriter writer, final ModelNode bindingModel) throws XMLStreamException {
for (Property binding : bindingModel.asPropertyList()) {
final String type = binding.getValue().get(BINDING_TYPE).asString();
if (type.equals(SIMPLE)) {
writeSimpleBinding(binding, writer);
} else if (type.equals(OBJECT_FACTORY)) {
writeObjectFactoryBinding(binding, writer);
} else if (type.equals(LOOKUP)) {
writeLookupBinding(binding, writer);
} else if (type.equals(EXTERNAL_CONTEXT)) {
writeExternalContext(binding, writer);
} else {
throw new XMLStreamException("Unknown binding type " + type);
}
}
}
private void writeSimpleBinding(final Property binding, final XMLExtendedStreamWriter writer) throws XMLStreamException {
writer.writeStartElement(NamingSubsystemXMLElement.SIMPLE.getLocalName());
writer.writeAttribute(NamingSubsystemXMLAttribute.NAME.getLocalName(), binding.getName());
NamingBindingResourceDefinition.VALUE.marshallAsAttribute(binding.getValue(), writer);
NamingBindingResourceDefinition.TYPE.marshallAsAttribute(binding.getValue(), writer);
writer.writeEndElement();
}
private void writeObjectFactoryBinding(final Property binding, final XMLExtendedStreamWriter writer)
throws XMLStreamException {
writer.writeStartElement(NamingSubsystemXMLElement.OBJECT_FACTORY.getLocalName());
writer.writeAttribute(NamingSubsystemXMLAttribute.NAME.getLocalName(), binding.getName());
NamingBindingResourceDefinition.MODULE.marshallAsAttribute(binding.getValue(), writer);
NamingBindingResourceDefinition.CLASS.marshallAsAttribute(binding.getValue(), writer);
NamingBindingResourceDefinition.ENVIRONMENT.marshallAsElement(binding.getValue(), writer);
writer.writeEndElement();
}
private void writeExternalContext(final Property binding, final XMLExtendedStreamWriter writer)
throws XMLStreamException {
writer.writeStartElement(NamingSubsystemXMLElement.EXTERNAL_CONTEXT.getLocalName());
writer.writeAttribute(NamingSubsystemXMLAttribute.NAME.getLocalName(), binding.getName());
NamingBindingResourceDefinition.MODULE.marshallAsAttribute(binding.getValue(), writer);
NamingBindingResourceDefinition.CLASS.marshallAsAttribute(binding.getValue(), writer);
NamingBindingResourceDefinition.CACHE.marshallAsAttribute(binding.getValue(), writer);
NamingBindingResourceDefinition.ENVIRONMENT.marshallAsElement(binding.getValue(), writer);
writer.writeEndElement();
}
private void writeLookupBinding(final Property binding, final XMLExtendedStreamWriter writer) throws XMLStreamException {
writer.writeStartElement(NamingSubsystemXMLElement.LOOKUP.getLocalName());
writer.writeAttribute(NamingSubsystemXMLAttribute.NAME.getLocalName(), binding.getName());
NamingBindingResourceDefinition.LOOKUP.marshallAsAttribute(binding.getValue(), writer);
writer.writeEndElement();
}
}
| 6,457 | 45.460432 | 137 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/RemoteNamingResourceDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.RuntimePackageDependency;
/**
* A {@link org.jboss.as.controller.ResourceDefinition} for JNDI bindings
*/
public class RemoteNamingResourceDefinition extends SimpleResourceDefinition {
private static final String JBOSS_REMOTING = "org.jboss.remoting";
static final String REMOTING_ENDPOINT_CAPABILITY_NAME = "org.wildfly.remoting.endpoint";
public static final RuntimeCapability<Void> REMOTE_NAMING_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.naming.remote")
.addRequirements(REMOTING_ENDPOINT_CAPABILITY_NAME)
.build();
RemoteNamingResourceDefinition() {
super(new Parameters(NamingSubsystemModel.REMOTE_NAMING_PATH, NamingExtension.getResourceDescriptionResolver(NamingSubsystemModel.REMOTE_NAMING))
.setAddHandler(RemoteNamingAdd.INSTANCE)
.setRemoveHandler(RemoteNamingRemove.INSTANCE)
.addCapabilities(REMOTE_NAMING_CAPABILITY));
}
@Override
public void registerAdditionalRuntimePackages(ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerAdditionalRuntimePackages(RuntimePackageDependency.required(JBOSS_REMOTING));
}
}
| 2,491 | 45.148148 | 153 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/RemoteNamingRemove.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import org.jboss.as.controller.ServiceRemoveStepHandler;
import org.jboss.as.naming.remote.RemoteNamingServerService;
import org.jboss.msc.service.ServiceName;
/**
* Handles removing a JNDI binding
*/
public class RemoteNamingRemove extends ServiceRemoveStepHandler {
public static final RemoteNamingRemove INSTANCE = new RemoteNamingRemove();
private RemoteNamingRemove() {
super(RemoteNamingAdd.INSTANCE);
}
@Override
protected ServiceName serviceName(final String name) {
return RemoteNamingServerService.SERVICE_NAME;
}
}
| 1,636 | 35.377778 | 79 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingSubsystem14Parser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.requireAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import static org.jboss.as.naming.subsystem.NamingExtension.SUBSYSTEM_PATH;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.BINDING;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.BINDING_TYPE;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.EXTERNAL_CONTEXT;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.LOOKUP;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.OBJECT_FACTORY;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.SIMPLE;
import java.util.EnumSet;
import java.util.List;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* @author Eduardo Martins
*/
public class NamingSubsystem14Parser implements XMLElementReader<List<ModelNode>> {
private final NamingSubsystemNamespace validNamespace;
NamingSubsystem14Parser() {
this.validNamespace = NamingSubsystemNamespace.NAMING_1_4;
}
NamingSubsystem14Parser(NamingSubsystemNamespace validNamespace) {
this.validNamespace = validNamespace;
}
/**
* {@inheritDoc}
*/
@Override
public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> operations) throws XMLStreamException {
PathAddress address = PathAddress.pathAddress(SUBSYSTEM_PATH);
final ModelNode ejb3SubsystemAddOperation = Util.createAddOperation(address);
operations.add(ejb3SubsystemAddOperation);
// elements
final EnumSet<NamingSubsystemXMLElement> encountered = EnumSet.noneOf(NamingSubsystemXMLElement.class);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (validNamespace == NamingSubsystemNamespace.forUri(reader.getNamespaceURI())) {
final NamingSubsystemXMLElement element = NamingSubsystemXMLElement.forName(reader.getLocalName());
if (!encountered.add(element)) {
throw unexpectedElement(reader);
}
switch (element) {
case BINDINGS: {
parseBindings(reader, operations, address);
break;
}
case REMOTE_NAMING: {
parseRemoteNaming(reader, operations, address);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
else {
throw unexpectedElement(reader);
}
}
}
private void parseRemoteNaming(final XMLExtendedStreamReader reader, final List<ModelNode> operations, PathAddress parent) throws XMLStreamException {
requireNoAttributes(reader);
requireNoContent(reader);
operations.add(Util.createAddOperation(parent.append(NamingSubsystemModel.SERVICE, NamingSubsystemModel.REMOTE_NAMING)));
}
private void parseBindings(final XMLExtendedStreamReader reader, final List<ModelNode> operations, PathAddress address) throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (NamingSubsystemXMLElement.forName(reader.getLocalName())) {
case SIMPLE: {
this.parseSimpleBinding(reader, operations, address);
break;
}
case OBJECT_FACTORY: {
this.parseObjectFactoryBinding(reader, operations, address);
break;
}
case LOOKUP: {
this.parseLookupBinding(reader, operations, address);
break;
}
case EXTERNAL_CONTEXT: {
this.parseExternalContext(reader, operations, address);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseSimpleBinding(final XMLExtendedStreamReader reader, List<ModelNode> operations, PathAddress parentAddress) throws XMLStreamException {
String name = null;
final ModelNode bindingAdd = Util.createAddOperation();
bindingAdd.get(BINDING_TYPE).set(SIMPLE);
final EnumSet<NamingSubsystemXMLAttribute> required = EnumSet.of(NamingSubsystemXMLAttribute.NAME, NamingSubsystemXMLAttribute.VALUE);
for (int i = 0; i < reader.getAttributeCount(); i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final NamingSubsystemXMLAttribute attribute = NamingSubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
name = value.trim();
break;
case VALUE:
NamingBindingResourceDefinition.VALUE.parseAndSetParameter(value, bindingAdd, reader);
break;
case TYPE:
NamingBindingResourceDefinition.TYPE.parseAndSetParameter(value, bindingAdd, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
final PathAddress address = parentAddress.append(BINDING, name);
bindingAdd.get(OP_ADDR).set(address.toModelNode());
operations.add(bindingAdd);
}
private void parseObjectFactoryBinding(final XMLExtendedStreamReader reader, List<ModelNode> operations, PathAddress parentAddress) throws XMLStreamException {
final int attCount = reader.getAttributeCount();
String name = null;
final ModelNode bindingAdd = Util.createAddOperation();
bindingAdd.get(BINDING_TYPE).set(OBJECT_FACTORY);
final EnumSet<NamingSubsystemXMLAttribute> required = EnumSet.of(NamingSubsystemXMLAttribute.NAME, NamingSubsystemXMLAttribute.MODULE, NamingSubsystemXMLAttribute.CLASS);
for (int i = 0; i < attCount; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final NamingSubsystemXMLAttribute attribute = NamingSubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
name = value.trim();
break;
case MODULE:
NamingBindingResourceDefinition.MODULE.parseAndSetParameter(value, bindingAdd, reader);
break;
case CLASS:
NamingBindingResourceDefinition.CLASS.parseAndSetParameter(value, bindingAdd, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
bindingAdd.get(OP_ADDR).set(parentAddress.append(BINDING, name).toModelNode());
// if present, parse the optional environment
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (NamingSubsystemXMLElement.forName(reader.getLocalName())) {
case ENVIRONMENT: {
parseObjectFactoryBindingEnvironment(reader, bindingAdd);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
operations.add(bindingAdd);
}
private void parseExternalContext(final XMLExtendedStreamReader reader, List<ModelNode> operations, PathAddress parentAddress) throws XMLStreamException {
final int attCount = reader.getAttributeCount();
String name = null;
final ModelNode bindingAdd = Util.createAddOperation();
bindingAdd.get(BINDING_TYPE).set(EXTERNAL_CONTEXT);
final EnumSet<NamingSubsystemXMLAttribute> required = EnumSet.of(NamingSubsystemXMLAttribute.NAME, NamingSubsystemXMLAttribute.CLASS, NamingSubsystemXMLAttribute.MODULE);
for (int i = 0; i < attCount; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final NamingSubsystemXMLAttribute attribute = NamingSubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
name = value.trim();
break;
case MODULE:
NamingBindingResourceDefinition.MODULE.parseAndSetParameter(value, bindingAdd, reader);
break;
case CLASS:
NamingBindingResourceDefinition.CLASS.parseAndSetParameter(value, bindingAdd, reader);
break;
case CACHE:
NamingBindingResourceDefinition.CACHE.parseAndSetParameter(value, bindingAdd, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
bindingAdd.get(OP_ADDR).set(parentAddress.append(BINDING, name).toModelNode());
// if present, parse the optional environment
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (NamingSubsystemXMLElement.forName(reader.getLocalName())) {
case ENVIRONMENT: {
parseObjectFactoryBindingEnvironment(reader, bindingAdd);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
operations.add(bindingAdd);
}
/**
* <p>
* Parses the optional {@code ObjectFactory environment}.
* </p>
*
* @param reader the {@code XMLExtendedStreamReader} used to read the configuration XML.
* @param bindingAdd where to add
* @throws javax.xml.stream.XMLStreamException
* if an error occurs while parsing the XML.
*/
private void parseObjectFactoryBindingEnvironment(XMLExtendedStreamReader reader, ModelNode bindingAdd) throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (NamingSubsystemXMLElement.forName(reader.getLocalName())) {
case ENVIRONMENT_PROPERTY: {
final String[] array = requireAttributes(reader, org.jboss.as.controller.parsing.Attribute.NAME.getLocalName(), org.jboss.as.controller.parsing.Attribute.VALUE.getLocalName());
NamingBindingResourceDefinition.ENVIRONMENT.parseAndAddParameterElement(array[0], array[1], bindingAdd, reader);
requireNoContent(reader);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseLookupBinding(final XMLExtendedStreamReader reader, List<ModelNode> operations, PathAddress parentAddress) throws XMLStreamException {
final int attCount = reader.getAttributeCount();
String name = null;
final ModelNode bindingAdd = Util.createAddOperation();
bindingAdd.get(BINDING_TYPE).set(LOOKUP);
final EnumSet<NamingSubsystemXMLAttribute> required = EnumSet.of(NamingSubsystemXMLAttribute.NAME, NamingSubsystemXMLAttribute.LOOKUP);
for (int i = 0; i < attCount; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final NamingSubsystemXMLAttribute attribute = NamingSubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
name = value.trim();
break;
case LOOKUP:
NamingBindingResourceDefinition.LOOKUP.parseAndSetParameter(value, bindingAdd, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
bindingAdd.get(OP_ADDR).set(parentAddress.append(BINDING, name).toModelNode());
operations.add(bindingAdd);
}
}
| 15,039 | 44.714286 | 196 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/BindingType.java
|
/*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
* /
*/
package org.jboss.as.naming.subsystem;
import java.util.HashMap;
import java.util.Map;
import org.jboss.dmr.ModelNode;
/**
* @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc.
*/
public enum BindingType {
SIMPLE(NamingSubsystemModel.SIMPLE),
OBJECT_FACTORY(NamingSubsystemModel.OBJECT_FACTORY),
LOOKUP(NamingSubsystemModel.LOOKUP),
EXTERNAL_CONTEXT(NamingSubsystemModel.EXTERNAL_CONTEXT),
;
private static final Map<String, BindingType> MAP;
static {
final Map<String, BindingType> map = new HashMap<String, BindingType>();
for (BindingType directoryGrouping : values()) {
map.put(directoryGrouping.localName, directoryGrouping);
}
MAP = map;
}
public static BindingType forName(String localName) {
if (localName == null) return null;
final BindingType directoryGrouping = MAP.get(localName.toLowerCase());
return directoryGrouping == null ? BindingType.valueOf(localName.toUpperCase()) : directoryGrouping;
}
private final String localName;
BindingType(final String localName) {
this.localName = localName;
}
@Override
public String toString() {
return localName;
}
/**
* Converts the value of the directory grouping to a model node.
*
* @return a new model node for the value.
*/
public ModelNode toModelNode() {
return new ModelNode().set(toString());
}
}
| 2,546 | 30.060976 | 108 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingSubsystemXMLAttribute.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import java.util.HashMap;
import java.util.Map;
/**
* @author Stuart Douglas
*/
public enum NamingSubsystemXMLAttribute {
UNKNOWN(null),
CACHE("cache"),
CLASS("class"),
LOOKUP("lookup"),
MODULE("module"),
NAME("name"),
TYPE("type"),
VALUE("value"),;
private final String name;
NamingSubsystemXMLAttribute(final String name) {
this.name = name;
}
/**
* Get the local name of this attribute.
*
* @return the local name
*/
public String getLocalName() {
return name;
}
private static final Map<String, NamingSubsystemXMLAttribute> MAP;
static {
final Map<String, NamingSubsystemXMLAttribute> map = new HashMap<String, NamingSubsystemXMLAttribute>();
for (NamingSubsystemXMLAttribute element : values()) {
final String name = element.getLocalName();
if (name != null)
map.put(name, element);
}
MAP = map;
}
public static NamingSubsystemXMLAttribute forName(String localName) {
final NamingSubsystemXMLAttribute element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
@Override
public String toString() {
return getLocalName();
}
}
| 2,341 | 29.025641 | 112 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingSubsystem13Parser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.requireAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import static org.jboss.as.naming.subsystem.NamingExtension.SUBSYSTEM_PATH;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.BINDING;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.BINDING_TYPE;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.LOOKUP;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.OBJECT_FACTORY;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.SIMPLE;
import java.util.EnumSet;
import java.util.List;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* @author Eduardo Martins
*/
public class NamingSubsystem13Parser implements XMLElementReader<List<ModelNode>> {
NamingSubsystem13Parser() {
}
/**
* {@inheritDoc}
*/
@Override
public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> operations) throws XMLStreamException {
PathAddress address = PathAddress.pathAddress(SUBSYSTEM_PATH);
final ModelNode ejb3SubsystemAddOperation = Util.createAddOperation(address);
operations.add(ejb3SubsystemAddOperation);
// elements
final EnumSet<NamingSubsystemXMLElement> encountered = EnumSet.noneOf(NamingSubsystemXMLElement.class);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (NamingSubsystemNamespace.forUri(reader.getNamespaceURI())) {
case NAMING_1_3: {
final NamingSubsystemXMLElement element = NamingSubsystemXMLElement.forName(reader.getLocalName());
if (!encountered.add(element)) {
throw unexpectedElement(reader);
}
switch (element) {
case BINDINGS: {
parseBindings(reader, operations, address);
break;
}
case REMOTE_NAMING: {
parseRemoteNaming(reader, operations, address);
break;
}
default: {
throw unexpectedElement(reader);
}
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseRemoteNaming(final XMLExtendedStreamReader reader, final List<ModelNode> operations, PathAddress parent) throws XMLStreamException {
requireNoAttributes(reader);
requireNoContent(reader);
operations.add(Util.createAddOperation(parent.append(NamingSubsystemModel.SERVICE, NamingSubsystemModel.REMOTE_NAMING)));
}
private void parseBindings(final XMLExtendedStreamReader reader, final List<ModelNode> operations, PathAddress address) throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (NamingSubsystemXMLElement.forName(reader.getLocalName())) {
case SIMPLE: {
this.parseSimpleBinding(reader, operations, address);
break;
}
case OBJECT_FACTORY: {
this.parseObjectFactoryBinding(reader, operations, address);
break;
}
case LOOKUP: {
this.parseLookupBinding(reader, operations, address);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseSimpleBinding(final XMLExtendedStreamReader reader, List<ModelNode> operations, PathAddress parentAddress) throws XMLStreamException {
String name = null;
final ModelNode bindingAdd = Util.createAddOperation();
bindingAdd.get(BINDING_TYPE).set(SIMPLE);
final EnumSet<NamingSubsystemXMLAttribute> required = EnumSet.of(NamingSubsystemXMLAttribute.NAME, NamingSubsystemXMLAttribute.VALUE);
for (int i = 0; i < reader.getAttributeCount(); i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final NamingSubsystemXMLAttribute attribute = NamingSubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
name = value.trim();
break;
case VALUE:
NamingBindingResourceDefinition.VALUE.parseAndSetParameter(value, bindingAdd, reader);
break;
case TYPE:
NamingBindingResourceDefinition.TYPE.parseAndSetParameter(value, bindingAdd, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
final PathAddress address = parentAddress.append(BINDING, name);
bindingAdd.get(OP_ADDR).set(address.toModelNode());
operations.add(bindingAdd);
}
private void parseObjectFactoryBinding(final XMLExtendedStreamReader reader, List<ModelNode> operations, PathAddress parentAddress) throws XMLStreamException {
final int attCount = reader.getAttributeCount();
String name = null;
final ModelNode bindingAdd = Util.createAddOperation();
bindingAdd.get(BINDING_TYPE).set(OBJECT_FACTORY);
final EnumSet<NamingSubsystemXMLAttribute> required = EnumSet.of(NamingSubsystemXMLAttribute.NAME, NamingSubsystemXMLAttribute.MODULE, NamingSubsystemXMLAttribute.CLASS);
for (int i = 0; i < attCount; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final NamingSubsystemXMLAttribute attribute = NamingSubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
name = value.trim();
break;
case MODULE:
NamingBindingResourceDefinition.MODULE.parseAndSetParameter(value, bindingAdd, reader);
break;
case CLASS:
NamingBindingResourceDefinition.CLASS.parseAndSetParameter(value, bindingAdd, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
bindingAdd.get(OP_ADDR).set(parentAddress.append(BINDING, name).toModelNode());
// if present, parse the optional environment
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (NamingSubsystemXMLElement.forName(reader.getLocalName())) {
case ENVIRONMENT: {
parseObjectFactoryBindingEnvironment(reader, bindingAdd);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
operations.add(bindingAdd);
}
/**
* <p>
* Parses the optional {@code ObjectFactory environment}.
* </p>
*
* @param reader the {@code XMLExtendedStreamReader} used to read the configuration XML.
* @param bindingAdd where to add
* @throws XMLStreamException if an error occurs while parsing the XML.
*/
private void parseObjectFactoryBindingEnvironment(XMLExtendedStreamReader reader, ModelNode bindingAdd) throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (NamingSubsystemXMLElement.forName(reader.getLocalName())) {
case ENVIRONMENT_PROPERTY: {
final String[] array = requireAttributes(reader, org.jboss.as.controller.parsing.Attribute.NAME.getLocalName(), org.jboss.as.controller.parsing.Attribute.VALUE.getLocalName());
NamingBindingResourceDefinition.ENVIRONMENT.parseAndAddParameterElement(array[0], array[1], bindingAdd, reader);
requireNoContent(reader);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseLookupBinding(final XMLExtendedStreamReader reader, List<ModelNode> operations, PathAddress parentAddress) throws XMLStreamException {
final int attCount = reader.getAttributeCount();
String name = null;
final ModelNode bindingAdd = Util.createAddOperation();
bindingAdd.get(BINDING_TYPE).set(LOOKUP);
final EnumSet<NamingSubsystemXMLAttribute> required = EnumSet.of(NamingSubsystemXMLAttribute.NAME, NamingSubsystemXMLAttribute.LOOKUP);
for (int i = 0; i < attCount; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final NamingSubsystemXMLAttribute attribute = NamingSubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
name = value.trim();
break;
case LOOKUP:
NamingBindingResourceDefinition.LOOKUP.parseAndSetParameter(value, bindingAdd, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
bindingAdd.get(OP_ADDR).set(parentAddress.append(BINDING, name).toModelNode());
operations.add(bindingAdd);
}
}
| 12,328 | 44.662963 | 196 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingSubsystemModel.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import org.jboss.as.controller.PathElement;
/**
* User: jpai
*/
public interface NamingSubsystemModel {
String BINDING = "binding";
String BINDING_TYPE = "binding-type";
String CACHE = "cache";
String CLASS = "class";
String EXTERNAL_CONTEXT = "external-context";
String LOOKUP = "lookup";
String OBJECT_FACTORY = "object-factory";
String ENVIRONMENT = "environment";
String MODULE = "module";
String REBIND = "rebind";
String REMOTE_NAMING = "remote-naming";
String SIMPLE = "simple";
String SERVICE = "service";
String TYPE = "type";
String VALUE = "value";
PathElement BINDING_PATH = PathElement.pathElement(BINDING);
PathElement REMOTE_NAMING_PATH = PathElement.pathElement(SERVICE, REMOTE_NAMING);
}
| 1,853 | 28.903226 | 85 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingSubsystemAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.naming.NamingContext;
import org.jboss.as.naming.NamingStore;
import org.jboss.as.naming.context.external.ExternalContexts;
import org.jboss.as.naming.context.external.ExternalContextsNavigableSet;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.deployment.ExternalContextsProcessor;
import org.jboss.as.naming.deployment.JndiNamingDependencyProcessor;
import org.jboss.as.naming.management.JndiViewExtensionRegistry;
import org.jboss.as.naming.remote.HttpRemoteNamingServerService;
import org.jboss.as.naming.service.DefaultNamespaceContextSelectorService;
import org.jboss.as.naming.service.ExternalContextsService;
import org.jboss.as.naming.service.NamingService;
import org.jboss.as.naming.service.NamingStoreService;
import org.jboss.as.naming.subsystem.NamingSubsystemRootResourceDefinition.Capability;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.Phase;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceTarget;
import static org.jboss.as.naming.logging.NamingLogger.ROOT_LOGGER;
import io.undertow.server.handlers.PathHandler;
/**
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
* @author Emanuel Muckenhuber
* @author John Bailey
* @author Eduardo Martins
*/
public class NamingSubsystemAdd extends AbstractBoottimeAddStepHandler {
private static final String UNDERTOW_HTTP_INVOKER_CAPABILITY_NAME = "org.wildfly.undertow.http-invoker";
@Override
protected void populateModel(ModelNode operation, ModelNode model) {
model.setEmptyObject();
}
@SuppressWarnings("deprecation")
@Override
protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) {
ROOT_LOGGER.activatingSubsystem();
NamingContext.initializeNamingManager();
final ServiceTarget target = context.getServiceTarget();
// Create the java: namespace
target.addService(ContextNames.JAVA_CONTEXT_SERVICE_NAME, new NamingStoreService())
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
// Create the Naming Service
final NamingService namingService = new NamingService();
target.addService(Capability.NAMING_STORE.getDefinition().getCapabilityServiceName(), namingService)
.addAliases(NamingService.SERVICE_NAME)
.addDependency(ContextNames.JAVA_CONTEXT_SERVICE_NAME, NamingStore.class, namingService.getNamingStore())
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
// Create the java:global namespace
target.addService(ContextNames.GLOBAL_CONTEXT_SERVICE_NAME, new NamingStoreService())
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
// Create the java:jboss vendor namespace
target.addService(ContextNames.JBOSS_CONTEXT_SERVICE_NAME, new NamingStoreService())
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
// Setup remote naming store
//we always install the naming store, but we don't install the server unless it has been explicitly enabled
target.addService(ContextNames.EXPORTED_CONTEXT_SERVICE_NAME, new NamingStoreService())
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
// add the default namespace context selector service
DefaultNamespaceContextSelectorService defaultNamespaceContextSelectorService = new DefaultNamespaceContextSelectorService();
target.addService(DefaultNamespaceContextSelectorService.SERVICE_NAME, defaultNamespaceContextSelectorService)
.addDependency(ContextNames.GLOBAL_CONTEXT_SERVICE_NAME, NamingStore.class, defaultNamespaceContextSelectorService.getGlobalNamingStore())
.addDependency(ContextNames.JBOSS_CONTEXT_SERVICE_NAME, NamingStore.class, defaultNamespaceContextSelectorService.getJbossNamingStore())
.addDependency(ContextNames.EXPORTED_CONTEXT_SERVICE_NAME, NamingStore.class, defaultNamespaceContextSelectorService.getRemoteExposedNamingStore())
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
target.addService(JndiViewExtensionRegistry.SERVICE_NAME, new JndiViewExtensionRegistry()).install();
// create the subsystem's external context instance, and install related Service and DUP
final ExternalContexts externalContexts = new ExternalContextsNavigableSet();
target.addService(ExternalContextsService.SERVICE_NAME, new ExternalContextsService(externalContexts)).install();
context.addStep(new AbstractDeploymentChainStep() {
@Override
protected void execute(DeploymentProcessorTarget processorTarget) {
processorTarget.addDeploymentProcessor(NamingExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, Phase.STRUCTURE_NAMING_EXTERNAL_CONTEXTS, new ExternalContextsProcessor(externalContexts));
processorTarget.addDeploymentProcessor(NamingExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_JNDI_DEPENDENCIES, new JndiNamingDependencyProcessor());
}
}, OperationContext.Stage.RUNTIME);
if(context.hasOptionalCapability(UNDERTOW_HTTP_INVOKER_CAPABILITY_NAME, NamingService.CAPABILITY_NAME, null)) {
HttpRemoteNamingServerService httpRemoteNamingServerService = new HttpRemoteNamingServerService();
context.getServiceTarget().addService(HttpRemoteNamingServerService.SERVICE_NAME, httpRemoteNamingServerService)
.addDependency(context.getCapabilityServiceName(UNDERTOW_HTTP_INVOKER_CAPABILITY_NAME, PathHandler.class), PathHandler.class, httpRemoteNamingServerService.getPathHandlerInjectedValue())
.addDependency(ContextNames.EXPORTED_CONTEXT_SERVICE_NAME, NamingStore.class, httpRemoteNamingServerService.getNamingStore())
.install();
}
}
}
| 7,371 | 52.42029 | 206 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingSubsystem10Parser.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import java.util.List;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.parsing.ParseUtils;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* @author Stuart Douglas
*/
class NamingSubsystem10Parser implements XMLStreamConstants, XMLElementReader<List<ModelNode>> {
private final boolean appclient;
NamingSubsystem10Parser(boolean appclient) {
this.appclient = appclient;
}
/**
* {@inheritDoc}
*/
@Override
public void readElement(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException {
ParseUtils.requireNoAttributes(reader);
ParseUtils.requireNoContent(reader);
list.add(Util.createAddOperation(PathAddress.pathAddress(NamingExtension.SUBSYSTEM_PATH)));
if(!appclient) {
//we do not add remote naming to the application client
//note that this is a bi
list.add(Util.createAddOperation(PathAddress.pathAddress(NamingExtension.SUBSYSTEM_PATH).append(NamingSubsystemModel.SERVICE, NamingSubsystemModel.REMOTE_NAMING)));
}
}
}
| 2,392 | 37.596774 | 176 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingBindingAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.TYPE;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Map;
import javax.naming.InitialContext;
import javax.naming.spi.ObjectFactory;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.naming.ContextListAndJndiViewManagedReferenceFactory;
import org.jboss.as.naming.ContextListManagedReferenceFactory;
import org.jboss.as.naming.ExternalContextObjectFactory;
import org.jboss.as.naming.ImmediateManagedReference;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.logging.NamingLogger;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.ValueManagedReferenceFactory;
import org.jboss.as.naming.context.external.ExternalContexts;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.BinderService;
import org.jboss.as.naming.service.ExternalContextBinderService;
import org.jboss.as.naming.service.ExternalContextsService;
import org.jboss.dmr.ModelNode;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
import org.jboss.modules.ModuleNotFoundException;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* A {@link org.jboss.as.controller.AbstractAddStepHandler} to handle the add operation for simple JNDI bindings
*
* @author Stuart Douglas
* @author Eduardo Martins
*/
public class NamingBindingAdd extends AbstractAddStepHandler {
private static final String[] GLOBAL_NAMESPACES = {"java:global", "java:jboss", "java:/"};
static final NamingBindingAdd INSTANCE = new NamingBindingAdd();
private NamingBindingAdd() {
}
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
final String name = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.ADDRESS)).getLastElement().getValue();
installRuntimeServices(context, name, model);
}
void installRuntimeServices(final OperationContext context, final String name, final ModelNode model) throws OperationFailedException {
boolean allowed = false;
for (String ns : GLOBAL_NAMESPACES) {
if (name.startsWith(ns)) {
allowed = true;
break;
}
}
if (!allowed) {
throw NamingLogger.ROOT_LOGGER.invalidNamespaceForBinding(name, Arrays.toString(GLOBAL_NAMESPACES));
}
final BindingType type = BindingType.forName(NamingBindingResourceDefinition.BINDING_TYPE.resolveModelAttribute(context, model).asString());
if (type == BindingType.SIMPLE) {
installSimpleBinding(context, name, model);
} else if (type == BindingType.OBJECT_FACTORY) {
installObjectFactory(context, name, model);
} else if (type == BindingType.LOOKUP) {
installLookup(context, name, model);
} else if (type == BindingType.EXTERNAL_CONTEXT) {
installExternalContext(context, name, model);
} else {
throw NamingLogger.ROOT_LOGGER.unknownBindingType(type.toString());
}
}
void installSimpleBinding(final OperationContext context, final String name, final ModelNode model) throws OperationFailedException {
Object bindValue = createSimpleBinding(context, model);
ValueManagedReferenceFactory referenceFactory = new ValueManagedReferenceFactory(bindValue);
final BinderService binderService = new BinderService(name, bindValue);
binderService.getManagedObjectInjector().inject(new MutableManagedReferenceFactory(referenceFactory));
final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(name);
final ServiceTarget serviceTarget = context.getServiceTarget();
ServiceBuilder<ManagedReferenceFactory> builder = serviceTarget.addService(bindInfo.getBinderServiceName(), binderService)
.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector());
builder.install();
}
private Object createSimpleBinding(OperationContext context, ModelNode model) throws OperationFailedException {
final String value = NamingBindingResourceDefinition.VALUE.resolveModelAttribute(context, model).asString();
final String type;
if (model.hasDefined(TYPE)) {
type = NamingBindingResourceDefinition.TYPE.resolveModelAttribute(context, model).asString();
} else {
type = null;
}
return coerceToType(value, type);
}
void installObjectFactory(final OperationContext context, final String name, final ModelNode model) throws OperationFailedException {
final ObjectFactory objectFactoryClassInstance = createObjectFactory(context, model);
final Hashtable<String, String> environment = getObjectFactoryEnvironment(context, model);
ContextListAndJndiViewManagedReferenceFactory factory = new ObjectFactoryManagedReference(objectFactoryClassInstance, name, environment);
final ServiceTarget serviceTarget = context.getServiceTarget();
final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(name);
final BinderService binderService = new BinderService(name, objectFactoryClassInstance);
binderService.getManagedObjectInjector().inject(new MutableManagedReferenceFactory(factory));
serviceTarget.addService(bindInfo.getBinderServiceName(), binderService)
.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector())
.install();
}
private ObjectFactory createObjectFactory(OperationContext context, ModelNode model) throws OperationFailedException {
final ModuleIdentifier moduleID = ModuleIdentifier.fromString(NamingBindingResourceDefinition.MODULE.resolveModelAttribute(context, model).asString());
final String className = NamingBindingResourceDefinition.CLASS.resolveModelAttribute(context, model).asString();
final Module module;
try {
module = Module.getBootModuleLoader().loadModule(moduleID);
} catch (ModuleNotFoundException e) {
throw NamingLogger.ROOT_LOGGER.moduleNotFound(moduleID, e.getMessage());
} catch (ModuleLoadException e) {
throw NamingLogger.ROOT_LOGGER.couldNotLoadModule(moduleID);
}
final ObjectFactory objectFactoryClassInstance;
final ClassLoader cl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader());
final Class<?> clazz = module.getClassLoader().loadClass(className);
objectFactoryClassInstance = (ObjectFactory) clazz.newInstance();
} catch (ClassNotFoundException e) {
throw NamingLogger.ROOT_LOGGER.couldNotLoadClassFromModule(className, moduleID);
} catch (InstantiationException e) {
throw NamingLogger.ROOT_LOGGER.couldNotInstantiateClassInstanceFromModule(className, moduleID);
} catch (IllegalAccessException e) {
throw NamingLogger.ROOT_LOGGER.couldNotInstantiateClassInstanceFromModule(className, moduleID);
} catch (ClassCastException e) {
throw NamingLogger.ROOT_LOGGER.notAnInstanceOfObjectFactory(className, moduleID);
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(cl);
}
return objectFactoryClassInstance;
}
void installExternalContext(final OperationContext context, final String name, final ModelNode model) throws OperationFailedException {
final String moduleID = NamingBindingResourceDefinition.MODULE.resolveModelAttribute(context, model).asString();
final String className = NamingBindingResourceDefinition.CLASS.resolveModelAttribute(context, model).asString();
final ModelNode cacheNode = NamingBindingResourceDefinition.CACHE.resolveModelAttribute(context, model);
boolean cache = cacheNode.isDefined() ? cacheNode.asBoolean() : false;
final ObjectFactory objectFactoryClassInstance = new ExternalContextObjectFactory();
final ServiceTarget serviceTarget = context.getServiceTarget();
final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(name);
final Hashtable<String, String> environment = getObjectFactoryEnvironment(context, model);
environment.put(ExternalContextObjectFactory.CACHE_CONTEXT, Boolean.toString(cache));
environment.put(ExternalContextObjectFactory.INITIAL_CONTEXT_CLASS, className);
environment.put(ExternalContextObjectFactory.INITIAL_CONTEXT_MODULE, moduleID);
final ExternalContextBinderService binderService = new ExternalContextBinderService(name, objectFactoryClassInstance);
binderService.getManagedObjectInjector().inject(new ContextListAndJndiViewManagedReferenceFactory() {
@Override
public ManagedReference getReference() {
try {
final Object value = objectFactoryClassInstance.getObjectInstance(name, null, null, environment);
return new ImmediateManagedReference(value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public String getInstanceClassName() {
return className;
}
@Override
public String getJndiViewInstanceValue() {
final ClassLoader cl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(objectFactoryClassInstance.getClass().getClassLoader());
return String.valueOf(getReference().getInstance());
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(cl);
}
}
});
serviceTarget.addService(bindInfo.getBinderServiceName(), binderService)
.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector())
.addDependency(ExternalContextsService.SERVICE_NAME, ExternalContexts.class, binderService.getExternalContextsInjector())
.install();
}
private Hashtable<String, String> getObjectFactoryEnvironment(OperationContext context, ModelNode model) throws OperationFailedException {
Hashtable<String, String> environment;
Map<String, String> resolvedModelAttribute = NamingBindingResourceDefinition.ENVIRONMENT.unwrap(context, model);
environment = new Hashtable<String, String>(resolvedModelAttribute);
return environment;
}
void installLookup(final OperationContext context, final String name, final ModelNode model) throws OperationFailedException {
final String lookup = NamingBindingResourceDefinition.LOOKUP.resolveModelAttribute(context, model).asString();
final ServiceTarget serviceTarget = context.getServiceTarget();
final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(name);
final BinderService binderService = new BinderService(name);
binderService.getManagedObjectInjector().inject(new MutableManagedReferenceFactory(new LookupManagedReferenceFactory(lookup)));
serviceTarget.addService(bindInfo.getBinderServiceName(), binderService)
.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector())
.install();
}
private Object coerceToType(final String value, final String type) throws OperationFailedException {
if (type == null || type.isEmpty() || type.equals(String.class.getName())) {
return value;
} else if (type.equals("char") || type.equals("java.lang.Character")) {
return value.charAt(0);
} else if (type.equals("byte") || type.equals("java.lang.Byte")) {
return Byte.parseByte(value);
} else if (type.equals("short") || type.equals("java.lang.Short")) {
return Short.parseShort(value);
} else if (type.equals("int") || type.equals("java.lang.Integer")) {
return Integer.parseInt(value);
} else if (type.equals("long") || type.equals("java.lang.Long")) {
return Long.parseLong(value);
} else if (type.equals("float") || type.equals("java.lang.Float")) {
return Float.parseFloat(value);
} else if (type.equals("double") || type.equals("java.lang.Double")) {
return Double.parseDouble(value);
} else if (type.equals("boolean") || type.equals("java.lang.Boolean")) {
return Boolean.parseBoolean(value);
} else if (type.equals(URL.class.getName())) {
try {
return new URL(value);
} catch (MalformedURLException e) {
throw NamingLogger.ROOT_LOGGER.unableToTransformURLBindingValue(value, e);
}
} else {
throw NamingLogger.ROOT_LOGGER.unsupportedSimpleBindingType(type);
}
}
@Override
protected void populateModel(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
super.populateModel(context, operation, resource);
context.addStep(NamingBindingResourceDefinition.VALIDATE_RESOURCE_MODEL_OPERATION_STEP_HANDLER, OperationContext.Stage.MODEL);
}
@Override
protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException {
for (AttributeDefinition attr : NamingBindingResourceDefinition.ATTRIBUTES) {
attr.validateAndSet(operation, model);
}
}
void doRebind(OperationContext context, ModelNode model, BinderService service) throws OperationFailedException {
ManagedReferenceFactory ref = service.getManagedObjectInjector().getValue();
if(ref instanceof MutableManagedReferenceFactory) {
MutableManagedReferenceFactory factory = (MutableManagedReferenceFactory) ref;
final BindingType type = BindingType.forName(NamingBindingResourceDefinition.BINDING_TYPE.resolveModelAttribute(context, model).asString());
if (type == BindingType.SIMPLE) {
Object bindValue = createSimpleBinding(context, model);
factory.setFactory(new ValueManagedReferenceFactory(bindValue));
service.setSource(bindValue);
} else if (type == BindingType.OBJECT_FACTORY) {
final ObjectFactory objectFactoryClassInstance = createObjectFactory(context, model);
final Hashtable<String, String> environment = getObjectFactoryEnvironment(context, model);
factory.setFactory(new ObjectFactoryManagedReference(objectFactoryClassInstance, service.getName(), environment));
service.setSource(objectFactoryClassInstance);
} else if (type == BindingType.LOOKUP) {
final String lookup = NamingBindingResourceDefinition.LOOKUP.resolveModelAttribute(context, model).asString();
factory.setFactory(new LookupManagedReferenceFactory(lookup));
service.setSource(null);
} else if (type == BindingType.EXTERNAL_CONTEXT) {
throw NamingLogger.ROOT_LOGGER.cannotRebindExternalContext();
} else {
throw NamingLogger.ROOT_LOGGER.unknownBindingType(type.toString());
}
} else {
throw NamingLogger.ROOT_LOGGER.cannotRebindExternalContext();
}
}
static class MutableManagedReferenceFactory implements ContextListAndJndiViewManagedReferenceFactory {
MutableManagedReferenceFactory(ManagedReferenceFactory factory) {
this.factory = factory;
}
private volatile ManagedReferenceFactory factory;
@Override
public ManagedReference getReference() {
return factory.getReference();
}
public ManagedReferenceFactory getFactory() {
return factory;
}
public void setFactory(ManagedReferenceFactory factory) {
this.factory = factory;
}
@Override
public String getInstanceClassName() {
if(factory instanceof ContextListManagedReferenceFactory) {
return ((ContextListManagedReferenceFactory) factory).getInstanceClassName();
}
ManagedReference ref = getReference();
try {
final Object value = ref.getInstance();
return value != null ? value.getClass().getName() : ContextListManagedReferenceFactory.DEFAULT_INSTANCE_CLASS_NAME;
} finally {
ref.release();
}
}
@Override
public String getJndiViewInstanceValue() {
if(factory instanceof ContextListAndJndiViewManagedReferenceFactory) {
return ((ContextListAndJndiViewManagedReferenceFactory) factory).getJndiViewInstanceValue();
}
ManagedReference reference = getReference();
try {
return String.valueOf(reference.getInstance());
} finally {
reference.release();
}
}
}
private static class ObjectFactoryManagedReference implements ContextListAndJndiViewManagedReferenceFactory {
private final ObjectFactory objectFactoryClassInstance;
private final String name;
private final Hashtable<String, String> environment;
ObjectFactoryManagedReference(ObjectFactory objectFactoryClassInstance, String name, Hashtable<String, String> environment) {
this.objectFactoryClassInstance = objectFactoryClassInstance;
this.name = name;
this.environment = environment;
}
@Override
public ManagedReference getReference() {
try {
final Object value = objectFactoryClassInstance.getObjectInstance(name, null, null, environment);
return new ImmediateManagedReference(value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public String getInstanceClassName() {
final ClassLoader cl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(objectFactoryClassInstance.getClass().getClassLoader());
final Object value = getReference().getInstance();
return value != null ? value.getClass().getName() : ContextListManagedReferenceFactory.DEFAULT_INSTANCE_CLASS_NAME;
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(cl);
}
}
@Override
public String getJndiViewInstanceValue() {
final ClassLoader cl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(objectFactoryClassInstance.getClass().getClassLoader());
return String.valueOf(getReference().getInstance());
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(cl);
}
}
}
private static class LookupManagedReferenceFactory implements ManagedReferenceFactory {
private final String lookup;
LookupManagedReferenceFactory(String lookup) {
this.lookup = lookup;
}
@Override
public ManagedReference getReference() {
try {
final Object value = new InitialContext().lookup(lookup);
return new ImmediateManagedReference(value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
| 21,998 | 47.032751 | 159 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingBindingRemove.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import org.jboss.as.controller.ServiceRemoveStepHandler;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.msc.service.ServiceName;
/**
* Handles removing a JNDI binding
*/
public class NamingBindingRemove extends ServiceRemoveStepHandler {
public static final NamingBindingRemove INSTANCE = new NamingBindingRemove();
private NamingBindingRemove() {
super(NamingBindingAdd.INSTANCE);
}
@Override
protected ServiceName serviceName(final String name) {
return ContextNames.bindInfoFor(name).getBinderServiceName();
}
}
| 1,648 | 34.847826 | 81 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingSubsystem20Parser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
/**
* @author Eduardo Martins
*/
class NamingSubsystem20Parser extends NamingSubsystem14Parser {
NamingSubsystem20Parser() {
super(NamingSubsystemNamespace.NAMING_2_0);
}
}
| 1,256 | 35.970588 | 70 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingSubsystem11Parser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.BINDING;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.BINDING_TYPE;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.CLASS;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.LOOKUP;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.MODULE;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.OBJECT_FACTORY;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.SIMPLE;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.TYPE;
import static org.jboss.as.naming.subsystem.NamingSubsystemModel.VALUE;
import java.util.EnumSet;
import java.util.List;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* @author Stuart Douglas
*/
public class NamingSubsystem11Parser implements XMLElementReader<List<ModelNode>> {
NamingSubsystem11Parser() {
}
/**
* {@inheritDoc}
*/
@Override
public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> operations) throws XMLStreamException {
operations.add(Util.createAddOperation(PathAddress.pathAddress(NamingExtension.SUBSYSTEM_PATH)));
operations.add(Util.createAddOperation(PathAddress.pathAddress(NamingExtension.SUBSYSTEM_PATH).append(NamingSubsystemModel.SERVICE, NamingSubsystemModel.REMOTE_NAMING)));
// elements
final EnumSet<NamingSubsystemXMLElement> encountered = EnumSet.noneOf(NamingSubsystemXMLElement.class);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (NamingSubsystemNamespace.forUri(reader.getNamespaceURI())) {
case NAMING_1_1: {
final NamingSubsystemXMLElement element = NamingSubsystemXMLElement.forName(reader.getLocalName());
if (!encountered.add(element)) {
throw unexpectedElement(reader);
}
switch (element) {
case BINDINGS: {
parseBindings(reader, operations);
break;
}
default: {
throw unexpectedElement(reader);
}
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseBindings(final XMLExtendedStreamReader reader, final List<ModelNode> operations) throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (NamingSubsystemXMLElement.forName(reader.getLocalName())) {
case SIMPLE: {
this.parseSimpleBinding(reader, operations);
break;
}
case OBJECT_FACTORY: {
this.parseObjectFactoryBinding(reader, operations);
break;
}
case LOOKUP: {
this.parseLookupBinding(reader, operations);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseSimpleBinding(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
final int attCount = reader.getAttributeCount();
String name = null;
String bindingValue = null;
String type = null;
final EnumSet<NamingSubsystemXMLAttribute> required = EnumSet.of(NamingSubsystemXMLAttribute.NAME, NamingSubsystemXMLAttribute.VALUE);
for (int i = 0; i < attCount; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final NamingSubsystemXMLAttribute attribute = NamingSubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
name = value.trim();
break;
case VALUE:
bindingValue = parse(NamingBindingResourceDefinition.VALUE, value, reader).asString();
break;
case TYPE:
type = parse(NamingBindingResourceDefinition.TYPE, value, reader).asString();
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
final ModelNode address = new ModelNode();
address.add(SUBSYSTEM, NamingExtension.SUBSYSTEM_NAME);
address.add(BINDING, name);
final ModelNode bindingAdd = new ModelNode();
bindingAdd.get(OP).set(ADD);
bindingAdd.get(OP_ADDR).set(address);
bindingAdd.get(BINDING_TYPE).set(SIMPLE);
bindingAdd.get(VALUE).set(bindingValue);
if (type != null) {
bindingAdd.get(TYPE).set(type);
}
operations.add(bindingAdd);
}
private void parseObjectFactoryBinding(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
final int attCount = reader.getAttributeCount();
String name = null;
String module = null;
String factory = null;
final EnumSet<NamingSubsystemXMLAttribute> required = EnumSet.of(NamingSubsystemXMLAttribute.NAME, NamingSubsystemXMLAttribute.MODULE, NamingSubsystemXMLAttribute.CLASS);
for (int i = 0; i < attCount; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final NamingSubsystemXMLAttribute attribute = NamingSubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
name = value.trim();
break;
case MODULE:
module = parse(NamingBindingResourceDefinition.MODULE, value, reader).asString();
break;
case CLASS:
factory = parse(NamingBindingResourceDefinition.CLASS, value, reader).asString();
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
final ModelNode address = new ModelNode();
address.add(SUBSYSTEM, NamingExtension.SUBSYSTEM_NAME);
address.add(BINDING, name);
final ModelNode bindingAdd = new ModelNode();
bindingAdd.get(OP).set(ADD);
bindingAdd.get(OP_ADDR).set(address);
bindingAdd.get(BINDING_TYPE).set(OBJECT_FACTORY);
bindingAdd.get(MODULE).set(module);
bindingAdd.get(CLASS).set(factory);
operations.add(bindingAdd);
}
private void parseLookupBinding(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
final int attCount = reader.getAttributeCount();
String name = null;
String lookup = null;
final EnumSet<NamingSubsystemXMLAttribute> required = EnumSet.of(NamingSubsystemXMLAttribute.NAME, NamingSubsystemXMLAttribute.LOOKUP);
for (int i = 0; i < attCount; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final NamingSubsystemXMLAttribute attribute = NamingSubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
name = value.trim();
break;
case LOOKUP:
lookup = parse(NamingBindingResourceDefinition.LOOKUP, value, reader).asString();
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
final ModelNode address = new ModelNode();
address.add(SUBSYSTEM, NamingExtension.SUBSYSTEM_NAME);
address.add(BINDING, name);
final ModelNode bindingAdd = new ModelNode();
bindingAdd.get(OP).set(ADD);
bindingAdd.get(OP_ADDR).set(address);
bindingAdd.get(BINDING_TYPE).set(LOOKUP);
bindingAdd.get(LOOKUP).set(lookup);
operations.add(bindingAdd);
}
protected static ModelNode parse(AttributeDefinition ad, String value, XMLStreamReader reader) throws XMLStreamException {
return ad.getParser().parse(ad, value, reader);
}
}
| 11,432 | 42.471483 | 178 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingBindingResourceDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PropertiesAttributeDefinition;
import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.access.management.AccessConstraintDefinition;
import org.jboss.as.controller.operations.validation.EnumValidator;
import org.jboss.as.controller.operations.validation.StringAllowedValuesValidator;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.logging.NamingLogger;
import org.jboss.as.naming.service.BinderService;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.msc.service.ServiceController;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
/**
* A {@link org.jboss.as.controller.ResourceDefinition} for JNDI bindings
*/
public class NamingBindingResourceDefinition extends SimpleResourceDefinition {
private static final String[] ALLOWED_TYPES = {"char", "java.lang.Character", "byte", "java.lang.Byte", "short", "java.lang.Short", "int", "java.lang.Integer", "long", "java.lang.Long", "float", "java.lang.Float", "double", "java.lang.Double", "boolean", "java.lang.Boolean", "java.lang.String", "java.net.URL"};
static final SimpleAttributeDefinition BINDING_TYPE = new SimpleAttributeDefinitionBuilder(NamingSubsystemModel.BINDING_TYPE, ModelType.STRING, false)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.setValidator(EnumValidator.create(BindingType.class))
.build();
static final SimpleAttributeDefinition VALUE = new SimpleAttributeDefinitionBuilder(NamingSubsystemModel.VALUE, ModelType.STRING, true)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
static final SimpleAttributeDefinition TYPE = new SimpleAttributeDefinitionBuilder(NamingSubsystemModel.TYPE, ModelType.STRING, true)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.setValidator(new StringAllowedValuesValidator(ALLOWED_TYPES))
.build();
static final SimpleAttributeDefinition CLASS = new SimpleAttributeDefinitionBuilder(NamingSubsystemModel.CLASS, ModelType.STRING, true)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
static final SimpleAttributeDefinition MODULE = new SimpleAttributeDefinitionBuilder(NamingSubsystemModel.MODULE, ModelType.STRING, true)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
static final SimpleAttributeDefinition LOOKUP = new SimpleAttributeDefinitionBuilder(NamingSubsystemModel.LOOKUP, ModelType.STRING, true)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
static final PropertiesAttributeDefinition ENVIRONMENT = new PropertiesAttributeDefinition.Builder(NamingSubsystemModel.ENVIRONMENT, true)
.setAllowExpression(true)
.build();
static final SimpleAttributeDefinition CACHE = new SimpleAttributeDefinitionBuilder(NamingSubsystemModel.CACHE, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
static final AttributeDefinition[] ATTRIBUTES = {BINDING_TYPE, VALUE, TYPE, CLASS, MODULE, LOOKUP, ENVIRONMENT, CACHE};
private static final List<AccessConstraintDefinition> ACCESS_CONSTRAINTS;
static {
List<AccessConstraintDefinition> constraints = new ArrayList<AccessConstraintDefinition>();
constraints.add(NamingExtension.NAMING_BINDING_APPLICATION_CONSTRAINT);
constraints.add(NamingExtension.NAMING_BINDING_SENSITIVITY_CONSTRAINT);
ACCESS_CONSTRAINTS = Collections.unmodifiableList(constraints);
}
static final OperationStepHandler VALIDATE_RESOURCE_MODEL_OPERATION_STEP_HANDLER = (context, op) -> validateResourceModel(context.readResource(PathAddress.EMPTY_ADDRESS).getModel(), true);
NamingBindingResourceDefinition() {
super(NamingSubsystemModel.BINDING_PATH,
NamingExtension.getResourceDescriptionResolver(NamingSubsystemModel.BINDING),
NamingBindingAdd.INSTANCE, NamingBindingRemove.INSTANCE);
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
OperationStepHandler writeHandler = new WriteAttributeHandler(ATTRIBUTES);
for (AttributeDefinition attr : ATTRIBUTES) {
resourceRegistration.registerReadWriteAttribute(attr, null, writeHandler);
}
}
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
super.registerOperations(resourceRegistration);
SimpleOperationDefinitionBuilder builder = new SimpleOperationDefinitionBuilder(NamingSubsystemModel.REBIND, getResourceDescriptionResolver())
// disallow rebind op for external-context
.addParameter(SimpleAttributeDefinitionBuilder.create(BINDING_TYPE)
.setValidator(new EnumValidator<>(BindingType.class, EnumSet.complementOf(EnumSet.of(BindingType.EXTERNAL_CONTEXT))))
.build())
.addParameter(TYPE)
.addParameter(VALUE)
.addParameter(CLASS)
.addParameter(MODULE)
.addParameter(LOOKUP)
.addParameter(ENVIRONMENT);
resourceRegistration.registerOperationHandler(builder.build(), new OperationStepHandler() {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
context.addStep(new OperationStepHandler() {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
Resource resource = context.readResourceForUpdate(PathAddress.EMPTY_ADDRESS);
ModelNode model = resource.getModel();
for (AttributeDefinition attr : ATTRIBUTES) {
attr.validateAndSet(operation, model);
}
context.addStep(NamingBindingResourceDefinition.VALIDATE_RESOURCE_MODEL_OPERATION_STEP_HANDLER, OperationContext.Stage.MODEL);
context.addStep(new OperationStepHandler() {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
final String name = context.getCurrentAddressValue();
final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(name);
ServiceController<ManagedReferenceFactory> service = (ServiceController<ManagedReferenceFactory>) context.getServiceRegistry(false).getService(bindInfo.getBinderServiceName());
if (service == null) {
context.reloadRequired();
return;
}
NamingBindingAdd.INSTANCE.doRebind(context, operation, (BinderService) service.getService());
}
}, OperationContext.Stage.RUNTIME);
}
}, OperationContext.Stage.MODEL);
}
});
}
@Override
public List<AccessConstraintDefinition> getAccessConstraints() {
return ACCESS_CONSTRAINTS;
}
private static class WriteAttributeHandler extends ReloadRequiredWriteAttributeHandler {
private WriteAttributeHandler(AttributeDefinition... definitions) {
super(definitions);
}
@Override
protected void validateUpdatedModel(OperationContext context, Resource model) throws OperationFailedException {
super.validateUpdatedModel(context, model);
context.addStep(VALIDATE_RESOURCE_MODEL_OPERATION_STEP_HANDLER, OperationContext.Stage.MODEL);
}
}
static void validateResourceModel(ModelNode modelNode, boolean allowExternal) throws OperationFailedException {
final BindingType type = BindingType.forName(modelNode.require(NamingSubsystemModel.BINDING_TYPE).asString());
if (type == BindingType.SIMPLE) {
if(!modelNode.hasDefined(NamingBindingResourceDefinition.VALUE.getName())) {
throw NamingLogger.ROOT_LOGGER.bindingTypeRequiresAttributeDefined(type, NamingBindingResourceDefinition.VALUE.getName());
}
if (modelNode.hasDefined(NamingBindingResourceDefinition.CACHE.getName())
&& modelNode.get(NamingBindingResourceDefinition.CACHE.getName()).asBoolean()) {
throw NamingLogger.ROOT_LOGGER.cacheNotValidForBindingType(type);
}
} else if (type == BindingType.OBJECT_FACTORY) {
if(!modelNode.hasDefined(NamingBindingResourceDefinition.MODULE.getName())) {
throw NamingLogger.ROOT_LOGGER.bindingTypeRequiresAttributeDefined(type, NamingBindingResourceDefinition.MODULE.getName());
}
if(!modelNode.hasDefined(NamingBindingResourceDefinition.CLASS.getName())) {
throw NamingLogger.ROOT_LOGGER.bindingTypeRequiresAttributeDefined(type, NamingBindingResourceDefinition.CLASS.getName());
}
if (modelNode.hasDefined(NamingBindingResourceDefinition.CACHE.getName())
&& modelNode.get(NamingBindingResourceDefinition.CACHE.getName()).asBoolean()) {
throw NamingLogger.ROOT_LOGGER.cacheNotValidForBindingType(type);
}
} else if (type == BindingType.EXTERNAL_CONTEXT) {
if(!allowExternal) {
throw NamingLogger.ROOT_LOGGER.cannotRebindExternalContext();
}
if(!modelNode.hasDefined(NamingBindingResourceDefinition.MODULE.getName())) {
throw NamingLogger.ROOT_LOGGER.bindingTypeRequiresAttributeDefined(type, NamingBindingResourceDefinition.MODULE.getName());
}
if(!modelNode.hasDefined(NamingBindingResourceDefinition.CLASS.getName())) {
throw NamingLogger.ROOT_LOGGER.bindingTypeRequiresAttributeDefined(type, NamingBindingResourceDefinition.CLASS.getName());
}
} else if (type == BindingType.LOOKUP) {
if(!modelNode.hasDefined(NamingBindingResourceDefinition.LOOKUP.getName())) {
throw NamingLogger.ROOT_LOGGER.bindingTypeRequiresAttributeDefined(type, NamingBindingResourceDefinition.LOOKUP.getName());
}
if (modelNode.hasDefined(NamingBindingResourceDefinition.CACHE.getName())
&& modelNode.get(NamingBindingResourceDefinition.CACHE.getName()).asBoolean()) {
throw NamingLogger.ROOT_LOGGER.cacheNotValidForBindingType(type);
}
} else {
throw NamingLogger.ROOT_LOGGER.unknownBindingType(type.toString());
}
}
}
| 13,172 | 54.348739 | 316 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingSubsystemXMLElement.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import java.util.HashMap;
import java.util.Map;
/**
* Enumeration of elements used in the Naming subsystem
*
* @author Stuart Douglas
*/
public enum NamingSubsystemXMLElement {
// must be first
UNKNOWN(null),
BINDINGS("bindings"),
REMOTE_NAMING("remote-naming"),
SIMPLE("simple"),
LOOKUP("lookup"),
OBJECT_FACTORY("object-factory"),
ENVIRONMENT(NamingSubsystemModel.ENVIRONMENT),
ENVIRONMENT_PROPERTY("property"),
EXTERNAL_CONTEXT("external-context"),
;
private final String name;
NamingSubsystemXMLElement(final String name) {
this.name = name;
}
/**
* Get the local name of this element.
*
* @return the local name
*/
public String getLocalName() {
return name;
}
private static final Map<String, NamingSubsystemXMLElement> MAP;
static {
final Map<String, NamingSubsystemXMLElement> map = new HashMap<String, NamingSubsystemXMLElement>();
for (NamingSubsystemXMLElement element : values()) {
final String name = element.getLocalName();
if (name != null) map.put(name, element);
}
MAP = map;
}
public static NamingSubsystemXMLElement forName(String localName) {
final NamingSubsystemXMLElement element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
}
| 2,448 | 29.234568 | 108 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingSubsystemRemove.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import org.jboss.as.controller.AbstractRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.dmr.ModelNode;
/**
* Handler for removing the Enterprise Beans 3 subsystem.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class NamingSubsystemRemove extends AbstractRemoveStepHandler {
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
// This subsystem registers DUPs, so we can't remove it from the runtime without a reload
context.reloadRequired();
}
@Override
protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
context.revertReloadRequired();
}
}
| 1,932 | 39.270833 | 132 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingSubsystemRootResourceDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import java.util.EnumSet;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleOperationDefinition;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.naming.NamingStore;
import org.jboss.as.naming.management.JndiViewOperation;
import org.jboss.as.naming.service.NamingService;
import org.jboss.dmr.ModelType;
/**
* {@link org.jboss.as.controller.ResourceDefinition} for the Naming subsystem's root management resource.
*
* @author Stuart Douglas
*/
public class NamingSubsystemRootResourceDefinition extends SimpleResourceDefinition {
enum Capability {
NAMING_STORE(NamingService.CAPABILITY_NAME, NamingStore.class),
;
private final RuntimeCapability<?> definition;
Capability(String name, Class<?> type) {
this.definition = RuntimeCapability.Builder.of(name, type).build();
}
RuntimeCapability<?> getDefinition() {
return this.definition;
}
}
static final SimpleOperationDefinition JNDI_VIEW = new SimpleOperationDefinitionBuilder(JndiViewOperation.OPERATION_NAME, NamingExtension.getResourceDescriptionResolver(NamingExtension.SUBSYSTEM_NAME))
.addAccessConstraint(NamingExtension.JNDI_VIEW_CONSTRAINT)
.setReadOnly()
.setRuntimeOnly()
.setReplyType(ModelType.LIST)
.setReplyValueType(ModelType.STRING)
.build();
NamingSubsystemRootResourceDefinition() {
super(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, NamingExtension.SUBSYSTEM_NAME),
NamingExtension.getResourceDescriptionResolver(NamingExtension.SUBSYSTEM_NAME),
new NamingSubsystemAdd(), new NamingSubsystemRemove());
}
@Override
public void registerCapabilities(ManagementResourceRegistration registration) {
super.registerCapabilities(registration);
for (Capability capability : EnumSet.allOf(Capability.class)) {
RuntimeCapability<?> definition = capability.getDefinition();
registration.registerCapability(definition);
}
}
}
| 3,477 | 40.404762 | 205 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/NamingExtension.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import org.jboss.as.controller.Extension;
import org.jboss.as.controller.ExtensionContext;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.ProcessType;
import org.jboss.as.controller.SubsystemRegistration;
import org.jboss.as.controller.access.constraint.ApplicationTypeConfig;
import org.jboss.as.controller.access.constraint.SensitivityClassification;
import org.jboss.as.controller.access.management.ApplicationTypeAccessConstraintDefinition;
import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
import org.jboss.as.controller.descriptions.ResourceDescriptionResolver;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.naming.management.JndiViewOperation;
/**
* Domain extension used to initialize the naming subsystem element handlers.
*
* @author John E. Bailey
* @author Emanuel Muckenhuber
*/
public class NamingExtension implements Extension {
public static final String SUBSYSTEM_NAME = "naming";
private static final String NAMESPACE_1_0 = "urn:jboss:domain:naming:1.0";
private static final String NAMESPACE_1_1 = "urn:jboss:domain:naming:1.1";
private static final String NAMESPACE_1_2 = "urn:jboss:domain:naming:1.2";
private static final String NAMESPACE_1_3 = "urn:jboss:domain:naming:1.3";
private static final String NAMESPACE_1_4 = "urn:jboss:domain:naming:1.4";
static final String NAMESPACE_2_0 = "urn:jboss:domain:naming:2.0";
//2.1 introduced in WildFly 10.1
private static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(2, 1, 0);
static final String RESOURCE_NAME = NamingExtension.class.getPackage().getName() + ".LocalDescriptions";
static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, NamingExtension.SUBSYSTEM_NAME);
static final SensitiveTargetAccessConstraintDefinition JNDI_VIEW_CONSTRAINT = new SensitiveTargetAccessConstraintDefinition(
new SensitivityClassification(SUBSYSTEM_NAME, "jndi-view", false, true, true));
static final SensitiveTargetAccessConstraintDefinition NAMING_BINDING_SENSITIVITY_CONSTRAINT = new SensitiveTargetAccessConstraintDefinition(
new SensitivityClassification(SUBSYSTEM_NAME, "naming-binding", false, false, false));
static final ApplicationTypeAccessConstraintDefinition NAMING_BINDING_APPLICATION_CONSTRAINT = new ApplicationTypeAccessConstraintDefinition(
new ApplicationTypeConfig(NamingExtension.SUBSYSTEM_NAME, NamingSubsystemModel.BINDING));
public static ResourceDescriptionResolver getResourceDescriptionResolver(final String keyPrefix) {
return new StandardResourceDescriptionResolver(keyPrefix, RESOURCE_NAME, NamingExtension.class.getClassLoader(), true, true);
}
/**
* {@inheritDoc}
*/
@Override
public void initialize(ExtensionContext context) {
final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new NamingSubsystemRootResourceDefinition());
registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
registration.registerSubModel(new NamingBindingResourceDefinition());
registration.registerSubModel(new RemoteNamingResourceDefinition());
if (context.isRuntimeOnlyRegistrationValid()) {
registration.registerOperationHandler(NamingSubsystemRootResourceDefinition.JNDI_VIEW, JndiViewOperation.INSTANCE, false);
}
subsystem.registerXMLElementWriter(NamingSubsystemXMLPersister.INSTANCE);
}
/**
* {@inheritDoc}
*/
@Override
public void initializeParsers(ExtensionParsingContext context) {
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, NAMESPACE_1_0, () -> new NamingSubsystem10Parser(context.getProcessType() == ProcessType.APPLICATION_CLIENT));
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, NAMESPACE_1_1, NamingSubsystem11Parser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, NAMESPACE_1_2, NamingSubsystem12Parser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, NAMESPACE_1_3, NamingSubsystem13Parser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, NAMESPACE_1_4, NamingSubsystem14Parser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, NAMESPACE_2_0, NamingSubsystem20Parser::new);
}
}
| 5,975 | 50.965217 | 165 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/subsystem/RemoteNamingAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.subsystem;
import static org.jboss.as.naming.subsystem.RemoteNamingResourceDefinition.REMOTING_ENDPOINT_CAPABILITY_NAME;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.naming.NamingStore;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.remote.RemoteNamingServerService;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.remoting3.Endpoint;
import org.wildfly.naming.client.remote.RemoteNamingService;
/**
* A {@link org.jboss.as.controller.AbstractAddStepHandler} to handle the add operation for simple JNDI bindings
*
* @author Stuart Douglas
*/
public class RemoteNamingAdd extends AbstractAddStepHandler {
static final RemoteNamingAdd INSTANCE = new RemoteNamingAdd();
private RemoteNamingAdd() {
}
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
installRuntimeServices(context);
}
void installRuntimeServices(final OperationContext context) {
final RemoteNamingServerService remoteNamingServerService = new RemoteNamingServerService();
final ServiceBuilder<RemoteNamingService> builder = context.getServiceTarget().addService(RemoteNamingServerService.SERVICE_NAME, remoteNamingServerService);
builder.addDependency(context.getCapabilityServiceName(REMOTING_ENDPOINT_CAPABILITY_NAME, Endpoint.class), Endpoint.class, remoteNamingServerService.getEndpointInjector())
.addDependency(ContextNames.EXPORTED_CONTEXT_SERVICE_NAME, NamingStore.class, remoteNamingServerService.getNamingStoreInjector())
.install();
}
@Override
protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException {
}
}
| 3,004 | 41.323944 | 179 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/util/NameParser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.util;
import javax.naming.CompositeName;
import javax.naming.Name;
import javax.naming.NamingException;
/**
* Name parser used by the NamingContext instances. Relies on composite name instances.
*
* @author John E. Bailey
*/
public class NameParser implements javax.naming.NameParser {
public static final NameParser INSTANCE = new NameParser();
private NameParser() {
}
/**
* Parse the string name into a {@code javax.naming.Name} instance.
*
* @param name The name to parse
* @return The parsed name.
* @throws NamingException
*/
public Name parse(String name) throws NamingException {
return new CompositeName(name);
}
}
| 1,748 | 32.634615 | 88 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/util/FastCopyHashMap.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.util;
import java.io.IOException;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.jboss.as.naming.logging.NamingLogger;
/**
* A HashMap that is optimized for fast shallow copies. If the copy-ctor is
* passed another FastCopyHashMap, or clone is called on this map, the shallow
* copy can be performed using little more than a single array copy. In order to
* accomplish this, immutable objects must be used internally, so update
* operations result in slightly more object churn than <code>HashMap</code>.
* <p/>
* Note: It is very important to use a smaller load factor than you normally
* would for HashMap, since the implementation is open-addressed with linear
* probing. With a 50% load-factor a get is expected to return in only 2 probes.
* However, a 90% load-factor is expected to return in around 50 probes.
*
* @author Jason T. Greene
*/
public class FastCopyHashMap<K, V> extends AbstractMap<K, V> implements Map<K, V>, Cloneable, Serializable {
/**
* Marks null keys.
*/
private static final Object NULL = new Object();
/**
* Serialization ID
*/
private static final long serialVersionUID = 10929568968762L;
/**
* Same default as HashMap, must be a power of 2
*/
private static final int DEFAULT_CAPACITY = 8;
/**
* MAX_INT - 1
*/
private static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 67%, just like IdentityHashMap
*/
private static final float DEFAULT_LOAD_FACTOR = 0.67f;
/**
* The open-addressed table
*/
private transient Entry<K, V>[] table;
/**
* The current number of key-value pairs
*/
private transient int size;
/**
* The next resize
*/
private transient int threshold;
/**
* The user defined load factor which defines when to resize
*/
private final float loadFactor;
/**
* Counter used to detect changes made outside of an iterator
*/
private transient int modCount;
// Cached views
private transient KeySet keySet;
private transient Values values;
private transient EntrySet entrySet;
public FastCopyHashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw NamingLogger.ROOT_LOGGER.invalidTableSize();
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (!(loadFactor > 0F && loadFactor <= 1F))
throw NamingLogger.ROOT_LOGGER.invalidLoadFactor();
this.loadFactor = loadFactor;
init(initialCapacity, loadFactor);
}
@SuppressWarnings("unchecked")
public FastCopyHashMap(Map<? extends K, ? extends V> map) {
if (map instanceof FastCopyHashMap) {
FastCopyHashMap<? extends K, ? extends V> fast = (FastCopyHashMap<? extends K, ? extends V>) map;
this.table = (Entry<K, V>[]) fast.table.clone();
this.loadFactor = fast.loadFactor;
this.size = fast.size;
this.threshold = fast.threshold;
} else {
this.loadFactor = DEFAULT_LOAD_FACTOR;
init(map.size(), this.loadFactor);
putAll(map);
}
}
@SuppressWarnings("unchecked")
private void init(int initialCapacity, float loadFactor) {
int c = 1;
while (c < initialCapacity) c <<= 1;
threshold = (int) (c * loadFactor);
// Include the load factor when sizing the table for the first time
if (initialCapacity > threshold && c < MAXIMUM_CAPACITY) {
c <<= 1;
threshold = (int) (c * loadFactor);
}
this.table = (Entry<K, V>[]) new Entry[c];
}
public FastCopyHashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public FastCopyHashMap() {
this(DEFAULT_CAPACITY);
}
// The normal bit spreader...
private static int hash(Object key) {
int h = key.hashCode();
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
@SuppressWarnings("unchecked")
private static <K> K maskNull(K key) {
return key == null ? (K) NULL : key;
}
private static <K> K unmaskNull(K key) {
return key == NULL ? null : key;
}
private int nextIndex(int index, int length) {
index = (index >= length - 1) ? 0 : index + 1;
return index;
}
private static boolean eq(Object o1, Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
private static int index(int hashCode, int length) {
return hashCode & (length - 1);
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public V get(Object key) {
key = maskNull(key);
int hash = hash(key);
int length = table.length;
int index = index(hash, length);
for (int start = index; ;) {
Entry<K, V> e = table[index];
if (e == null)
return null;
if (e.hash == hash && eq(key, e.key))
return e.value;
index = nextIndex(index, length);
if (index == start) // Full table
return null;
}
}
public boolean containsKey(Object key) {
key = maskNull(key);
int hash = hash(key);
int length = table.length;
int index = index(hash, length);
for (int start = index; ;) {
Entry<K, V> e = table[index];
if (e == null)
return false;
if (e.hash == hash && eq(key, e.key))
return true;
index = nextIndex(index, length);
if (index == start) // Full table
return false;
}
}
public boolean containsValue(Object value) {
for (Entry<K, V> e : table)
if (e != null && eq(value, e.value))
return true;
return false;
}
public V put(K key, V value) {
key = maskNull(key);
Entry<K, V>[] table = this.table;
int hash = hash(key);
int length = table.length;
int index = index(hash, length);
for (int start = index; ;) {
Entry<K, V> e = table[index];
if (e == null)
break;
if (e.hash == hash && eq(key, e.key)) {
table[index] = new Entry<K, V>(e.key, e.hash, value);
return e.value;
}
index = nextIndex(index, length);
if (index == start)
throw NamingLogger.ROOT_LOGGER.tableIsFull();
}
modCount++;
table[index] = new Entry<K, V>(key, hash, value);
if (++size >= threshold)
resize(length);
return null;
}
@SuppressWarnings("unchecked")
private void resize(int from) {
int newLength = from << 1;
// Can't get any bigger
if (newLength > MAXIMUM_CAPACITY || newLength <= from)
return;
Entry<K, V>[] newTable = new Entry[newLength];
Entry<K, V>[] old = table;
for (Entry<K, V> e : old) {
if (e == null)
continue;
int index = index(e.hash, newLength);
while (newTable[index] != null)
index = nextIndex(index, newLength);
newTable[index] = e;
}
threshold = (int) (loadFactor * newLength);
table = newTable;
}
public void putAll(Map<? extends K, ? extends V> map) {
int size = map.size();
if (size == 0)
return;
if (size > threshold) {
if (size > MAXIMUM_CAPACITY)
size = MAXIMUM_CAPACITY;
int length = table.length;
while (length < size) length <<= 1;
resize(length);
}
for (Map.Entry<? extends K, ? extends V> e : map.entrySet())
put(e.getKey(), e.getValue());
}
public V remove(Object key) {
key = maskNull(key);
Entry<K, V>[] table = this.table;
int length = table.length;
int hash = hash(key);
int start = index(hash, length);
for (int index = start; ;) {
Entry<K, V> e = table[index];
if (e == null)
return null;
if (e.hash == hash && eq(key, e.key)) {
table[index] = null;
relocate(index);
modCount++;
size--;
return e.value;
}
index = nextIndex(index, length);
if (index == start)
return null;
}
}
private void relocate(int start) {
Entry<K, V>[] table = this.table;
int length = table.length;
int current = nextIndex(start, length);
for (; ;) {
Entry<K, V> e = table[current];
if (e == null)
return;
// A Doug Lea variant of Knuth's Section 6.4 Algorithm R.
// This provides a non-recursive method of relocating
// entries to their optimal positions once a gap is created.
int prefer = index(e.hash, length);
if ((current < prefer && (prefer <= start || start <= current))
|| (prefer <= start && start <= current)) {
table[start] = e;
table[current] = null;
start = current;
}
current = nextIndex(current, length);
}
}
public void clear() {
modCount++;
Entry<K, V>[] table = this.table;
for (int i = 0; i < table.length; i++)
table[i] = null;
size = 0;
}
@SuppressWarnings("unchecked")
public FastCopyHashMap<K, V> clone() {
try {
FastCopyHashMap<K, V> clone = (FastCopyHashMap<K, V>) super.clone();
clone.table = table.clone();
clone.entrySet = null;
clone.values = null;
clone.keySet = null;
return clone;
}
catch (CloneNotSupportedException e) {
// should never happen
throw new IllegalStateException(e);
}
}
public void printDebugStats() {
int optimal = 0;
int total = 0;
int totalSkew = 0;
int maxSkew = 0;
for (int i = 0; i < table.length; i++) {
Entry<K, V> e = table[i];
if (e != null) {
total++;
int target = index(e.hash, table.length);
if (i == target)
optimal++;
else {
int skew = Math.abs(i - target);
if (skew > maxSkew) maxSkew = skew;
totalSkew += skew;
}
}
}
System.out.println(" Size: " + size);
System.out.println(" Real Size: " + total);
System.out.println(" Optimal: " + optimal + " (" + (float) optimal * 100 / total + "%)");
System.out.println(" Average Distnce: " + ((float) totalSkew / (total - optimal)));
System.out.println(" Max Distance: " + maxSkew);
}
public Set<Map.Entry<K, V>> entrySet() {
if (entrySet == null)
entrySet = new EntrySet();
return entrySet;
}
public Set<K> keySet() {
if (keySet == null)
keySet = new KeySet();
return keySet;
}
public Collection<V> values() {
if (values == null)
values = new Values();
return values;
}
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
int size = s.readInt();
init(size, loadFactor);
for (int i = 0; i < size; i++) {
K key = (K) s.readObject();
V value = (V) s.readObject();
putForCreate(key, value);
}
this.size = size;
}
@SuppressWarnings("unchecked")
private void putForCreate(K key, V value) {
key = maskNull(key);
Entry<K, V>[] table = this.table;
int hash = hash(key);
int length = table.length;
int index = index(hash, length);
Entry<K, V> e = table[index];
while (e != null) {
index = nextIndex(index, length);
e = table[index];
}
table[index] = new Entry<K, V>(key, hash, value);
}
private void writeObject(java.io.ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeInt(size);
for (Entry<K, V> e : table) {
if (e != null) {
s.writeObject(unmaskNull(e.key));
s.writeObject(e.value);
}
}
}
private static final class Entry<K, V> {
final K key;
final int hash;
final V value;
Entry(K key, int hash, V value) {
this.key = key;
this.hash = hash;
this.value = value;
}
}
private abstract class FasyCopyHashMapIterator<E> implements Iterator<E> {
private int next = 0;
private int expectedCount = modCount;
private int current = -1;
private boolean hasNext;
Entry<K, V>[] table = FastCopyHashMap.this.table;
public boolean hasNext() {
if (hasNext == true)
return true;
Entry<K, V>[] table = this.table;
for (int i = next; i < table.length; i++) {
if (table[i] != null) {
next = i;
return hasNext = true;
}
}
next = table.length;
return false;
}
protected Entry<K, V> nextEntry() {
if (modCount != expectedCount)
throw new ConcurrentModificationException();
if (!hasNext && !hasNext())
throw new NoSuchElementException();
current = next++;
hasNext = false;
return table[current];
}
@SuppressWarnings("unchecked")
public void remove() {
if (modCount != expectedCount)
throw new ConcurrentModificationException();
int current = this.current;
int delete = current;
if (current == -1)
throw new IllegalStateException();
// Invalidate current (prevents multiple remove)
this.current = -1;
// Start were we relocate
next = delete;
Entry<K, V>[] table = this.table;
if (table != FastCopyHashMap.this.table) {
FastCopyHashMap.this.remove(table[delete].key);
table[delete] = null;
expectedCount = modCount;
return;
}
int length = table.length;
int i = delete;
table[delete] = null;
size--;
for (; ;) {
i = nextIndex(i, length);
Entry<K, V> e = table[i];
if (e == null)
break;
int prefer = index(e.hash, length);
if ((i < prefer && (prefer <= delete || delete <= i))
|| (prefer <= delete && delete <= i)) {
// Snapshot the unseen portion of the table if we have
// to relocate an entry that was already seen by this iterator
if (i < current && current <= delete && table == FastCopyHashMap.this.table) {
int remaining = length - current;
Entry<K, V>[] newTable = (Entry<K, V>[]) new Entry[remaining];
System.arraycopy(table, current, newTable, 0, remaining);
// Replace iterator's table.
// Leave table local var pointing to the real table
this.table = newTable;
next = 0;
}
// Do the swap on the real table
table[delete] = e;
table[i] = null;
delete = i;
}
}
}
}
private class KeyIterator extends FasyCopyHashMapIterator<K> {
public K next() {
return unmaskNull(nextEntry().key);
}
}
private class ValueIterator extends FasyCopyHashMapIterator<V> {
public V next() {
return nextEntry().value;
}
}
private class EntryIterator extends FasyCopyHashMapIterator<Map.Entry<K, V>> {
private class WriteThroughEntry extends SimpleEntry<K, V> {
WriteThroughEntry(K key, V value) {
super(key, value);
}
public V setValue(V value) {
if (table != FastCopyHashMap.this.table)
FastCopyHashMap.this.put(getKey(), value);
return super.setValue(value);
}
}
public Map.Entry<K, V> next() {
Entry<K, V> e = nextEntry();
return new WriteThroughEntry(unmaskNull(e.key), e.value);
}
}
private class KeySet extends AbstractSet<K> {
public Iterator<K> iterator() {
return new KeyIterator();
}
public void clear() {
FastCopyHashMap.this.clear();
}
public boolean contains(Object o) {
return containsKey(o);
}
public boolean remove(Object o) {
int size = size();
FastCopyHashMap.this.remove(o);
return size() < size;
}
public int size() {
return FastCopyHashMap.this.size();
}
}
private class Values extends AbstractCollection<V> {
public Iterator<V> iterator() {
return new ValueIterator();
}
public void clear() {
FastCopyHashMap.this.clear();
}
public int size() {
return FastCopyHashMap.this.size();
}
}
private class EntrySet extends AbstractSet<Map.Entry<K, V>> {
public Iterator<Map.Entry<K, V>> iterator() {
return new EntryIterator();
}
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
Object value = get(entry.getKey());
return eq(entry.getValue(), value);
}
public void clear() {
FastCopyHashMap.this.clear();
}
public boolean isEmpty() {
return FastCopyHashMap.this.isEmpty();
}
public int size() {
return FastCopyHashMap.this.size();
}
}
protected static class SimpleEntry<K, V> implements Map.Entry<K, V> {
private K key;
private V value;
SimpleEntry(K key, V value) {
this.key = key;
this.value = value;
}
SimpleEntry(Map.Entry<K, V> entry) {
this.key = entry.getKey();
this.value = entry.getValue();
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
V old = this.value;
this.value = value;
return old;
}
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;
return eq(key, e.getKey()) && eq(value, e.getValue());
}
public int hashCode() {
return (key == null ? 0 : hash(key)) ^
(value == null ? 0 : hash(value));
}
public String toString() {
return getKey() + "=" + getValue();
}
}
}
| 21,511 | 27.305263 | 109 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/util/NamingUtils.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.util;
import javax.naming.CannotProceedException;
import javax.naming.Context;
import javax.naming.InvalidNameException;
import javax.naming.Name;
import javax.naming.NameAlreadyBoundException;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.NotContextException;
import org.jboss.as.naming.logging.NamingLogger;
import java.util.Collection;
import java.util.Iterator;
/**
* Common utility functions used by the naming implementation.
*
* @author John E. Bailey
*/
public class NamingUtils {
private NamingUtils() {}
/**
* Create a subcontext including any intermediate contexts.
* @param ctx the parent JNDI Context under which value will be bound
* @param name the name relative to ctx of the subcontext.
* @return The new or existing JNDI subcontext
* @throws NamingException on any JNDI failure
*/
private static Context createSubcontext(Context ctx, final Name name) throws NamingException {
Context subctx = ctx;
for (int pos = 0; pos < name.size(); pos++) {
final String ctxName = name.get(pos);
try {
subctx = (Context) ctx.lookup(ctxName);
}
catch (NameNotFoundException e) {
subctx = ctx.createSubcontext(ctxName);
}
// The current subctx will be the ctx for the next name component
ctx = subctx;
}
return subctx;
}
/**
* Get the last component of a name.
*
* @param name the name
* @return the last component
*/
public static String getLastComponent(final Name name) {
if(name.size() > 0)
return name.get(name.size() - 1);
return "";
}
/**
* Determine if a name is empty, or if ot contains only one component which is the empty string.
*
* @param name the name
* @return {@code true} if the name is empty or contains one empty component
*/
public static boolean isEmpty(final Name name) {
return name.isEmpty() || (name.size() == 1 && "".equals(name.get(0)));
}
/**
* Determine whether the last component is empty.
*
* @param name the name to test
* @return {@code true} if the last component is empty, or if the name is empty
*/
public static boolean isLastComponentEmpty(final Name name) {
return name.isEmpty() || getLastComponent(name).equals("");
}
/**
* Create a name-not-found exception.
*
* @param name the name
* @param contextName the context name
* @return the exception
*/
public static NameNotFoundException nameNotFoundException(final String name, final Name contextName) {
return NamingLogger.ROOT_LOGGER.nameNotFoundInContext(name, contextName);
}
/**
* Create a name-already-bound exception.
*
* @param name the name
* @return the exception
*/
public static NameAlreadyBoundException nameAlreadyBoundException(final Name name) {
return new NameAlreadyBoundException(name.toString());
}
/**
* Create an invalid name exception for an empty name.
*
* @return the exception
*/
public static InvalidNameException emptyNameException() {
return NamingLogger.ROOT_LOGGER.emptyNameNotAllowed();
}
/**
* Return a not-context exception for a name.
*
* @param name the name
* @return the exception
*/
public static NotContextException notAContextException(Name name) {
return new NotContextException(name.toString());
}
/**
* Return a general naming exception with a root cause.
*
* @param message the message
* @param cause the exception cause, or {@code null} for none
* @return the exception
*/
public static NamingException namingException(final String message, final Throwable cause) {
final NamingException exception = new NamingException(message);
if (cause != null) exception.initCause(cause);
return exception;
}
/**
* Return a general naming exception with a root cause and a remaining name field.
*
* @param message the message
* @param cause the exception cause, or {@code null} for none
* @param remainingName the remaining name
* @return the exception
*/
public static NamingException namingException(final String message, final Throwable cause, final Name remainingName) {
final NamingException exception = namingException(message, cause);
exception.setRemainingName(remainingName);
return exception;
}
/**
* Return a cannot-proceed exception.
*
* @param resolvedObject the resolved object
* @param remainingName the remaining name
* @return the exception
*/
public static CannotProceedException cannotProceedException(final Object resolvedObject, final Name remainingName) {
final CannotProceedException cpe = new CannotProceedException();
cpe.setResolvedObj(resolvedObject);
cpe.setRemainingName(remainingName);
return cpe;
}
/**
* Return a naming enumeration over a collection.
*
* @param collection the collection
* @param <T> the member type
* @return the enumeration
*/
public static <T> NamingEnumeration<T> namingEnumeration(final Collection<T> collection) {
final Iterator<T> iterator = collection.iterator();
return new NamingEnumeration<T>() {
public T next() {
return nextElement();
}
public boolean hasMore() {
return hasMoreElements();
}
public void close() {
}
public boolean hasMoreElements() {
return iterator.hasNext();
}
public T nextElement() {
return iterator.next();
}
};
}
/**
* Rebind val to name in ctx, and make sure that all intermediate contexts exist
*
* @param ctx the parent JNDI Context under which value will be bound
* @param name the name relative to ctx where value will be bound
* @param value the value to bind.
* @throws NamingException for any error
*/
public static void rebind(final Context ctx, final String name, final Object value) throws NamingException {
final Name n = ctx.getNameParser("").parse(name);
rebind(ctx, n, value);
}
/**
* Rebind val to name in ctx, and make sure that all intermediate contexts exist
*
* @param ctx the parent JNDI Context under which value will be bound
* @param name the name relative to ctx where value will be bound
* @param value the value to bind.
* @throws NamingException for any error
*/
public static void rebind(final Context ctx, final Name name, final Object value) throws NamingException {
final int size = name.size();
final String atom = name.get(size - 1);
final Context parentCtx = createSubcontext(ctx, name.getPrefix(size - 1));
parentCtx.rebind(atom, value);
}
/**
* Unbinds a name from ctx, and removes parents if they are empty
*
* @param ctx the parent JNDI Context under which the name will be unbound
* @param name The name to unbind
* @throws NamingException for any error
*/
public static void unbind(Context ctx, String name) throws NamingException {
unbind(ctx, ctx.getNameParser("").parse(name));
}
/**
* Unbinds a name from ctx, and removes parents if they are empty
*
* @param ctx the parent JNDI Context under which the name will be unbound
* @param name The name to unbind
* @throws NamingException for any error
*/
public static void unbind(Context ctx, Name name) throws NamingException {
ctx.unbind(name); //unbind the end node in the name
int sz = name.size();
// walk the tree backwards, stopping at the domain
while (--sz > 0) {
Name pname = name.getPrefix(sz);
try {
ctx.destroySubcontext(pname);
}
catch (NamingException e) {
//log.trace("Unable to remove context " + pname, e);
break;
}
}
}
}
| 9,482 | 33.358696 | 122 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/context/ObjectFactoryBuilder.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.context;
import java.security.AccessController;
import java.util.Hashtable;
import java.util.StringTokenizer;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import javax.naming.directory.Attributes;
import javax.naming.spi.DirObjectFactory;
import javax.naming.spi.ObjectFactory;
import org.jboss.as.naming.ServiceAwareObjectFactory;
import org.jboss.as.naming.logging.NamingLogger;
import org.jboss.as.server.CurrentServiceContainer;
import org.jboss.modules.Module;
import org.jboss.msc.service.ServiceContainer;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* ObjectFactoryBuilder implementation used to support custom object factories being loaded from modules. This class
* also provides the default object factory implementation.
*
* @author John Bailey
*/
public class ObjectFactoryBuilder implements javax.naming.spi.ObjectFactoryBuilder, DirObjectFactory {
public static final ObjectFactoryBuilder INSTANCE = new ObjectFactoryBuilder();
private ObjectFactoryBuilder() {
}
/**
* Create an object factory. If the object parameter is a reference it will attempt to create an {@link javax.naming.spi.ObjectFactory}
* from the reference. If the parameter is not a reference, or the reference does not create an {@link javax.naming.spi.ObjectFactory}
* it will return {@code this} as the {@link javax.naming.spi.ObjectFactory} to use.
*
* @param obj The object bound in the naming context
* @param environment The environment information
* @return The object factory the object resolves to
* @throws NamingException If any problems occur
*/
public ObjectFactory createObjectFactory(final Object obj, Hashtable<?, ?> environment) throws NamingException {
try {
if (obj instanceof Reference) {
return factoryFromReference((Reference) obj, environment);
}
} catch (Throwable ignored) {
}
return this;
}
/**
* Create an object instance.
*
* @param ref Object containing reference information
* @param name The name relative to nameCtx
* @param nameCtx The naming context
* @param environment The environment information
* @return The object
* @throws Exception If any error occur
*/
public Object getObjectInstance(final Object ref, final Name name, final Context nameCtx, final Hashtable<?, ?> environment) throws Exception {
final ClassLoader classLoader = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
if (classLoader == null) {
return ref;
}
final String factoriesProp = (String) environment.get(Context.OBJECT_FACTORIES);
if (factoriesProp != null) {
final String[] classes = factoriesProp.split(":");
for (String className : classes) {
try {
final Class<?> factoryClass = classLoader.loadClass(className);
final ObjectFactory objectFactory = ObjectFactory.class.cast(factoryClass.newInstance());
final Object result = objectFactory.getObjectInstance(ref, name, nameCtx, environment);
if (result != null) {
return result;
}
} catch (Throwable ignored) {
}
}
}
return ref;
}
/**
* Create an object instance.
*
* @param ref Object containing reference information
* @param name The name relative to nameCtx
* @param nameCtx The naming context
* @param environment The environment information
* @param attributes The directory attributes
* @return The object
* @throws Exception If any error occur
*/
public Object getObjectInstance(final Object ref, final Name name, final Context nameCtx, final Hashtable<?, ?> environment, final Attributes attributes) throws Exception {
final ClassLoader classLoader = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
if (classLoader == null) {
return ref;
}
final String factoriesProp = (String) environment.get(Context.OBJECT_FACTORIES);
if (factoriesProp != null) {
final String[] classes = factoriesProp.split(":");
for (String className : classes) {
try {
final Class<?> factoryClass = classLoader.loadClass(className);
final ObjectFactory objectFactory = ObjectFactory.class.cast(factoryClass.newInstance());
final Object result;
if (objectFactory instanceof DirObjectFactory) {
result = DirObjectFactory.class.cast(objectFactory).getObjectInstance(ref, name, nameCtx, environment, attributes);
} else {
result = objectFactory.getObjectInstance(ref, name, nameCtx, environment);
}
if (result != null) {
return result;
}
} catch (Throwable ignored) {
}
}
}
return ref;
}
private ObjectFactory factoryFromReference(final Reference reference, final Hashtable<?, ?> environment) throws Exception {
if (reference.getFactoryClassName() == null) {
return lookForURLs(reference, environment);
}
if (reference instanceof ModularReference) {
return factoryFromModularReference(ModularReference.class.cast(reference), environment);
}
return factoryFromReference(reference, WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(), environment);
}
private ObjectFactory factoryFromModularReference(ModularReference modularReference, final Hashtable<?, ?> environment) throws Exception {
final Module module = Module.getCallerModuleLoader().loadModule(modularReference.getModuleIdentifier());
final ClassLoader classLoader = module.getClassLoader();
return factoryFromReference(modularReference, classLoader, environment);
}
private ObjectFactory factoryFromReference(final Reference reference, final ClassLoader classLoader, final Hashtable<?, ?> environment) throws Exception {
try {
final Class<?> factoryClass = classLoader.loadClass(reference.getFactoryClassName());
ObjectFactory factory = ObjectFactory.class.cast(factoryClass.newInstance());
if (factory instanceof ServiceAwareObjectFactory) {
((ServiceAwareObjectFactory) factory).injectServiceRegistry(currentServiceContainer());
}
return factory;
} catch (Throwable t) {
throw NamingLogger.ROOT_LOGGER.objectFactoryCreationFailure(t);
}
}
static ObjectFactory lookForURLs(Reference ref, Hashtable environment)
throws NamingException {
for (int i = 0; i < ref.size(); i++) {
RefAddr addr = ref.get(i);
if (addr instanceof StringRefAddr &&
addr.getType().equalsIgnoreCase("URL")) {
String url = (String) addr.getContent();
ObjectFactory answer = processURL(url, environment);
if (answer != null) {
return answer;
}
}
}
return null;
}
private static ObjectFactory processURL(Object refInfo, Hashtable environment) throws NamingException {
if (refInfo instanceof String) {
String url = (String) refInfo;
String scheme = getURLScheme(url);
if (scheme != null) {
ObjectFactory answer = getURLObjectFactory(scheme, url, environment);
if (answer != null) {
return answer;
}
}
}
if (refInfo instanceof String[]) {
String[] urls = (String[]) refInfo;
for (int i = 0; i < urls.length; i++) {
String scheme = getURLScheme(urls[i]);
if (scheme != null) {
ObjectFactory answer = getURLObjectFactory(scheme, urls[i], environment);
if (answer != null) {
return answer;
}
}
}
}
return null;
}
private static ObjectFactory getURLObjectFactory(String scheme, String url, Hashtable environment) throws NamingException {
String facProp = (String) environment.get(Context.URL_PKG_PREFIXES);
if (facProp != null) {
facProp += ":" + "com.sun.jndi.url";
} else {
facProp = "com.sun.jndi.url";
}
ClassLoader loader = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
String suffix = "." + scheme + "." + scheme + "URLContextFactory";
// Not cached; find first factory and cache
StringTokenizer parser = new StringTokenizer(facProp, ":");
String className;
ObjectFactory factory = null;
while (parser.hasMoreTokens()) {
className = parser.nextToken() + suffix;
try {
Class<?> clazz;
if (loader == null) {
clazz = Class.forName(className);
} else {
clazz = Class.forName(className, true, loader);
}
return new ReferenceUrlContextFactoryWrapper((ObjectFactory) clazz.newInstance(), url);
} catch (InstantiationException | IllegalAccessException e) {
NamingException ne = new NamingException(className);
ne.setRootCause(e);
throw ne;
} catch (Exception e) {
}
}
return factory;
}
private static String getURLScheme(String str) {
int colon = str.indexOf(':');
int slash = str.indexOf('/');
if (colon > 0 && (slash == -1 || colon + 1 == slash))
return str.substring(0, colon);
return null;
}
private static ServiceContainer currentServiceContainer() {
if(System.getSecurityManager() == null) {
return CurrentServiceContainer.getServiceContainer();
}
return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION);
}
private static final class ReferenceUrlContextFactoryWrapper implements ObjectFactory {
private final ObjectFactory factory;
private final String url;
private ReferenceUrlContextFactoryWrapper(final ObjectFactory factory, final String url) {
this.factory = factory;
this.url = url;
}
@Override
public Object getObjectInstance(final Object obj, final Name name, final Context nameCtx, final Hashtable<?, ?> environment) throws Exception {
return factory.getObjectInstance(url, name, nameCtx, environment);
}
}
}
| 12,270 | 40.316498 | 176 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/context/ModularReference.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.context;
import javax.naming.RefAddr;
import javax.naming.Reference;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
/**
* Reference implementation that captures a module name and allows object factories to be loaded and created from
* modules.
*
* @author John Bailey
*/
public class ModularReference extends Reference {
private static final long serialVersionUID = -4805781394834948096L;
private final ModuleIdentifier moduleIdentifier;
/**
* Create a ModuleReference from a target type and factory class.
*
* @param type The class type for the reference
* @param factoryClass The factory class
* @return A ModularReference
*/
public static ModularReference create(final Class<?> type, final Class<?> factoryClass) {
return create(type.getName(), factoryClass);
}
/**
* Create a ModuleReference from a target class name and factory class.
*
* @param className The class name for the reference
* @param factoryClass The factory class
* @return A ModularReference
*/
public static ModularReference create(final String className, final Class<?> factoryClass) {
return new ModularReference(className, factoryClass.getName(), Module.forClass(factoryClass).getIdentifier());
}
/**
* Create a ModuleReference from a target type, reference address and factory class.
*
* @param type The class type for the reference
* @param addr The address of the object
* @param factoryClass The factory class
* @return A ModularReference
*/
public static ModularReference create(final Class<?> type, final RefAddr addr, final Class<?> factoryClass) {
return create(type.getName(), addr, factoryClass);
}
/**
* Create a ModuleReference from a target class name, reference address and factory class.
*
* @param className The class name for the reference
* @param addr The address of the object
* @param factoryClass The factory class
* @return A ModularReference
*/
public static ModularReference create(final String className, final RefAddr addr, final Class<?> factoryClass) {
return new ModularReference(className, addr, factoryClass.getName(), Module.forClass(factoryClass).getIdentifier());
}
/**
* Create an instance.
*
* @param className The class name of the target object type
* @param factory The object factory class name
* @param moduleIdentifier The module name to load the factory class
*/
public ModularReference(final String className, final String factory, final ModuleIdentifier moduleIdentifier) {
super(className, factory, null);
this.moduleIdentifier = moduleIdentifier;
}
/**
* Create an instance.
*
* @param className The class name of the target object type
* @param addr The address of the object
* @param factory The object factory class name
* @param moduleIdentifier The module name to load the factory class
*/
public ModularReference(final String className, final RefAddr addr, final String factory, final ModuleIdentifier moduleIdentifier) {
super(className, addr, factory, null);
this.moduleIdentifier = moduleIdentifier;
}
/**
* Get the module name to load the factory class from.
*
* @return The module name
*/
public ModuleIdentifier getModuleIdentifier() {
return moduleIdentifier;
}
}
| 4,575 | 36.818182 | 136 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/context/NamespaceContextSelector.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.context;
import javax.naming.Context;
import org.wildfly.common.function.ThreadLocalStack;
/**
* Selects a naming context based on the provided identifier (eg. comp). Maintains a thread local used to managed the current selector.
* The current selector will be used by instances of {@code org.jboss.as.naming.contexts.NamespaceObjectFactory} to determine
* which context to return.
*
* @author John E. Bailey
*/
public abstract class NamespaceContextSelector {
/* Thread local maintaining the current context selector */
private static ThreadLocalStack<NamespaceContextSelector> currentSelector = new ThreadLocalStack<NamespaceContextSelector>();
private static NamespaceContextSelector defaultSelector;
/**
* Set the current context selector for the current thread.
*
* @param selector The current selector
*/
public static void pushCurrentSelector(final NamespaceContextSelector selector) {
currentSelector.push(selector);
}
/**
* Pops the current selector for the thread, replacing it with the previous selector
*
* @return selector The current selector
*/
public static NamespaceContextSelector popCurrentSelector() {
return currentSelector.pop();
}
/**
* Get the current context selector for the current thread.
*
* @return The current context selector.
*/
public static NamespaceContextSelector getCurrentSelector() {
NamespaceContextSelector selector = currentSelector.peek();
if(selector != null) {
return selector;
}
return defaultSelector;
}
/**
* Get the context for a given identifier (eg. comp -> java:comp). Implementers of this method can use any means to
* determine which context to return.
*
* @param identifier The context identifier
* @return The context for this identifier
*/
public abstract Context getContext(final String identifier);
public static void setDefault(NamespaceContextSelector selector) {
defaultSelector = selector;
}
}
| 3,149 | 35.627907 | 136 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/context/external/ExternalContexts.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.context.external;
import org.jboss.msc.service.ServiceName;
/**
* The external contexts which exist in Wildfly's Naming subsystem.
* @author Eduardo Martins
*/
public interface ExternalContexts {
/**
* Adds an external context.
* @param serviceName the external context's service name
* @throws IllegalArgumentException if there is already an external context with such service name, or if there is already an external context which is a child or parent of the one to add
*/
void addExternalContext(ServiceName serviceName) throws IllegalArgumentException;
/**
* Removes an external context.
* @param serviceName the external context's service name
* @return true if an external context with the specified jndi name was found and removed.
*/
boolean removeExternalContext(ServiceName serviceName);
/**
* Retrieves the external context that is a parent of the specified child service name.
* @param childServiceName a external context's child service name
* @return null if there is currently no external context, which is a parent of the specified service name.
*/
ServiceName getParentExternalContext(ServiceName childServiceName);
}
| 2,278 | 42 | 191 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/context/external/ExternalContextsNavigableSet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.context.external;
import org.jboss.msc.service.ServiceName;
import java.util.concurrent.ConcurrentSkipListSet;
/**
* An {@link ExternalContexts} implementation using a {@link java.util.NavigableSet} to store the service names of the existent external contexts.
* @author Eduardo Martins
*/
public class ExternalContextsNavigableSet implements ExternalContexts {
/**
*
*/
private final ConcurrentSkipListSet<ServiceName> externalContexts;
/**
*
*/
public ExternalContextsNavigableSet() {
externalContexts = new ConcurrentSkipListSet<>();
}
@Override
public void addExternalContext(ServiceName serviceName) {
externalContexts.add(serviceName);
}
@Override
public boolean removeExternalContext(ServiceName serviceName) {
return externalContexts.remove(serviceName);
}
@Override
public ServiceName getParentExternalContext(ServiceName serviceName) {
final ServiceName lower = externalContexts.lower(serviceName);
return lower != null && lower.isParentOf(serviceName) ? lower : null;
}
}
| 2,161 | 33.870968 | 146 |
java
|
null |
wildfly-main/naming/src/main/java/org/jboss/as/naming/interfaces/java/javaURLContextFactory.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming.interfaces.java;
import org.jboss.as.naming.NamingContext;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.spi.ObjectFactory;
import java.util.Hashtable;
/**
* Implementation of {@code ObjectFactory} used to create a {@code NamingContext} instances to support the java: namespace.
*
* @author John E. Bailey
*/
public class javaURLContextFactory implements ObjectFactory {
/** {@inheritDoc} */
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
return new NamingContext(name != null ? name : new CompositeName(""), environment);
}
}
| 1,744 | 37.777778 | 123 |
java
|
null |
wildfly-main/naming/src/main/java/org/wildfly/naming/java/permission/JndiPermissionNameParser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.naming.java.permission;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.jboss.as.naming.logging.NamingLogger;
import org.wildfly.common.iteration.CodePointIterator;
final class JndiPermissionNameParser {
private JndiPermissionNameParser() {
}
static Iterator<String> nameIterator(final String string) {
return new ParsingIterator(string);
}
static Iterator<String> segmentsIterator(String[] segments) {
return new SegmentsIterator(segments);
}
static String[] toArray(Iterator<String> iter) {
return toArray(iter, 0);
}
private static String[] toArray(final Iterator<String> iter, final int size) {
if (iter.hasNext()) {
String next = iter.next();
String[] array = toArray(iter, size + 1);
array[size] = next;
return array;
} else {
return new String[size];
}
}
static class SegmentsIterator implements Iterator<String> {
private final String[] segments;
private int idx;
SegmentsIterator(final String[] segments) {
this.segments = segments;
}
public boolean hasNext() {
return idx < segments.length;
}
public String next() {
return segments[idx ++];
}
String[] getSegments() {
return segments;
}
}
static class ParsingIterator implements Iterator<String> {
private final CodePointIterator cpi;
private final StringBuilder b;
private final String string;
private boolean hasNext = true;
ParsingIterator(final String string) {
this.string = string;
cpi = CodePointIterator.ofString(string);
b = new StringBuilder();
}
public boolean hasNext() {
return hasNext;
}
public String next() {
if (! hasNext()) throw new NoSuchElementException();
final StringBuilder b = this.b;
final CodePointIterator cpi = this.cpi;
int cp;
while (cpi.hasNext()) {
cp = cpi.next();
if (cp == '\\') {
// skip the next code point always
if (! cpi.hasNext()) {
throw NamingLogger.ROOT_LOGGER.invalidJndiName(string);
}
b.appendCodePoint(cpi.next());
} else if (cp == '"' || cp == '\'') {
int q = cp;
if (! cpi.hasNext()) {
throw NamingLogger.ROOT_LOGGER.invalidJndiName(string);
}
for (;;) {
cp = cpi.next();
if (cp == '\\') {
// skip the next code point always
if (! cpi.hasNext()) {
throw NamingLogger.ROOT_LOGGER.invalidJndiName(string);
}
b.appendCodePoint(cpi.next());
} else if (cp == q) {
break;
} else {
b.appendCodePoint(cp);
}
if (! cpi.hasNext()) {
throw NamingLogger.ROOT_LOGGER.invalidJndiName(string);
}
}
} else if (cp == '/') {
final String s = b.toString();
b.setLength(0);
return s;
} else {
b.appendCodePoint(cp);
}
}
final String s = b.toString();
b.setLength(0);
hasNext = false;
return s;
}
}
}
| 4,922 | 32.951724 | 87 |
java
|
null |
wildfly-main/naming/src/main/java/org/wildfly/naming/java/permission/JndiPermissionCollection.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.naming.java.permission;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.concurrent.atomic.AtomicReference;
import org.jboss.as.naming.logging.NamingLogger;
import org.wildfly.common.Assert;
final class JndiPermissionCollection extends PermissionCollection {
private static final long serialVersionUID = - 769684900128311150L;
private static final JndiPermission[] NO_PERMISSIONS = new JndiPermission[0];
private final AtomicReference<JndiPermission[]> permissions;
JndiPermissionCollection() {
permissions = new AtomicReference<>(NO_PERMISSIONS);
}
JndiPermissionCollection(JndiPermission[] permissions) {
Assert.checkNotNullParam("permissions", permissions);
this.permissions = new AtomicReference<>(permissions);
}
public void add(final Permission permission) {
if (isReadOnly()) {
throw NamingLogger.ROOT_LOGGER.cannotAddToReadOnlyPermissionCollection();
}
if (! (permission instanceof JndiPermission)) {
throw NamingLogger.ROOT_LOGGER.invalidPermission(permission);
}
final AtomicReference<JndiPermission[]> permissions = this.permissions;
JndiPermission jndiPermission = (JndiPermission) permission;
if (jndiPermission.getActionBits() == 0) {
// no operation
return;
}
JndiPermission[] oldVal;
ArrayList<JndiPermission> newVal;
boolean added = false;
do {
oldVal = permissions.get();
newVal = new ArrayList<>(oldVal.length + 1);
// first, test if it's in the set, or combine with any other permission with the same actions
for (final JndiPermission testPerm : oldVal) {
if (testPerm.implies(jndiPermission)) {
// already in the set
return;
} else if (jndiPermission.implies(testPerm)) {
// otherwise skip all other matches
} else if (jndiPermission.getName().equals(testPerm.getName())) {
// the two .implies() would have caught this condition
assert jndiPermission.getActionBits() != testPerm.getActionBits();
jndiPermission = jndiPermission.withActions(testPerm.getActionBits());
// and skip it
}
}
for (final JndiPermission testPerm : oldVal) {
if (! jndiPermission.implies(testPerm)) {
newVal.add(testPerm);
}
}
newVal.add(jndiPermission);
} while (! permissions.compareAndSet(oldVal, newVal.toArray(NO_PERMISSIONS)));
}
public boolean implies(final Permission permission) {
final JndiPermission[] jndiPermissions = permissions.get();
for (JndiPermission jndiPermission : jndiPermissions) {
if (jndiPermission.implies(permission)) {
return true;
}
}
return false;
}
public Enumeration<Permission> elements() {
final JndiPermission[] jndiPermissions = permissions.get();
return new Enumeration<Permission>() {
int i;
public boolean hasMoreElements() {
return i < jndiPermissions.length;
}
public Permission nextElement() {
return jndiPermissions[i++];
}
};
}
Object writeReplace() {
return new SerializedJndiPermissionCollection(isReadOnly(), permissions.get());
}
}
| 4,718 | 38.325 | 105 |
java
|
null |
wildfly-main/naming/src/main/java/org/wildfly/naming/java/permission/SerializedJndiPermissionCollection.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.naming.java.permission;
import java.io.Serializable;
class SerializedJndiPermissionCollection implements Serializable {
private static final long serialVersionUID = 315106751231586701L;
private final boolean readOnly;
private final JndiPermission[] permissions;
SerializedJndiPermissionCollection(final boolean readOnly, final JndiPermission[] permissions) {
this.readOnly = readOnly;
this.permissions = permissions;
}
Object readResolve() {
final JndiPermissionCollection collection = new JndiPermissionCollection(permissions);
if (readOnly) collection.setReadOnly();
return collection;
}
}
| 1,710 | 37.022222 | 100 |
java
|
null |
wildfly-main/naming/src/main/java/org/wildfly/naming/java/permission/JndiPermission.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.naming.java.permission;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.Iterator;
import org.jboss.as.naming.logging.NamingLogger;
import org.wildfly.common.Assert;
/**
* Permission to access an object within the "java:" JNDI namespace.
* <p>
* This permission does not span into bound nested contexts; such contexts may be governed by their own permission scheme.
* <p>
* The {@code name} segment of the permission is a JNDI path whose segments are separated by {@code /} characters. The
* name may be preceded with the string {@code java:} for compatibility with previous schemes. A name of
* {@code <<ALL BINDINGS>>} is translated to {@code -} for compatibility reasons.
*/
public final class JndiPermission extends Permission {
private static final long serialVersionUID = 1272655825146515997L;
private final int actionBits;
private String actionString;
/**
* The bitwise encoding of the {@code bind} action.
*/
public static final int ACTION_BIND = 0b000000001;
/**
* The bitwise encoding of the {@code rebind} action.
*/
public static final int ACTION_REBIND = 0b000000010;
/**
* The bitwise encoding of the {@code unbind} action.
*/
public static final int ACTION_UNBIND = 0b000000100;
/**
* The bitwise encoding of the {@code lookup} action.
*/
public static final int ACTION_LOOKUP = 0b000001000;
/**
* The bitwise encoding of the {@code list} action.
*/
public static final int ACTION_LIST = 0b000010000;
/**
* The bitwise encoding of the {@code listBindings} action.
*/
public static final int ACTION_LIST_BINDINGS = 0b000100000;
/**
* The bitwise encoding of the {@code createSubcontext} action.
*/
public static final int ACTION_CREATE_SUBCONTEXT = 0b001000000;
/**
* The bitwise encoding of the {@code destroySubcontext} action.
*/
public static final int ACTION_DESTROY_SUBCONTEXT = 0b010000000;
/**
* The bitwise encoding of the {@code addNamingListener} action.
*/
public static final int ACTION_ADD_NAMING_LISTENER = 0b100000000;
/**
* The bitwise encoding of the {@code *} action. This value is the bitwise-OR of all of the other action bits.
*/
public static final int ACTION_ALL = 0b111111111;
/**
* Construct a new instance.
*
* @param name the path name (must not be {@code null})
* @param actions the actions (must not be {@code null})
*/
public JndiPermission(final String name, final String actions) {
this(name, parseActions(Assert.checkNotNullParam("actions", actions)));
}
/**
* Construct a new instance using an action bitmask. If a bit in the mask falls outside of {@link #ACTION_ALL}, it
* is stripped.
*
* @param name the path name (must not be {@code null})
* @param actionBits the action bits
*/
public JndiPermission(final String name, final int actionBits) {
super(canonicalize1(Assert.checkNotNullParam("name", name)));
this.actionBits = actionBits & ACTION_ALL;
}
/**
* Determine if this permission implies the other permission.
*
* @param permission the other permission
* @return {@code true} if this permission implies the other, {@code false} if it does not or {@code permission} is {@code null}
*/
public boolean implies(final Permission permission) {
return permission instanceof JndiPermission && implies((JndiPermission) permission);
}
/**
* Determine if this permission implies the other permission.
*
* @param permission the other permission
* @return {@code true} if this permission implies the other, {@code false} if it does not or {@code permission} is {@code null}
*/
public boolean implies(final JndiPermission permission) {
return permission != null && ((actionBits & permission.actionBits) == permission.actionBits) && impliesPath(permission.getName());
}
/**
* Determine if this permission implies the given {@code actions} on the given {@code name}.
*
* @param name the name (must not be {@code null})
* @param actions the actions (must not be {@code null})
* @return {@code true} if this permission implies the {@code actions} on the {@code name}, {@code false} otherwise
*/
public boolean implies(final String name, final String actions) {
return implies(name, parseActions(actions));
}
/**
* Determine if this permission implies the given {@code actionsBits} on the given {@code name}.
*
* @param name the name (must not be {@code null})
* @param actionBits the action bits
* @return {@code true} if this permission implies the {@code actionBits} on the {@code name}, {@code false} otherwise
*/
public boolean implies(final String name, final int actionBits) {
Assert.checkNotNullParam("name", name);
final int maskedBits = actionBits & ACTION_ALL;
return (this.actionBits & maskedBits) == maskedBits && impliesPath(name);
}
/**
* Determine whether this object is equal to another.
*
* @param other the other object
* @return {@code true} if they are equal, {@code false} otherwise
*/
public boolean equals(Object other) {
return other instanceof JndiPermission && equals((JndiPermission)other);
}
/**
* Determine whether this object is equal to another.
*
* @param other the other object
* @return {@code true} if they are equal, {@code false} otherwise
*/
public boolean equals(JndiPermission other) {
return this == other || other != null && getName().equals(other.getName()) && actionBits == other.actionBits;
}
/**
* Get the hash code of this permission.
*
* @return the hash code of this permission
*/
public int hashCode() {
return actionBits * 23 + getName().hashCode();
}
/**
* Get the actions string. The actions string will be a canonical version of the one passed in at construction.
*
* @return the actions string (not {@code null})
*/
public String getActions() {
final String actionString = this.actionString;
if (actionString != null) {
return actionString;
}
int actionBits = this.actionBits;
if (actionBits == ACTION_ALL) {
return this.actionString = "*";
}
int m = Integer.lowestOneBit(actionBits);
if (m != 0) {
StringBuilder b = new StringBuilder();
b.append(getAction(m));
actionBits &= ~m;
while (actionBits != 0) {
m = Integer.lowestOneBit(actionBits);
b.append(',').append(getAction(m));
actionBits &= ~m;
}
return this.actionString = b.toString();
} else {
return this.actionString = "";
}
}
/**
* Get the action bits.
*
* @return the action bits
*/
public int getActionBits() {
return actionBits;
}
/**
* Return a permission which is equal to this one except with its actions reset to {@code actionBits}. If the given
* {@code actionBits} equals the current bits of this permission, then this permission instance is returned; otherwise
* a new permission is constructed. Any action bits which fall outside of {@link #ACTION_ALL} are silently ignored.
*
* @param actionBits the action bits to use
* @return a permission with only the given action bits (not {@code null})
*/
public JndiPermission withNewActions(int actionBits) {
actionBits &= ACTION_ALL;
if (actionBits == this.actionBits) {
return this;
} else {
return new JndiPermission(getName(), actionBits);
}
}
/**
* Return a permission which is equal to this one except with its actions reset to {@code actions}. If the given
* {@code actions} equals the current actions of this permission, then this permission instance is returned; otherwise
* a new permission is constructed.
*
* @param actions the actions to use (must not be {@code null})
* @return a permission with only the given action bits (not {@code null})
*/
public JndiPermission withNewActions(String actions) {
return withNewActions(parseActions(Assert.checkNotNullParam("actions", actions)));
}
/**
* Return a permission which is equal to this one except with additional action bits. If the given {@code actionBits}
* do not add any new actions, then this permission instance is returned; otherwise a new permission is constructed.
* Any action bits which fall outside of {@link #ACTION_ALL} are silently ignored.
*
* @param actionBits the action bits to add
* @return a permission with the union of permissions from this instance and the given bits (not {@code null})
*/
public JndiPermission withActions(int actionBits) {
return withNewActions(actionBits & ACTION_ALL | this.actionBits);
}
/**
* Return a permission which is equal to this one except with additional actions. If the given {@code actionBits}
* do not add any new actions, then this permission instance is returned; otherwise a new permission is constructed.
*
* @param actions the actions to add (must not be {@code null})
* @return a permission with the union of permissions from this instance and the given bits (not {@code null})
*/
public JndiPermission withActions(String actions) {
return withActions(parseActions(Assert.checkNotNullParam("actions", actions)));
}
/**
* Return a permission which is equal to this one except without some action bits. If the given {@code actionBits}
* do not remove any actions, then this permission instance is returned; otherwise a new permission is constructed.
* Any action bits which fall outside of {@link #ACTION_ALL} are silently ignored.
*
* @param actionBits the action bits to remove
* @return a permission with the given bits subtracted from this instance (not {@code null})
*/
public JndiPermission withoutActions(int actionBits) {
return withNewActions(this.actionBits & ~(actionBits & ACTION_ALL));
}
/**
* Return a permission which is equal to this one except without some actions. If the given {@code actions}
* do not remove any actions, then this permission instance is returned; otherwise a new permission is constructed.
*
* @param actions the actions to remove (must not be {@code null})
* @return a permission with the given bits subtracted from this instance (not {@code null})
*/
public JndiPermission withoutActions(String actions) {
return withoutActions(parseActions(Assert.checkNotNullParam("actions", actions)));
}
/**
* Construct a new type-specific permission collection.
*
* @return the new permission collection instance (not {@code null})
*/
public PermissionCollection newPermissionCollection() {
return new JndiPermissionCollection();
}
// semi-private
Object writeReplace() {
return new SerializedJndiPermission(getName(), getActions());
}
boolean impliesPath(final String yourName) {
return yourName.startsWith("java:") ? impliesPath0(yourName.substring(5)) : impliesPath0(yourName);
}
// private
private boolean impliesPath0(final String yourName) {
// segment-by-segment comparison
final String myName = getName();
final Iterator<String> myIter = JndiPermissionNameParser.nameIterator(myName);
final Iterator<String> yourIter = JndiPermissionNameParser.nameIterator(yourName);
// even if it's just "", there is always a first element
assert myIter.hasNext() && yourIter.hasNext();
String myNext;
String yourNext;
for (;;) {
myNext = myIter.next();
yourNext = yourIter.next();
if (myNext.equals("-")) {
// "-" implies everything including ""
return true;
}
if (! myNext.equals("*") && ! myNext.equals(yourNext)) {
// "foo/bar" does not imply "foo/baz"
return false;
}
if (myIter.hasNext()) {
if (! yourIter.hasNext()) {
// "foo/bar" does not imply "foo"
return false;
}
} else {
// if neither has next, "foo/bar" implies "foo/bar", else "foo" does not imply "foo/bar"
return ! yourIter.hasNext();
}
}
}
private static String canonicalize1(String name) {
Assert.checkNotNullParam("name", name);
return name.equalsIgnoreCase("<<ALL BINDINGS>>") ? "-" : canonicalize2(name);
}
private static String canonicalize2(String name) {
return name.startsWith("java:") ? name.substring(5) : name;
}
private static int parseActions(final String actionsString) {
// TODO: switch to Elytron utility methods to do this
int actions = 0;
int pos = 0;
int idx = actionsString.indexOf(',');
for (;;) {
String str;
if (idx == -1) {
str = actionsString.substring(pos).trim();
if (! str.isEmpty()) actions |= parseAction(str);
return actions;
} else {
str = actionsString.substring(pos, idx).trim();
pos = idx + 1;
if (! str.isEmpty()) actions |= parseAction(str);
idx = actionsString.indexOf(',', pos);
}
}
}
private static int parseAction(final String str) {
switch (str) {
case "*":
case "all": return ACTION_ALL;
case "bind": return ACTION_BIND;
case "rebind": return ACTION_REBIND;
case "unbind": return ACTION_UNBIND;
case "lookup": return ACTION_LOOKUP;
case "list": return ACTION_LIST;
case "listBindings": return ACTION_LIST_BINDINGS;
case "createSubcontext": return ACTION_CREATE_SUBCONTEXT;
case "destroySubcontext": return ACTION_DESTROY_SUBCONTEXT;
case "addNamingListener": return ACTION_ADD_NAMING_LISTENER;
default: {
throw NamingLogger.ROOT_LOGGER.invalidPermissionAction(str);
}
}
}
private String getAction(final int bit) {
switch (bit) {
case ACTION_BIND: return "bind";
case ACTION_REBIND: return "rebind";
case ACTION_UNBIND: return "unbind";
case ACTION_LOOKUP: return "lookup";
case ACTION_LIST: return "list";
case ACTION_LIST_BINDINGS: return "listBindings";
case ACTION_CREATE_SUBCONTEXT: return "createSubcontext";
case ACTION_DESTROY_SUBCONTEXT: return "destroySubcontext";
case ACTION_ADD_NAMING_LISTENER: return "addNamingListener";
default: throw Assert.impossibleSwitchCase(bit);
}
}
}
| 16,558 | 38.997585 | 138 |
java
|
null |
wildfly-main/naming/src/main/java/org/wildfly/naming/java/permission/SerializedJndiPermission.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.naming.java.permission;
import java.io.Serializable;
final class SerializedJndiPermission implements Serializable {
private static final long serialVersionUID = - 7602123815143424767L;
private final String name;
private final String actions;
SerializedJndiPermission(final String name, final String actions) {
this.name = name;
this.actions = actions;
}
Object readResolve() {
return new JndiPermission(name, actions);
}
}
| 1,524 | 35.309524 | 72 |
java
|
null |
wildfly-main/sar/src/test/_java/org/jboss/as/service/JBossServiceXmlDescriptorParserTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.service;
import java.net.URL;
import org.jboss.as.service.descriptor.JBossServiceAttributeConfig;
import org.jboss.as.service.descriptor.JBossServiceConfig;
import org.jboss.as.service.descriptor.JBossServiceConstructorConfig;
import org.jboss.as.service.descriptor.JBossServiceDependencyConfig;
import org.jboss.as.service.descriptor.JBossServiceXmlDescriptor;
import org.jboss.as.service.descriptor.JBossServiceXmlDescriptorParser;
import org.jboss.as.model.ParseResult;
import org.jboss.staxmapper.XMLMapper;
import org.junit.Before;
import org.junit.Test;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/**
* Test to verify the {@code JBossServiceXmlDescriptorParser} implementation.
*
* @author John E. Bailey
*/
public class JBossServiceXmlDescriptorParserTestCase {
private JBossServiceXmlDescriptorParser parser;
private XMLMapper xmlMapper;
private XMLInputFactory inputFactory;
@Before
public void setupParser() throws Exception {
parser = new JBossServiceXmlDescriptorParser(propertyReplacer);
xmlMapper = XMLMapper.Factory.create();
xmlMapper.registerRootElement(new QName(JBossServiceXmlDescriptorParser.NAMESPACE, "server"), parser);
inputFactory = XMLInputFactory.newInstance();
}
@Test
public void testParse() throws Exception {
final File testXmlFile = getResourceFile(JBossServiceXmlDescriptorParserTestCase.class, "/test/serviceXmlDeployment.jar/META-INF/jboss-service.xml");
final ParseResult<JBossServiceXmlDescriptor> jBossServiceXmlDescriptorParseResult = new ParseResult<JBossServiceXmlDescriptor>();
InputStream inputStream = null;
try {
inputStream = new FileInputStream(testXmlFile);
final XMLStreamReader reader = inputFactory.createXMLStreamReader(inputStream);
xmlMapper.parseDocument(jBossServiceXmlDescriptorParseResult, reader);
} finally {
if (inputStream != null) inputStream.close();
}
final JBossServiceXmlDescriptor xmlDescriptor = jBossServiceXmlDescriptorParseResult.getResult();
assertNotNull(xmlDescriptor);
final List<JBossServiceConfig> serviceConfigs = xmlDescriptor.getServiceConfigs();
assertEquals(3, serviceConfigs.size());
for (JBossServiceConfig jBossServiceConfig : serviceConfigs) {
assertEquals("org.jboss.as.service.LegacyService", jBossServiceConfig.getCode());
if (jBossServiceConfig.getName().equals("jboss.test.service")) {
final JBossServiceConstructorConfig constructorConfig = jBossServiceConfig.getConstructorConfig();
assertNotNull(constructorConfig);
final JBossServiceConstructorConfig.Argument[] arguments = constructorConfig.getArguments();
assertEquals(1, arguments.length);
assertEquals(String.class.getName(), arguments[0].getType());
assertEquals("Test Value", arguments[0].getValue());
} else if (jBossServiceConfig.getName().equals("jboss.test.service.second")) {
assertNull(jBossServiceConfig.getConstructorConfig());
final JBossServiceDependencyConfig[] dependencyConfigs = jBossServiceConfig.getDependencyConfigs();
assertEquals(1, dependencyConfigs.length);
assertEquals("jboss.test.service", dependencyConfigs[0].getDependencyName());
assertEquals("other", dependencyConfigs[0].getOptionalAttributeName());
final JBossServiceAttributeConfig[] attributeConfigs = jBossServiceConfig.getAttributeConfigs();
assertEquals(1, attributeConfigs.length);
assertEquals("somethingElse", attributeConfigs[0].getName());
assertNull(attributeConfigs[0].getInject());
final JBossServiceAttributeConfig.ValueFactory valueFactory = attributeConfigs[0].getValueFactory();
assertNotNull(valueFactory);
assertEquals("jboss.test.service", valueFactory.getBeanName());
assertEquals("appendSomethingElse", valueFactory.getMethodName());
final JBossServiceAttributeConfig.ValueFactoryParameter[] parameters = valueFactory.getParameters();
assertEquals(1, parameters.length);
assertEquals("java.lang.String", parameters[0].getType());
assertEquals("more value", parameters[0].getValue());
} else if (jBossServiceConfig.getName().equals("jboss.test.service.third")) {
assertNull(jBossServiceConfig.getConstructorConfig());
final JBossServiceAttributeConfig[] attributeConfigs = jBossServiceConfig.getAttributeConfigs();
assertEquals(2, attributeConfigs.length);
assertEquals("other", attributeConfigs[0].getName());
assertNull(attributeConfigs[0].getValueFactory());
final JBossServiceAttributeConfig.Inject inject = attributeConfigs[0].getInject();
assertNotNull(inject);
assertEquals("jboss.test.service.second", inject.getBeanName());
assertEquals("other", inject.getPropertyName());
assertEquals("somethingElse", attributeConfigs[1].getName());
assertNull(attributeConfigs[1].getValueFactory());
assertNull(attributeConfigs[1].getInject());
assertEquals("Another test value", attributeConfigs[1].getValue());
}
}
}
protected URL getResource(final Class<?> testClass, final String path) throws Exception {
return testClass.getResource(path);
}
protected File getResourceFile(final Class<?> testClass, final String path) throws Exception {
return new File(getResource(testClass, path).toURI());
}
}
| 7,204 | 49.739437 | 157 |
java
|
null |
wildfly-main/sar/src/test/_java/org/jboss/as/service/LegacyService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.service;
import org.jboss.logging.Logger;
/**
* @author John E. Bailey
*/
public class LegacyService implements LegacyServiceMBean {
private static final Logger logger = Logger.getLogger(LegacyService.class);
private LegacyService other;
private String somethingElse;
public LegacyService() {
}
public LegacyService(String somethingElse) {
this.somethingElse = somethingElse;
}
public void setOther(LegacyService other) {
this.other = other;
}
public LegacyService getOther() {
return other;
}
public String getSomethingElse() {
return somethingElse;
}
public String appendSomethingElse(String more) {
return somethingElse + " - " + more;
}
public void setSomethingElse(String somethingElse) {
this.somethingElse = somethingElse;
}
public void start() {
logger.info("Started");
}
public void stop() {
logger.info("Stopped");
}
}
| 2,037 | 27.305556 | 79 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.