下面列出了怎么用javax.naming.Name的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Adds components to the end of remaining name.
*
* @param name The components to add. Can be null.
* @see #getRemainingName
* @see #setRemainingName
* @see #appendRemainingComponent
*/
public void appendRemainingName(Name name) {
// System.out.println("appendingRemainingName: " + name.toString());
// Exception e = new Exception();
// e.printStackTrace();
if (name != null) {
if (this.remainingName != null) {
try {
this.remainingName.addAll(name);
} catch (InvalidNameException e) {
// ignore; shouldn't happen for composite name
}
} else {
this.remainingName = (Name)(name.clone());
}
}
}
/**
* Adds components to the end of remaining name.
*
* @param name The components to add. Can be null.
* @see #getRemainingName
* @see #setRemainingName
* @see #appendRemainingComponent
*/
public void appendRemainingName(Name name) {
// System.out.println("appendingRemainingName: " + name.toString());
// Exception e = new Exception();
// e.printStackTrace();
if (name != null) {
if (this.remainingName != null) {
try {
this.remainingName.addAll(name);
} catch (InvalidNameException e) {
// ignore; shouldn't happen for composite name
}
} else {
this.remainingName = (Name)(name.clone());
}
}
}
/**
* Remove the supplied path from the beginning the specified
* <code>Name</code> if the name instance starts with
* <code>path</code>. Useful for stripping base path suffix from a
* <code>Name</code>. The original Name will not be affected.
*
* @param dn the dn to strip from.
* @param pathToRemove the path to remove from the beginning the dn instance.
* @return an LdapName instance that is a copy of the original name with the
* specified path stripped from its beginning.
* @since 2.0
*/
public static LdapName removeFirst(Name dn, Name pathToRemove) {
Assert.notNull(dn, "dn must not be null");
Assert.notNull(pathToRemove, "pathToRemove must not be null");
LdapName result = newLdapName(dn);
LdapName path = returnOrConstructLdapNameFromName(pathToRemove);
if(path.size() == 0 || !dn.startsWith(path)) {
return result;
}
for(int i = 0; i < path.size(); i++) {
try {
result.remove(0);
} catch (InvalidNameException e) {
throw convertLdapException(e);
}
}
return result;
}
/**
* Enumerates the names bound in the named context, along with the
* objects bound to them. The contents of any subcontexts are not
* included.
* <p>
* If a binding is added to or removed from this context, its effect on
* an enumeration previously returned is undefined.
*
* @param strName the name of the context to list
* @return an enumeration of the bindings in this context.
* Each element of the enumeration is of type Binding.
* @exception NamingException if a naming exception is encountered
*/
@Override
protected List<NamingEntry> doListBindings(String strName)
throws NamingException {
Name name = getEscapedJndiName(strName);
if (name.isEmpty())
return list(entries);
Entry entry = treeLookup(name);
if (entry == null)
return null;
return list(entry);
}
@Override
public Object getObjectInstance(final Object object, final Name name, final Context context, final Hashtable environment) throws Exception {
// ignore non ejb-refs
if (!(object instanceof EjbRef)) {
return null;
}
// lookup the value
Object value = super.getObjectInstance(object, name, context, environment);
// if this is an external reference, copy it into the local class loader
if (NamingUtil.isPropertyTrue((Reference) object, NamingUtil.EXTERNAL)) {
value = copy(value);
}
// done
return value;
}
public NamingEnumeration<SearchResult> search(Name name,
String filterExpr,
Object[] args,
SearchControls cons)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().search(res.getName(), filterExpr, args,
cons);
}
/**
* Tests add entry
*
*/
public void testModifyAdd() throws NamingException {
final Entry e = readEntry(
"dn: cn=ldap,dc=scriptella\n" +
"cn: ldap\n" +
"objectClass: top\n" +
"objectClass: driver\n" +
"envVars:");
DirContext mock = new ProxyAdapter<DirContext>(DirContext.class) {
public String getNameInNamespace() {
return "dc=scriptella";
}
public DirContext createSubcontext(Name name, Attributes attrs) throws InvalidNameException {
assertEquals(newName("cn=ldap"), name);
BasicAttributes exp = new BasicAttributes(true);
exp.put("cn", "ldap");
final BasicAttribute oc = new BasicAttribute("objectClass");
oc.add("top");
oc.add("driver");
exp.put(oc);
exp.put("envVars", null);
assertEquals(exp, attrs);
modified=true;
return null;
}
}.getProxy();
LdifScript.modify(mock, e);
assertTrue("DirContext was not modified", modified);
}
/**
* 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"));
}
public Name add(int index, String string) throws InvalidNameException {
try {
names.add(index, new LdapRdn(string));
}
catch (BadLdapGrammarException e) {
throw new InvalidNameException("Failed to parse rdn '" + string + "'");
}
return this;
}
/**
* Creates and binds a new context. Creates a new context with the given
* name and binds it in the target context (that named by all but
* terminal atomic component of the name). All intermediate contexts and
* the target context must already exist.
*
* @param name the name of the context to create; may not be empty
* @return the newly created context
* @exception NameAlreadyBoundException if name is already bound
* @exception javax.naming.directory.InvalidAttributesException if creation
* of the sub-context requires specification of mandatory attributes
* @exception NamingException if a naming exception is encountered
*/
@Override
public Context createSubcontext(Name name) throws NamingException {
if (!checkWritable()) {
return null;
}
NamingContext newContext = new NamingContext(env, this.name);
bind(name, newContext);
newContext.setExceptionOnFailedWrite(getExceptionOnFailedWrite());
return newContext;
}
public NamingEnumeration<SearchResult> search(Name name,
String filterExpr,
Object[] args,
SearchControls cons)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().search(res.getName(), filterExpr, args,
cons);
}
@Override
public Object getObjectInstance(final Object obj,
final Name name,
final Context nameCtx,
final Hashtable<?, ?> env) throws Exception {
Reference ref = (Reference) obj;
RefAddr addr = ref.get("nns");
String key = (String) addr.getContent();
return NonSerializableFactory.getWrapperMap().get(key);
}
public NamingEnumeration<SearchResult> search(Name name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().search(res.getName(), matchingAttributes,
attributesToReturn);
}
/**
* Clear the directory sub-tree starting with the node represented by the
* supplied distinguished name.
*
* @param contextSource the ContextSource to use for getting a DirContext.
* @param name the distinguished name of the root node.
* @throws NamingException if anything goes wrong removing the sub-tree.
*/
public static void clearSubContexts(ContextSource contextSource, Name name) throws NamingException {
DirContext ctx = null;
try {
ctx = contextSource.getReadWriteContext();
clearSubContexts(ctx, name);
} finally {
try {
ctx.close();
} catch (Exception e) {
// Never mind this
}
}
}
public NamingEnumeration<SearchResult> search(Name name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().search(res.getName(), matchingAttributes,
attributesToReturn);
}
public Name addAll(int arg0, Name name) throws InvalidNameException {
DistinguishedName distinguishedName = null;
try {
distinguishedName = (DistinguishedName) name;
}
catch (ClassCastException e) {
throw new InvalidNameException("Invalid name type");
}
names.addAll(arg0, distinguishedName.getNames());
return this;
}
protected DirContextStringPair getTargetContext(String name)
throws NamingException {
if (cpe.getResolvedObj() == null)
throw (NamingException)cpe.fillInStackTrace();
Context ctx = NamingManager.getContext(cpe.getResolvedObj(),
cpe.getAltName(),
cpe.getAltNameCtx(),
env);
if (ctx instanceof DirContext)
return new DirContextStringPair((DirContext)ctx, name);
if (ctx instanceof Resolver) {
Resolver res = (Resolver)ctx;
ResolveResult rr = res.resolveToClass(name, DirContext.class);
// Reached a DirContext; return result.
DirContext dctx = (DirContext)rr.getResolvedObj();
Name tmp = rr.getRemainingName();
String remains = (tmp != null) ? tmp.toString() : "";
return (new DirContextStringPair(dctx, remains));
}
// Resolve all the way using lookup(). This may allow the operation
// to succeed if it doesn't require the penultimate context.
Object ultimate = ctx.lookup(name);
if (ultimate instanceof DirContext) {
return (new DirContextStringPair((DirContext)ultimate, ""));
}
throw (NamingException)cpe.fillInStackTrace();
}
@Override
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
return new NamingEnumerationStub();
}
public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException {
throw new OperationNotSupportedException();
}
/**
* {@inheritDoc}
*/
@Override
public NamingEnumeration<Binding> listBindings(final Name name) throws NamingException {
return getThreadContext().listBindings(name);
}
@Override
public Object lookup(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
public NamingEnumeration list(Name _name) throws NamingException {
throw new OperationNotSupportedException();
}
@Override
public void bind(Name name, Object obj) throws NamingException
{
this.bind(StringUtils.join(Collections.list(name.getAll()), "/"), obj);
}
@Override
public Object lookupLink(Name name) throws NamingException {
return null;
}
public DifferentSubtreeTempEntryRenamingStrategy(Name subtreeNode) {
this.subtreeNode = subtreeNode;
}
/**
* {@inheritDoc}
*/
@Override
public void rename(final Name oldName, final Name newName) throws NamingException {
// No code necessary
}
public void bind(Name name, Object obj, Attributes attrs)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
res.getDirContext().bind(res.getName(), obj, attrs);
}
public void rebind(Name name, Object obj, Attributes attrs)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
res.getDirContext().rebind(res.getName(), obj, attrs);
}
public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes, String[] attributesToReturn)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void unbind(final Name name) throws NamingException {
unbind(name.toString());
}