下面列出了怎么用javax.naming.Binding的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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 name 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
public NamingEnumeration<Binding> listBindings(Name name)
throws NamingException {
// Removing empty parts
while ((!name.isEmpty()) && (name.get(0).length() == 0))
name = name.getSuffix(1);
if (name.isEmpty()) {
return new NamingContextBindingsEnumeration(bindings.values().iterator(), this);
}
NamingEntry entry = bindings.get(name.get(0));
if (entry == null) {
throw new NameNotFoundException
(sm.getString("namingContext.nameNotBound", name, name.get(0)));
}
if (entry.type != NamingEntry.CONTEXT) {
throw new NamingException
(sm.getString("namingContext.contextExpected"));
}
return ((Context) entry.value).listBindings(name.getSuffix(1));
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain;UTF-8");
PrintWriter out = resp.getWriter();
try {
Context ctx = new InitialContext();
NamingEnumeration<Binding> enm =
ctx.listBindings("java:comp/env/list");
while (enm.hasMore()) {
Binding b = enm.next();
out.print(b.getObject().getClass().getName());
}
} catch (NamingException ne) {
ne.printStackTrace(out);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain;UTF-8");
PrintWriter out = resp.getWriter();
try {
Context ctx = new InitialContext();
NamingEnumeration<Binding> enm =
ctx.listBindings("java:comp/env/list");
while (enm.hasMore()) {
Binding b = enm.next();
out.print(b.getObject().getClass().getName());
}
} catch (NamingException ne) {
ne.printStackTrace(out);
}
}
/**
* 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 name 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
public NamingEnumeration<Binding> listBindings(Name name)
throws NamingException {
// Removing empty parts
while ((!name.isEmpty()) && (name.get(0).length() == 0))
name = name.getSuffix(1);
if (name.isEmpty()) {
return new NamingContextBindingsEnumeration(bindings.values().iterator(), this);
}
NamingEntry entry = bindings.get(name.get(0));
if (entry == null) {
throw new NameNotFoundException
(sm.getString("namingContext.nameNotBound", name, name.get(0)));
}
if (entry.type != NamingEntry.CONTEXT) {
throw new NamingException
(sm.getString("namingContext.contextExpected"));
}
return ((Context) entry.value).listBindings(name.getSuffix(1));
}
@Test
public void testListBindings_ContextMapper() throws NamingException {
expectGetReadOnlyContext();
Object expectedObject = new Object();
Binding listResult = new Binding("", expectedObject);
setupStringListBindingsAndNamingEnumeration(listResult);
Object expectedResult = expectedObject;
when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult);
List list = tested.listBindings(NAME, contextMapperMock);
verify(dirContextMock).close();
verify(namingEnumerationMock).close();
assertThat(list).isNotNull();
assertThat(list).hasSize(1);
assertThat(list.get(0)).isSameAs(expectedResult);
}
@Test
public void testUnbindRecursive() throws Exception {
expectGetReadWriteContext();
when(namingEnumerationMock.hasMore()).thenReturn(true, false, false);
Binding binding = new Binding("cn=Some name", null);
when(namingEnumerationMock.next()).thenReturn(binding);
LdapName listDn = LdapUtils.newLdapName(DEFAULT_BASE_STRING);
when(dirContextMock.listBindings(listDn)).thenReturn(namingEnumerationMock);
LdapName subListDn = LdapUtils.newLdapName("cn=Some name, o=example.com");
when(dirContextMock.listBindings(subListDn)).thenReturn(namingEnumerationMock);
tested.unbind(new CompositeName(DEFAULT_BASE_STRING), true);
verify(dirContextMock).unbind(subListDn);
verify(dirContextMock).unbind(listDn);
verify(namingEnumerationMock, times(2)).close();
verify(dirContextMock).close();
}
public T getObjectFromNameClassPair(final NameClassPair nameClassPair) throws NamingException{
if (!(nameClassPair instanceof Binding)) {
throw new IllegalArgumentException("Parameter must be an instance of Binding");
}
Binding binding = (Binding) nameClassPair;
Object object = binding.getObject();
if (object == null) {
throw new ObjectRetrievalException("Binding did not contain any object.");
}
T result;
if (nameClassPair instanceof HasControls) {
result = mapper.mapFromContextWithControls(object, (HasControls) nameClassPair);
}
else {
result = mapper.mapFromContext(object);
}
return result;
}
@SuppressWarnings("unchecked")
@Override
public NamingEnumeration<Binding> listBindings(final String name) throws NamingException {
final Object o = lookup(name);
if (o instanceof Context) {
final Context context = (Context) o;
final NamingEnumeration<NameClassPair> enumeration = context.list("");
final List<NameClassPair> bindings = new ArrayList<NameClassPair>();
while (enumeration.hasMoreElements()) {
final NameClassPair pair = enumeration.nextElement();
bindings.add(new LazyBinding(pair.getName(), pair.getClassName(), context));
}
return new NameClassPairEnumeration(bindings);
} else {
return null;
}
}
private void assertBindings(NamingEnumeration<Binding> namingEnumeration) {
assertNotNull("namingEnumeration", namingEnumeration);
Map<String, Object> map = new HashMap<String, Object>();
while (namingEnumeration.hasMoreElements()) {
Binding pair = namingEnumeration.nextElement();
map.put(pair.getName(), pair.getObject());
}
assertTrue("OrangeRemote", map.containsKey("OrangeRemote"));
assertTrue("OrangeRemote is FruitRemote", map.get("OrangeRemote") instanceof FruitRemote);
assertTrue("AppleRemote", map.containsKey("AppleRemote"));
assertTrue("AppleRemote is FruitRemote", map.get("AppleRemote") instanceof FruitRemote);
assertTrue("PeachRemote", map.containsKey("PeachRemote"));
assertTrue("PeachRemote is FruitRemote", map.get("PeachRemote") instanceof FruitRemote);
assertTrue("PearRemote", map.containsKey("PearRemote"));
assertTrue("PearRemote is FruitRemote", map.get("PearRemote") instanceof FruitRemote);
assertTrue("PlumRemote", map.containsKey("PlumRemote"));
assertTrue("PlumRemote is FruitRemote", map.get("PlumRemote") instanceof FruitRemote);
}
public NamingEnumeration listBindings(String name) throws NamingException {
if (name.length() > 0)
throw new OperationNotSupportedException("subcontexts not supported");
final Iterator i = bindings.entrySet().iterator();
return new NamingEnumeration() {
public Object next() {
Map.Entry e = (Map.Entry) i.next();
return new Binding((String) e.getKey(), e.getValue());
}
public boolean hasMore() {
return i.hasNext();
}
public void close() {}
public boolean hasMoreElements() {
return hasMore();
}
public Object nextElement() {
return next();
}
};
}
private void configFromJndiConf(Object rootContextName) {
if (rootContextName instanceof String) {
String name = (String) rootContextName;
name = name.substring(0, name.lastIndexOf('/')) + "/conf" + name.substring(name.lastIndexOf('/'));
try {
InitialContext ctx = new InitialContext();
NamingEnumeration<Binding> bindings = ctx.listBindings(name);
while (bindings.hasMore()) {
Binding bd = bindings.next();
IntrospectionSupport.setProperty(this, bd.getName(), bd.getObject());
}
} catch (Exception ignored) {
if (LOG.isTraceEnabled()) {
LOG.trace("exception on config from jndi: " + name, ignored);
}
}
}
}
public Object getObjectFromNameClassPair(final NameClassPair nameClassPair) {
if (!(nameClassPair instanceof Binding)) {
throw new IllegalArgumentException("Parameter must be an instance of Binding");
}
Binding binding = (Binding) nameClassPair;
Object object = binding.getObject();
if (object == null) {
throw new ObjectRetrievalException("Binding did not contain any object.");
}
Object result = null;
if (nameClassPair instanceof HasControls) {
result = mapper.mapFromContextWithControls(object, (HasControls) nameClassPair);
}
else {
result = mapper.mapFromContext(object);
}
return result;
}
@Override
public NamingEnumeration<Binding> listBindings(String contextName) throws NamingException {
contextName = trimSlashes(contextName);
if (!"".equals(contextName) && !".".equals(contextName)) {
try {
return ((InVMContext) lookup(contextName)).listBindings("");
} catch (Throwable t) {
throw new NamingException(t.getMessage());
}
}
List<Binding> l = new ArrayList<>();
for (String name : map.keySet()) {
Object object = map.get(name);
l.add(new Binding(name, object));
}
return new NamingEnumerationImpl(l.iterator());
}
/**
* Enumerates the names bound in the named context, along with the
* objects bound to them.
*
* @param name 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.
* @throws NamingException if a naming exception is encountered
*/
@Override
public NamingEnumeration<Binding> listBindings(String name)
throws NamingException {
if (log.isDebugEnabled()) {
log.debug(sm.getString("selectorContext.methodUsingString",
"listBindings", name));
}
return getBoundContext().listBindings(parseName(name));
}
@SuppressWarnings("unchecked")
@Override
public NamingEnumeration<Binding> listBindings(final String name) throws NamingException {
return (NamingEnumeration<Binding>) new LoggingRetryHandler(DEFAULT_EXCEPTION_CLASSES,
this, schedule, maxRetries) {
@Override
public Object operation() throws NamingException {
return getDelegate().listBindings(name);
}
}.perform();
}
@Override
public NamingEnumeration<Binding> listBindings(String name) throws NamingException {
Object o = lookup(name);
if (o == this) {
return new ListBindingEnumeration();
} else if (o instanceof Context) {
return ((Context) o).listBindings("");
} else {
throw new NotContextException();
}
}
@Override
public NamingEnumeration<Binding> listBindings(String root) throws NamingException {
if (logger.isDebugEnabled()) {
logger.debug("Listing bindings under [" + root + "]");
}
return new BindingEnumeration(this, root);
}
@Override
public NamingEnumeration<Binding> listBindings(String root) throws NamingException {
if (logger.isDebugEnabled()) {
logger.debug("Listing bindings under [" + root + "]");
}
return new BindingEnumeration(this, root);
}
@Override
public NamingEnumeration<Binding> listBindings(String root) throws NamingException {
if (logger.isDebugEnabled()) {
logger.debug("Listing bindings under [" + root + "]");
}
return new BindingEnumeration(this, root);
}
@SuppressWarnings ( "unchecked" )
public static Enumeration<?> makeLazySearchEnumeration ( String codebase, String clazz ) throws Exception {
DirContext ctx = makeContinuationContext(codebase, clazz);
NamingEnumeration<?> inner = Reflections.createWithoutConstructor(LazySearchEnumerationImpl.class);
Reflections.setFieldValue(inner, "nextMatch", new SearchResult("foo", ctx, null));
return new LazySearchEnumerationImpl((NamingEnumeration<Binding>) inner, null, null);
}
/** Test.
* @throws IOException e
* @throws NamingException e */
@Test
public void testWriteJndi() throws NamingException, IOException {
final String contextPath = "comp/env/";
final Context context = createNiceMock(Context.class);
final NamingEnumeration<Binding> enumeration = createNiceMock(NamingEnumeration.class);
expect(context.listBindings("java:" + contextPath)).andReturn(enumeration).anyTimes();
expect(enumeration.hasMore()).andReturn(true).times(6);
expect(enumeration.next()).andReturn(new Binding("test value", "test value")).once();
expect(enumeration.next())
.andReturn(new Binding("test context", createNiceMock(Context.class))).once();
expect(enumeration.next()).andReturn(new Binding("", "test")).once();
expect(enumeration.next())
.andReturn(new Binding("java:/test context", createNiceMock(Context.class))).once();
expect(enumeration.next()).andReturn(new Binding("test null classname", null, null)).once();
expect(enumeration.next()).andThrow(new NamingException("test")).once();
final ServletContext servletContext = createNiceMock(ServletContext.class);
expect(servletContext.getServerInfo()).andReturn("Mock").anyTimes();
replay(servletContext);
Parameters.initialize(servletContext);
replay(context);
replay(enumeration);
final List<JndiBinding> bindings = JndiBinding.listBindings(context, contextPath);
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final PdfOtherReport pdfOtherReport = new PdfOtherReport(TEST_APP, output);
pdfOtherReport.writeJndi(bindings, contextPath);
assertNotEmptyAndClear(output);
verify(context);
verify(enumeration);
verify(servletContext);
final PdfOtherReport pdfOtherReport2 = new PdfOtherReport(TEST_APP, output);
final List<JndiBinding> bindings2 = Collections.emptyList();
pdfOtherReport2.writeJndi(bindings2, "");
assertNotEmptyAndClear(output);
}
@Override
public Binding nextElement() {
try {
return next();
} catch (NamingException e) {
e.printStackTrace();
return null;
}
}
/**
* Test listBindings method.
*
* @throws Exception when an error occurs.
*/
@Test
public void testListBindings2() throws Exception {
DefaultInitialContext context = new DefaultInitialContext();
Context subContext = context.createSubcontext("subcontext");
subContext.bind("name", "value");
NamingEnumeration<Binding> enumeration = context.listBindings("subcontext");
assertNotNull(enumeration);
assertTrue(enumeration.hasMore());
Binding binding = enumeration.next();
assertEquals(binding.getName(), "name");
assertThrows(NoSuchElementException.class, enumeration::next);
}
/**
* Test listBindings method.
*
* @throws Exception when an error occurs.
*/
@Test
public void testListBindings3() throws Exception {
DefaultInitialContext context = new DefaultInitialContext();
NamingEnumeration<Binding> enumeration = context.listBindings("name");
assertNotNull(enumeration);
enumeration.close();
assertThrows(NamingException.class, enumeration::hasMore);
}
/**
* Test listBindings method.
*
* @throws Exception when an error occurs.
*/
@Test
public void testListBindings4() throws Exception {
DefaultInitialContext context = new DefaultInitialContext();
Context subContext = context.createSubcontext("subcontext");
subContext.bind("name", "value");
NamingEnumeration<Binding> enumeration = context.listBindings("subcontext");
assertNotNull(enumeration);
assertTrue(enumeration.hasMoreElements());
Binding binding = enumeration.nextElement();
assertEquals(binding.getName(), "name");
}
/**
* Test listBindings method.
*
* @throws Exception when an error occurs.
*/
@Test
public void testListBindings5() throws Exception {
DefaultInitialContext context = new DefaultInitialContext();
Context subContext = context.createSubcontext("context1");
subContext.createSubcontext("context2");
NamingEnumeration<Binding> enumeration = context.listBindings("context1/context2");
assertNotNull(enumeration);
}
private void doToHtml(String contextPath) throws NamingException, IOException {
final StringWriter writer = new StringWriter();
final Context context = createNiceMock(Context.class);
final NamingEnumeration<Binding> enumeration = createNiceMock(NamingEnumeration.class);
if (contextPath == null) {
expect(context.listBindings(JNDI_PREFIX)).andReturn(enumeration).anyTimes();
expect(context.listBindings(JNDI_PREFIX + '/')).andReturn(enumeration).anyTimes();
expect(context.listBindings(JNDI_PREFIX + "comp")).andReturn(enumeration).anyTimes();
expect(context.listBindings(JNDI_PREFIX + "comp/")).andReturn(enumeration).anyTimes();
} else {
expect(context.listBindings(JNDI_PREFIX + contextPath)).andReturn(enumeration)
.anyTimes();
expect(context.listBindings(JNDI_PREFIX + contextPath + '/')).andReturn(enumeration)
.anyTimes();
}
expect(enumeration.hasMore()).andReturn(true).times(7);
expect(enumeration.next()).andReturn(new Binding("test value", "test")).once();
expect(enumeration.next()).andReturn(new Binding("test value collection",
Arrays.asList("test collection", "test collection"))).once();
expect(enumeration.next())
.andReturn(new Binding("test context", createNiceMock(Context.class))).once();
expect(enumeration.next()).andReturn(new Binding("", "test")).once();
expect(enumeration.next())
.andReturn(new Binding("java:/test context", createNiceMock(Context.class))).once();
expect(enumeration.next()).andReturn(new Binding("test null classname", null, null)).once();
expect(enumeration.next()).andThrow(new NamingException("test")).once();
replay(context);
replay(enumeration);
final List<JndiBinding> bindings = JndiBinding.listBindings(context, contextPath);
for (final JndiBinding binding : bindings) {
binding.toString();
}
final HtmlJndiTreeReport htmlJndiTreeReport = new HtmlJndiTreeReport(bindings, contextPath,
writer);
htmlJndiTreeReport.toHtml();
verify(context);
verify(enumeration);
assertNotEmptyAndClear(writer);
}
/**
* Lists all bindings for Context with name name. If name is empty then this
* Context is assumed.
*
* @param name name of Context, relative to this Context
* @return NamingEnumeration of all name-object pairs. Each element from the
* enumeration is instance of Binding.
* @throws NoPermissionException if this context has been destroyed
* @throws InvalidNameException if name is CompositeName that spans more than
* one naming system
* @throws NameNotFoundException if name can not be found
* @throws NotContextException component of name is not bound to instance of
* ContextImpl, when name is not an atomic name
* @throws NamingException if any other naming error occurs
*
*/
public NamingEnumeration listBindings(Name name) throws NamingException {
checkIsDestroyed();
Name parsedName = getParsedName(name);
if (parsedName.size() == 0) {
Vector bindings = new Vector();
Iterator iterat = ctxMaps.keySet().iterator();
while (iterat.hasNext()) {
String bindingName = (String) iterat.next();
bindings.addElement(new Binding(bindingName, ctxMaps.get(bindingName)));
}
return new NamingEnumerationImpl(bindings);
}
else {
Object subContext = ctxMaps.get(parsedName.get(0));
if (subContext instanceof Context) {
Name nextLayer = nameParser.parse("");
// getSuffix(1) only apply to name with size() > 1
if (parsedName.size() > 1) {
nextLayer = parsedName.getSuffix(1);
}
return ((Context) subContext).list(nextLayer);
}
if (subContext == null && !ctxMaps.containsKey(parsedName.get(0))) {
throw new NameNotFoundException(LocalizedStrings.ContextImpl_NAME_0_NOT_FOUND.toLocalizedString(name));
}
else {
throw new NotContextException(LocalizedStrings.ContextImpl_EXPECTED_CONTEXT_BUT_FOUND_0.toLocalizedString(subContext));
}
}
}
/**
* Removes all entries from the specified context, including subcontexts.
*
* @param context context ot clear
*/
private void clearContext(Context context)
throws NamingException {
for (NamingEnumeration e = context.listBindings(""); e
.hasMoreElements();) {
Binding binding = (Binding) e.nextElement();
if (binding.getObject() instanceof Context) {
clearContext((Context) binding.getObject());
}
context.unbind(binding.getName());
}
}
@Override
public NamingEnumeration<Binding> listBindings(final Name name) throws NamingException {
throw new UnsupportedOperationException();
}