下面列出了怎么用javax.naming.NameAlreadyBoundException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Bind the object to the given name.
*
* @param name the name.
* @param object the object.
* @throws NamingException when an naming error occurs.
*/
@Override
public void bind(String name, Object object) throws NamingException {
checkClosed();
if (name.contains("/")) {
String[] names = name.split("/");
DefaultInitialContext contextMap = this;
for (int i = 0; i < names.length - 1; i++) {
try {
contextMap = (DefaultInitialContext) contextMap.lookup(names[i]);
} catch (NameNotFoundException ne) {
contextMap = (DefaultInitialContext) contextMap.createSubcontext(names[i]);
}
}
contextMap.bind(names[names.length - 1], object);
} else if (!bindings.containsKey(name)) {
bindings.put(name, object);
} else {
throw new NameAlreadyBoundException("Name '" + name + "' already bound");
}
}
public DestinationWrapper<Topic> lookupTopic( String topic, Session session ) throws JMSException, NamingException {
if ( usingJNDI || session==null ) {
if ( autoCreateTopics ) {
Topic t = configureMQTopic( (MQTopic)session.createTopic( topic ) );
try {
getInitialContext().bind( topic, t );
Log.logger.fine( "Auto-created JNDI entry for "+topic );
} catch ( NameAlreadyBoundException e ) {
// No op - already exists
}
} // end if
return lookupTopicFromJNDI( topic );
} else {
return new DestinationWrapper<Topic>(topic,
configureMQTopic((MQTopic) session.createTopic(topic)));
}
}
public void createQueue(String name) throws Exception {
if ( usingJNDI ) {
// Assumes use of ME01 SupportPac for WMQInitialContextFactory
Queue queue = configureMQQueue( new MQQueue(name) );
try {
getInitialContext().bind( name, queue );
} catch ( NameAlreadyBoundException e ) {
// No op - already exists
}
} else {
// "new" PCF style.
PCFMessageAgent agent = new PCFMessageAgent( Config.parms.getString("jh"), Config.parms.getInt("jp"), "CLIENT" );
PCFMessage message = new PCFMessage( CMQCFC.MQCMD_CREATE_Q );
message.addParameter( CMQC.MQCA_Q_NAME, name);
agent.send( message );
}
}
public DestinationWrapper<Topic> lookupTopic(String topic, JMSContext context) throws JMSException, NamingException {
if (usingJNDI || context == null) {
if (autoCreateTopics) {
Topic t = configureMQTopic((MQTopic)context.createTopic(topic));
try {
getInitialContext().bind(topic, t);
Log.logger.fine( "Auto-created JNDI entry for: " + topic );
} catch ( NameAlreadyBoundException e ) {
// No op - already exists
}
} // end if
return lookupTopicFromJNDI(topic);
} else {
return new DestinationWrapper<Topic>(topic, configureMQTopic((MQTopic) context.createTopic(topic)));
}
}
@Override
public void bind(Name name, Object obj) throws NamingException {
if (name.isEmpty()) {
throw new InvalidNameException("Cannot bind empty name");
}
Name nm = getMyComponents(name);
String atom = nm.get(0);
Object inter = iBindings.get(atom);
if (nm.size() == 1) {
if (inter != null)
throw new NameAlreadyBoundException("Use rebind to override");
obj = NamingManager.getStateToBind(obj, new CompositeName().add(atom), this, iEnv);
iBindings.put(atom, obj);
} else {
if (!(inter instanceof Context))
throw new NotContextException(atom + " does not name a context");
((Context) inter).bind(nm.getSuffix(1), obj);
}
}
@Override
public Context createSubcontext(Name name) throws NamingException {
if (name.isEmpty())
throw new InvalidNameException("Cannot bind empty name");
Name nm = getMyComponents(name);
String atom = nm.get(0);
Object inter = iBindings.get(atom);
if (nm.size() == 1) {
if (inter != null)
throw new NameAlreadyBoundException("Use rebind to override");
Context child = createCtx(this, atom, iEnv);
iBindings.put(atom, child);
return child;
} else {
if (!(inter instanceof Context))
throw new NotContextException(atom + " does not name a context");
return ((Context) inter).createSubcontext(nm.getSuffix(1));
}
}
/**
* Binds a new name to the object bound to an old name, and unbinds the old name. Both names are relative to this context. Any attributes associated with the old name
* become associated with the new name. Intermediate contexts of the old name are not changed.
*
* @param oldName
* the name of the existing binding; may not be empty
* @param newName
* the name of the new binding; may not be empty
* @exception NameAlreadyBoundException
* if newName is already bound
* @exception NamingException
* if a naming exception is encountered
*/
@Override
public void rename(String oldName, String newName) throws NamingException {
VFSItem oldFile = resolveFile(oldName);
if (oldFile == null)
throw new NamingException(smgr.getString("resources.notFound", oldName));
VFSItem newFile = resolveFile(newName);
if (newFile != null)
throw new NameAlreadyBoundException();
VFSStatus status = oldFile.rename(newName);
if (status == VFSConstants.NO)
throw new NameAlreadyBoundException();
}
/**
* Creates and binds a new context, along with associated attributes. This method creates a new subcontext with the given name, binds it in the target context (that
* named by all but terminal atomic component of the name), and associates the supplied attributes with the newly created object. All intermediate and target contexts
* must already exist. If attrs is null, this method is equivalent to Context.createSubcontext().
*
* @param name
* the name of the context to create; may not be empty
* @param attrs
* the attributes to associate with the newly created context
* @return the newly created context
* @exception NameAlreadyBoundException
* if the name is already bound
* @exception InvalidAttributesException
* if attrs does not contain all the mandatory attributes required for creation
* @exception NamingException
* if a naming exception is encountered
*/
@Override
public DirContext createSubcontext(String name, Attributes attrs) throws NamingException {
VFSItem file = resolveFile(name);
if (file != null)
throw new NameAlreadyBoundException(smgr.getString("resources.alreadyBound", name));
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1)
throw new NamingException();
String parent = name.substring(0, lastSlash);
VFSItem folder = resolveFile(parent);
if (folder == null || (!(folder instanceof VFSContainer)))
throw new NamingException(smgr.getString("resources.bindFailed", name));
String newName = name.substring(lastSlash + 1);
VFSItem childContainer = ((VFSContainer) folder).createChildContainer(newName);
if (childContainer == null)
throw new NamingException(smgr.getString("resources.bindFailed", name));
return (DirContext) lookup(name);
}
/**
* Binds a new name to the object bound to an old name, and unbinds the old name. Both names are relative to this context. Any attributes associated with the old name
* become associated with the new name. Intermediate contexts of the old name are not changed.
*
* @param oldName
* the name of the existing binding; may not be empty
* @param newName
* the name of the new binding; may not be empty
* @exception NameAlreadyBoundException
* if newName is already bound
* @exception NamingException
* if a naming exception is encountered
*/
@Override
public void rename(String oldName, String newName) throws NamingException {
VFSItem oldFile = resolveFile(oldName);
if (oldFile == null)
throw new NamingException(smgr.getString("resources.notFound", oldName));
VFSItem newFile = resolveFile(newName);
if (newFile != null)
throw new NameAlreadyBoundException();
VFSStatus status = oldFile.rename(newName);
if (status == VFSConstants.NO)
throw new NameAlreadyBoundException();
}
/**
* Creates and binds a new context, along with associated attributes. This method creates a new subcontext with the given name, binds it in the target context (that
* named by all but terminal atomic component of the name), and associates the supplied attributes with the newly created object. All intermediate and target contexts
* must already exist. If attrs is null, this method is equivalent to Context.createSubcontext().
*
* @param name
* the name of the context to create; may not be empty
* @param attrs
* the attributes to associate with the newly created context
* @return the newly created context
* @exception NameAlreadyBoundException
* if the name is already bound
* @exception InvalidAttributesException
* if attrs does not contain all the mandatory attributes required for creation
* @exception NamingException
* if a naming exception is encountered
*/
@Override
public DirContext createSubcontext(String name, Attributes attrs) throws NamingException {
VFSItem file = resolveFile(name);
if (file != null)
throw new NameAlreadyBoundException(smgr.getString("resources.alreadyBound", name));
int lastSlash = name.lastIndexOf('/');
if (lastSlash == -1)
throw new NamingException();
String parent = name.substring(0, lastSlash);
VFSItem folder = resolveFile(parent);
if (folder == null || (!(folder instanceof VFSContainer)))
throw new NamingException(smgr.getString("resources.bindFailed", name));
String newName = name.substring(lastSlash + 1);
VFSItem childContainer = ((VFSContainer) folder).createChildContainer(newName);
if (childContainer == null)
throw new NamingException(smgr.getString("resources.bindFailed", name));
return (DirContext) lookup(name);
}
public synchronized void bind(String name, Object obj) throws NamingException {
if (name == null) {
throw new IllegalArgumentException("Name required");
}
if (name.length() == 0) {
throw new InvalidNameException("Cannot bind object named after context");
}
// If it's an alias name, stop here.
if (aliases.containsKey(name)) {
throw new NameAlreadyBoundException("Name \"" + name + "\" already bound as an aliased name");
}
// Make sure it isn't bound anywhere
for (NamingEnumeration e = list(""); e.hasMore();) {
NameClassPair nameClassPair = (NameClassPair) e.next();
if (name.equals(nameClassPair.getName())) {
throw new NameAlreadyBoundException("Name \"" + name + "\" already bound by a managed subcontext");
}
}
doRebind(name, obj);
}
public void bindGlobals(final Map<String, Object> bindings) throws NamingException {
final Context containerSystemContext = containerSystem.getJNDIContext();
for (final Entry<String, Object> value : bindings.entrySet()) {
final String path = value.getKey();
// keep only global bindings
if (path.startsWith("module/") || path.startsWith("app/") || path.startsWith("comp/") || path.equalsIgnoreCase("global/dummy")) {
continue;
}
// a bit weird but just to be consistent if user doesn't lookup directly the resource
final Context lastContext = Contexts.createSubcontexts(containerSystemContext, path);
try {
lastContext.rebind(path.substring(path.lastIndexOf('/') + 1, path.length()), value.getValue());
} catch (final NameAlreadyBoundException nabe) {
nabe.printStackTrace();
}
containerSystemContext.rebind(path, value.getValue());
}
}
public void bind(String name, final Object obj) throws NamingException {
if(checkReadOnly()) {
return;
}
final int indx = name.indexOf(':');
if (indx > -1) {
/*
The ':' character will be in the path if its an absolute path name starting with the schema
'java:'. We strip the schema off the path before passing it to the node.resolve method.
*/
name = name.substring(indx + 1);
}
if (fastCache.containsKey(name)) {
throw new NameAlreadyBoundException();
} else {
final ParsedName parsedName = getParsedNameFor(name);
mynode.bind(parsedName, obj);
}
}
public Context createSubcontext(String name) throws NamingException {
if(checkReadOnly()) {
//TODO: null is fine if there is a one time - 10 calls will log a single time - log line (warning?)
return null;
}
final int indx = name.indexOf(':');
if (indx > -1) {
/*
The ':' character will be in the path if its an absolute path name starting with the schema
'java:'. We strip the schema off the path before passing it to the node.resolve method.
*/
name = name.substring(indx + 1);
}
if (fastCache.containsKey(name)) {
throw new NameAlreadyBoundException();
} else {
return mynode.createSubcontext(getParsedNameFor(name), readOnly);
}
}
public void unbind(final ParsedName name) throws NameAlreadyBoundException {
final int compareResult = name.compareTo(atomicHash);
if (compareResult == ParsedName.IS_EQUAL && name.getComponent().equals(atomicName)) {
if (name.next()) {
if (subTree != null) {
subTree.unbind(name);
}
} else {
unbound = true;
myObject = null;
parentTree.unbind(this);
}
} else if (compareResult == ParsedName.IS_LESS) {
if (lessTree != null) {
lessTree.unbind(name);
}
} else {//ParsedName.IS_GREATER ...
if (grtrTree != null) {
grtrTree.unbind(name);
}
}
}
/**
* Rename the object.
*
* @param oldName the old name.
* @param newName the new name.
* @throws NamingException when a naming error occurs.
*/
@Override
public void rename(String oldName, String newName) throws NamingException {
checkClosed();
try {
lookup(newName);
throw new NameAlreadyBoundException(newName);
} catch (NameNotFoundException nnfe) {
// intentionally not caught.
}
Object object = lookup(oldName);
bind(newName, object);
unbind(oldName);
}
/**
* Test bind method.
*
* @throws Exception when an error occurs.
*/
@Test
public void testBind3() throws Exception {
DefaultInitialContext context = new DefaultInitialContext();
Name name = new CompositeName("name");
context.bind(name, "value");
assertNotNull(context.lookup(name));
assertThrows(NameAlreadyBoundException.class, () -> context.bind(name, "value"));
}
/**
* Test rename method.
*
* @throws Exception when an error occurs.
*/
@Test
public void testRename() throws Exception {
DefaultInitialContext context = new DefaultInitialContext();
context.bind("name", "value");
assertThrows(NameAlreadyBoundException.class, () -> context.rename("rename", "name"));
}
public void createTopic(String name) throws Exception {
if ( usingJNDI ) {
// Assumes use of ME01 SupportPac for WMQInitialContextFactory
Topic topic = configureMQTopic( new MQTopic(name) );
try {
getInitialContext().bind( name, topic );
} catch ( NameAlreadyBoundException e ) {
// No op - already exists
}
} else {
// No-op
}
}
public void createConnectionFactory(String name) throws Exception {
if ( usingJNDI ) {
ConnectionFactory cf = new MQConnectionFactory();
configureMQConnectionFactory( (MQConnectionFactory)cf );
try {
getInitialContext().bind( name, cf );
} catch ( NameAlreadyBoundException e ) {
// swallowed
}
} else {
// No op
}
}
public void createQueueConnectionFactory(String name) throws Exception {
if ( usingJNDI ) {
QueueConnectionFactory qcf = new MQQueueConnectionFactory();
configureMQConnectionFactory((MQConnectionFactory)qcf);
try {
getInitialContext().bind( name, qcf );
} catch ( NameAlreadyBoundException e ) {
// swallowed
}
} else {
// No op
}
}
public void createTopicConnectionFactory(String name) throws Exception {
if ( usingJNDI ) {
TopicConnectionFactory tcf = new MQTopicConnectionFactory();
configureMQConnectionFactory((MQConnectionFactory)tcf);
try {
getInitialContext().bind( name, tcf );
} catch ( NameAlreadyBoundException e ) {
// swallowed
}
} else {
// No op
}
}
/**
* Creates subcontext with name, relative to this Context.
*
* @param name subcontext name.
* @return new subcontext named name relative to this context.
* @throws NoPermissionException if this context has been destroyed.
* @throws InvalidNameException if name is empty or is CompositeName that
* spans more than one naming system.
* @throws NameAlreadyBoundException if name is already bound in this Context
* @throws NotContextException if any intermediate name from name is not bound
* to instance of javax.naming.Context.
*
*/
public Context createSubcontext(Name name) throws NamingException {
checkIsDestroyed();
Name parsedName = getParsedName(name);
if (parsedName.size() == 0 || parsedName.get(0).length() == 0) { throw new InvalidNameException(LocalizedStrings.ContextImpl_NAME_CAN_NOT_BE_EMPTY.toLocalizedString()); }
String subContextName = parsedName.get(0);
Object boundObject = ctxMaps.get(parsedName.get(0));
if (parsedName.size() == 1) {
// Check if name is already in use
if (boundObject == null) {
Context subContext = new ContextImpl(this, subContextName);
ctxMaps.put(subContextName, subContext);
return subContext;
}
else {
throw new NameAlreadyBoundException(LocalizedStrings.ContextImpl_NAME_0_IS_ALREADY_BOUND.toLocalizedString(subContextName));
}
}
else {
if (boundObject instanceof Context) {
// Let the subcontext create new subcontext
// lets consider a scenerio a/b/c
// case a/b exists : c will be created
// case a exists : b/c will not be created
// an exception will be thrown in that case.
return ((Context) boundObject)
.createSubcontext(parsedName.getSuffix(1));
}
else {
throw new NotContextException(LocalizedStrings.ContextImpl_EXPECTED_CONTEXT_BUT_FOUND_0.toLocalizedString(boundObject));
}
}
}
/**
* Creates subcontext with name, relative to this Context.
*
* @param name subcontext name.
* @return new subcontext named name relative to this context.
* @throws NoPermissionException if this context has been destroyed.
* @throws InvalidNameException if name is empty or is CompositeName that
* spans more than one naming system.
* @throws NameAlreadyBoundException if name is already bound in this Context
* @throws NotContextException if any intermediate name from name is not bound
* to instance of javax.naming.Context.
*
*/
public Context createSubcontext(Name name) throws NamingException {
checkIsDestroyed();
Name parsedName = getParsedName(name);
if (parsedName.size() == 0 || parsedName.get(0).length() == 0) { throw new InvalidNameException(LocalizedStrings.ContextImpl_NAME_CAN_NOT_BE_EMPTY.toLocalizedString()); }
String subContextName = parsedName.get(0);
Object boundObject = ctxMaps.get(parsedName.get(0));
if (parsedName.size() == 1) {
// Check if name is already in use
if (boundObject == null) {
Context subContext = new ContextImpl(this, subContextName);
ctxMaps.put(subContextName, subContext);
return subContext;
}
else {
throw new NameAlreadyBoundException(LocalizedStrings.ContextImpl_NAME_0_IS_ALREADY_BOUND.toLocalizedString(subContextName));
}
}
else {
if (boundObject instanceof Context) {
// Let the subcontext create new subcontext
// lets consider a scenerio a/b/c
// case a/b exists : c will be created
// case a exists : b/c will not be created
// an exception will be thrown in that case.
return ((Context) boundObject)
.createSubcontext(parsedName.getSuffix(1));
}
else {
throw new NotContextException(LocalizedStrings.ContextImpl_EXPECTED_CONTEXT_BUT_FOUND_0.toLocalizedString(boundObject));
}
}
}
public void addGroup(String name, String description)
throws NamingException {
// Create a container set of attributes
Attributes container = new BasicAttributes();
// Create the objectclass to add
Attribute objClasses = new BasicAttribute("objectClass");
objClasses.add("top");
objClasses.add("groupOfNames");
// Assign the name and description to the group
Attribute cn = new BasicAttribute("cn", name);
Attribute desc = new BasicAttribute("description", description);
// Add these to the container
container.put(objClasses);
container.put(cn);
container.put(desc);
try {
// Create the entry
context.createSubcontext(getGroupDN(name), container);
} catch (NameAlreadyBoundException e) {
log.info("Group already exist ..");
// Group already added. ignore exception.
}
}
@Override
public void rename(Name oldname, Name newname) throws NamingException {
if (oldname.isEmpty() || newname.isEmpty())
throw new InvalidNameException("Cannot rename empty name");
Name oldnm = getMyComponents(oldname);
Name newnm = getMyComponents(newname);
if (oldnm.size() != newnm.size())
throw new OperationNotSupportedException("Do not support rename across different contexts");
String oldatom = oldnm.get(0);
String newatom = newnm.get(0);
if (oldnm.size() == 1) {
if (iBindings.get(newatom) != null)
throw new NameAlreadyBoundException(newname.toString() + " is already bound");
Object oldBinding = iBindings.remove(oldatom);
if (oldBinding == null)
throw new NameNotFoundException(oldname.toString() + " not bound");
iBindings.put(newatom, oldBinding);
} else {
if (!oldatom.equals(newatom))
throw new OperationNotSupportedException("Do not support rename across different contexts");
Object inter = iBindings.get(oldatom);
if (!(inter instanceof Context))
throw new NotContextException(oldatom + " does not name a context");
((Context) inter).rename(oldnm.getSuffix(1), newnm.getSuffix(1));
}
}
@Override
public Context createSubcontext(String name) throws NamingException {
name = trimSlashes(name);
if (map.get(name) != null) {
throw new NameAlreadyBoundException(name);
}
InVMNamingContext c = new InVMNamingContext(getNameInNamespace());
map.put(name, c);
return c;
}
private void internalBind(String name, final Object obj, final boolean rebind) throws NamingException {
name = trimSlashes(name);
int i = name.lastIndexOf("/");
InVMNamingContext c = this;
if (i != -1) {
String path = name.substring(0, i);
c = (InVMNamingContext) lookup(path);
}
name = name.substring(i + 1);
if (!rebind && c.map.get(name) != null) {
throw new NameAlreadyBoundException(name);
}
c.map.put(name, obj);
}
@Override
public Context createSubcontext(String name) throws NamingException {
name = trimSlashes(name);
if (map.get(name) != null) {
throw new NameAlreadyBoundException(name);
}
InVMContext c = new InVMContext(getNameInNamespace());
map.put(name, c);
return c;
}
private void internalBind(String name, final Object obj, final boolean rebind) throws NamingException {
InVMContext.log.debug("Binding " + name + " obj " + obj + " rebind " + rebind);
name = trimSlashes(name);
int i = name.lastIndexOf("/");
InVMContext c = this;
if (i != -1) {
String path = name.substring(0, i);
c = (InVMContext) lookup(path);
}
name = name.substring(i + 1);
if (!rebind && c.map.get(name) != null) {
throw new NameAlreadyBoundException(name);
}
c.map.put(name, obj);
}