Java Examples for javax.naming.Binding
The following java examples will help you to understand the usage of javax.naming.Binding. These source code samples are taken from different open source projects.
Example 1
| Project: jndikit-master File: AbstractContextTestCase.java View source code |
public void testSubcontextListBindings() throws AssertionFailedError {
Map map = new HashMap();
map.put("o1", O1);
map.put("o2", O2);
map.put("o3", O3);
Set names = new HashSet();
try {
m_context.createSubcontext("x");
Context context = (Context) m_context.lookup("x");
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
context.bind((String) entry.getKey(), entry.getValue());
}
NamingEnumeration bindings = context.listBindings("");
while (bindings.hasMore()) {
Binding binding = (Binding) bindings.nextElement();
String name = binding.getName();
Object expected = map.get(name);
if (expected == null) {
throw new AssertionFailedError("Invalid binding: name=" + name + ", classname=" + binding.getClassName() + ", object=" + binding.getObject());
}
assertEquals(expected, binding.getObject());
names.add(name);
}
try {
bindings.nextElement();
fail("Expected nextElement() to throw NoSuchElementException");
} catch (final NoSuchElementException nsee) {
}
bindings.close();
} catch (final NamingException ne) {
throw new AssertionFailedError(ne.toString());
}
assertEquals(map.keySet(), names);
}Example 2
| Project: openjdk-master File: CNCtx.java View source code |
/**
* Returns a BindingEnumeration object which has a list of name
* class pairs. Lists the current context if the name is empty.
* @param name JNDI Name
* @exception NamingException all exceptions returned by lookup.
* @return a list of bindings as a BindingEnumeration.
*/
public NamingEnumeration<javax.naming.Binding> listBindings(Name name) throws NamingException {
if (_nc == null)
throw new ConfigurationException("Context does not have a corresponding NamingContext");
if (name.size() > 0) {
try {
java.lang.Object obj = lookup(name);
if (obj instanceof CNCtx) {
return new CNBindingEnumeration((CNCtx) obj, true, _env);
} else {
throw new NotContextException(name.toString());
}
} catch (NamingException ne) {
throw ne;
} catch (BAD_PARAM e) {
NamingException ne = new NotContextException(name.toString());
ne.setRootCause(e);
throw ne;
}
}
return new CNBindingEnumeration(this, false, _env);
}Example 3
| Project: openjdk8-jdk-master File: CNCtx.java View source code |
/**
* Returns a BindingEnumeration object which has a list of name
* class pairs. Lists the current context if the name is empty.
* @param name JNDI Name
* @exception NamingException all exceptions returned by lookup.
* @return a list of bindings as a BindingEnumeration.
*/
public NamingEnumeration<javax.naming.Binding> listBindings(Name name) throws NamingException {
if (_nc == null)
throw new ConfigurationException("Context does not have a corresponding NamingContext");
if (name.size() > 0) {
try {
java.lang.Object obj = lookup(name);
if (obj instanceof CNCtx) {
return new CNBindingEnumeration((CNCtx) obj, true, _env);
} else {
throw new NotContextException(name.toString());
}
} catch (NamingException ne) {
throw ne;
} catch (BAD_PARAM e) {
NamingException ne = new NotContextException(name.toString());
ne.setRootCause(e);
throw ne;
}
}
return new CNBindingEnumeration(this, false, _env);
}Example 4
| Project: crash-master File: JNDIHandler.java View source code |
static List<BindingRenderer.BindingData> get(List<String> filters, Pattern pattern, Boolean verbose, String path, String search, Context ctx) {
List<BindingRenderer.BindingData> data = new ArrayList<BindingRenderer.BindingData>();
try {
if (ctx == null) {
ctx = new InitialContext();
}
if (path.length() > 0) {
path += "/";
}
NamingEnumeration<Binding> e = ctx.listBindings(search);
while (e.hasMoreElements()) {
Binding instance = e.next();
String fullName = path + instance.getName();
if (filters == null || filters.size() == 0 || Utils.instanceOf(instance.getObject().getClass(), filters)) {
if (pattern == null || pattern.matcher(fullName).find()) {
data.add(new BindingRenderer.BindingData(fullName, instance.getClassName(), instance, verbose));
}
}
if (instance.getObject() instanceof Context) {
data.addAll(get(filters, pattern, verbose, fullName, "", (Context) instance.getObject()));
}
}
} catch (Exception e) {
}
return data;
}Example 5
| Project: cyrille-leclerc-master File: JndiUtil.java View source code |
/**
* Recursive method to dump a JNDI tree
*
* @param cx
* @param indent
* for display
*/
private void dumpContext(Context cx, String indent, int depth, PrintWriter out) {
NamingEnumeration enu;
try {
enu = cx.listBindings("");
} catch (NamingException e) {
e.printStackTrace(out);
return;
}
while (enu.hasMoreElements()) {
Binding binding = (Binding) enu.nextElement();
if (binding != null) {
Object o = binding.getObject();
if (o instanceof Context) {
if (depth > this.MAX_DEPTH && !("jdbc".equals(binding.getName()))) {
// Websphere 4.0.4 recursive context work around
out.println(indent + "+- " + binding.getName() + "- recursive context");
} else {
out.println(indent + "+- " + binding.getName());
dumpContext((Context) o, indent + "| ", ++depth, out);
}
} else {
out.println(indent + "+- " + binding.getName() + "=" + (o == null ? "null" : o.getClass().getName()) + "\t" + o);
}
} else {
out.println(indent + "+- #null binding#");
}
}
}Example 6
| Project: InSpider-master File: JndiPropertyPlaceholderConfigurer.java View source code |
@Override
protected void loadProperties(Properties props) throws IOException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.PROVIDER_URL, "jnp://localhost:1099");
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
env.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
InitialContext context = null;
Properties jndiProperties = new Properties();
NamingEnumeration<Binding> bindings;
try {
context = new InitialContext(env);
bindings = context.listBindings("");
while (bindings.hasMore()) {
Binding bd = (Binding) bindings.next();
logger.debug("Property read from JNDI: " + bd.getName() + ": " + bd.getObject());
jndiProperties.put(bd.getName(), bd.getObject());
}
} catch (NamingException ne) {
throw new RuntimeException(ne);
}
props.putAll(jndiProperties);
super.loadProperties(props);
}Example 7
| Project: spring-ldap-master File: LdapTemplate.java View source code |
/**
* Delete all subcontexts including the current one recursively.
*
* @param ctx The context to use for deleting.
* @param name The starting point to delete recursively.
* @throws NamingException if any error occurs
*/
protected void deleteRecursively(DirContext ctx, Name name) {
NamingEnumeration enumeration = null;
try {
enumeration = ctx.listBindings(name);
while (enumeration.hasMore()) {
Binding binding = (Binding) enumeration.next();
LdapName childName = LdapUtils.newLdapName(binding.getName());
childName.addAll(0, name);
deleteRecursively(ctx, childName);
}
ctx.unbind(name);
if (LOG.isDebugEnabled()) {
LOG.debug("Entry " + name + " deleted");
}
} catch (javax.naming.NamingException e) {
throw LdapUtils.convertLdapException(e);
} finally {
try {
enumeration.close();
} catch (Exception e) {
}
}
}Example 8
| Project: JamVM-PH-master File: ListBindingsEnumeration.java View source code |
/**
* Convert from the CORBA binding into the javax.naming binding. As the CORBA
* naming service binding does not contain the object itself, this method
* makes the additional calls to the naming service.
*
* @param binding
* the binding to convert
* @return the value, that must be returned by the {@link #next()}.
*/
public Object convert(Binding binding) {
CPStringBuilder name = new CPStringBuilder();
for (int i = 0; i < binding.binding_name.length; i++) {
name.append(binding.binding_name[i]);
if (i < binding.binding_name.length - 1)
name.append('/');
}
try {
Object object = service.resolve(binding.binding_name);
return new javax.naming.Binding(name.toString(), object);
} catch (Exception e) {
return null;
}
}Example 9
| Project: agile-master File: NamingContextBindingsEnumeration.java View source code |
private Object nextElementInternal() throws NamingException {
NamingEntry entry = (NamingEntry) iterator.next();
// If the entry is a reference, resolve it
if (entry.type == NamingEntry.REFERENCE || entry.type == NamingEntry.LINK_REF) {
try {
// A lookup will resolve the entry
ctx.lookup(new CompositeName(entry.name));
} catch (NamingException e) {
throw e;
} catch (Exception e) {
NamingException ne = new NamingException(e.getMessage());
ne.initCause(e);
throw ne;
}
}
return new Binding(entry.name, entry.value.getClass().getName(), entry.value, true);
}Example 10
| Project: android-servlet-container-master File: WinstoneBindingEnumeration.java View source code |
public Object next() throws NamingException {
if (this.nameEnumeration == null)
throw new NamingException(ContainerJNDIManager.JNDI_RESOURCES.getString("WinstoneBindingEnumeration.AlreadyClosed"));
String name = (String) this.nameEnumeration.nextElement();
Object value = this.bindings.get(name);
try {
value = NamingManager.getObjectInstance(value, new CompositeName().add(name), this.context, this.contextEnvironment);
} catch (Throwable err) {
NamingException errNaming = new NamingException(ContainerJNDIManager.JNDI_RESOURCES.getString("WinstoneBindingEnumeration.FailedToGetInstance"));
errNaming.setRootCause(err);
throw errNaming;
}
return new Binding(name, value);
}Example 11
| Project: HermesJMS-master File: HermesBrowser.java View source code |
/**
* Initialise the underlying Hermes that we're gonna do all our work with
*
* @throws HermesException
* @throws NamingException
*/
public void loadConfig() throws NamingException, HermesException {
Properties props = new Properties();
Context oldContext = context;
HermesConfig oldConfig = null;
props.put(Context.INITIAL_CONTEXT_FACTORY, HermesInitialContextFactory.class.getName());
props.put(Context.PROVIDER_URL, getCurrentConfigURL());
props.put("hermes.loader", JAXBHermesLoader.class.getName());
log.debug("props=" + props);
Iterator listeners = null;
if (loader != null) {
listeners = loader.getConfigurationListeners();
oldConfig = loader.getConfig();
}
if (oldConfig != null) {
Set naming = new HashSet();
naming.addAll(oldConfig.getNaming());
for (Iterator iter = naming.iterator(); iter.hasNext(); ) {
NamingConfig oldNaming = (NamingConfig) iter.next();
loader.notifyNamingRemoved(oldNaming);
}
}
context = new InitialContext(props);
loader = (HermesLoader) context.lookup(HermesContext.LOADER);
if (listeners != null) {
while (listeners.hasNext()) {
loader.addConfigurationListener((HermesConfigurationListener) listeners.next());
}
}
if (oldContext != null) {
for (NamingEnumeration iter = oldContext.listBindings(""); iter.hasMoreElements(); ) {
Binding binding = (Binding) iter.next();
try {
if (oldContext.lookup(binding.getName()) instanceof Hermes) {
Hermes hermes = (Hermes) oldContext.lookup(binding.getName());
Hermes newHermes = null;
try {
newHermes = (Hermes) context.lookup(hermes.getId());
} catch (NamingException e) {
}
if (newHermes == null) {
loader.notifyHermesRemoved(hermes);
}
}
} catch (NamingException ex) {
}
}
}
if (!firstLoad) {
closeWatches();
final ArrayList tmpList = new ArrayList();
tmpList.addAll(loader.getConfig().getWatch());
loader.getConfig().getWatch().clear();
for (Iterator iter = tmpList.iterator(); iter.hasNext(); ) {
WatchConfig wConfig = (WatchConfig) iter.next();
createWatch(wConfig);
}
}
setTitle("HermesJMS - " + TextUtils.crumble(getCurrentConfigURL(), 100));
}Example 12
| Project: tnoodle-master File: WinstoneBindingEnumeration.java View source code |
public Object next() throws NamingException {
if (this.nameEnumeration == null)
throw new NamingException(ContainerJNDIManager.JNDI_RESOURCES.getString("WinstoneBindingEnumeration.AlreadyClosed"));
String name = (String) this.nameEnumeration.nextElement();
Object value = this.bindings.get(name);
try {
value = NamingManager.getObjectInstance(value, new CompositeName().add(name), this.context, this.contextEnvironment);
} catch (Throwable err) {
NamingException errNaming = new NamingException(ContainerJNDIManager.JNDI_RESOURCES.getString("WinstoneBindingEnumeration.FailedToGetInstance"));
errNaming.setRootCause(err);
throw errNaming;
}
return new Binding(name, value);
}Example 13
| Project: Tomcat-master File: ManagerServlet.java View source code |
/**
* List the resources of the given context.
* @param writer Writer to render to
* @param prefix Path for recursion
* @param namingContext The naming context for lookups
* @param type Fully qualified class name of the resource type of interest,
* or <code>null</code> to list resources of all types
* @param clazz The resource class or <code>null</code> to list
* resources of all types
* @param smClient i18n support for current client's locale
*/
protected void printResources(PrintWriter writer, String prefix, javax.naming.Context namingContext, String type, Class<?> clazz, StringManager smClient) {
try {
NamingEnumeration<Binding> items = namingContext.listBindings("");
while (items.hasMore()) {
Binding item = items.next();
if (item.getObject() instanceof javax.naming.Context) {
printResources(writer, prefix + item.getName() + "/", (javax.naming.Context) item.getObject(), type, clazz, smClient);
} else {
if ((clazz != null) && (!(clazz.isInstance(item.getObject())))) {
continue;
}
writer.print(prefix + item.getName());
writer.print(':');
writer.print(item.getClassName());
// Do we want a description if available?
writer.println();
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log("ManagerServlet.resources[" + type + "]", t);
writer.println(smClient.getString("managerServlet.exception", t.toString()));
}
}Example 14
| Project: tomcat60-master File: ManagerServlet.java View source code |
/**
* List the resources of the given context.
*/
protected void printResources(PrintWriter writer, String prefix, javax.naming.Context namingContext, String type, Class clazz) {
try {
NamingEnumeration items = namingContext.listBindings("");
while (items.hasMore()) {
Binding item = (Binding) items.next();
if (item.getObject() instanceof javax.naming.Context) {
printResources(writer, prefix + item.getName() + "/", (javax.naming.Context) item.getObject(), type, clazz);
} else {
if ((clazz != null) && (!(clazz.isInstance(item.getObject())))) {
continue;
}
writer.print(prefix + item.getName());
writer.print(':');
writer.print(item.getClassName());
// Do we want a description if available?
writer.println();
}
}
} catch (Throwable t) {
log("ManagerServlet.resources[" + type + "]", t);
writer.println(sm.getString("managerServlet.exception", t.toString()));
}
}Example 15
| Project: tomcat70-master File: ContextConfig.java View source code |
/**
* Scan the web.xml files that apply to the web application and merge them
* using the rules defined in the spec. For the global web.xml files,
* where there is duplicate configuration, the most specific level wins. ie
* an application's web.xml takes precedence over the host level or global
* web.xml file.
*/
protected void webConfig() {
/*
* Anything and everything can override the global and host defaults.
* This is implemented in two parts
* - Handle as a web fragment that gets added after everything else so
* everything else takes priority
* - Mark Servlets as overridable so SCI configuration can replace
* configuration from the defaults
*/
/*
* The rules for annotation scanning are not as clear-cut as one might
* think. Tomcat implements the following process:
* - As per SRV.1.6.2, Tomcat will scan for annotations regardless of
* which Servlet spec version is declared in web.xml. The EG has
* confirmed this is the expected behaviour.
* - As per http://java.net/jira/browse/SERVLET_SPEC-36, if the main
* web.xml is marked as metadata-complete, JARs are still processed
* for SCIs.
* - If metadata-complete=true and an absolute ordering is specified,
* JARs excluded from the ordering are also excluded from the SCI
* processing.
* - If an SCI has a @HandlesType annotation then all classes (except
* those in JARs excluded from an absolute ordering) need to be
* scanned to check if they match.
*/
Set<WebXml> defaults = new HashSet<WebXml>();
defaults.add(getDefaultWebXmlFragment());
WebXml webXml = createWebXml();
// Parse context level web.xml
InputSource contextWebXml = getContextWebXmlSource();
parseWebXml(contextWebXml, webXml, false);
ServletContext sContext = context.getServletContext();
// Ordering is important here
// Step 1. Identify all the JARs packaged with the application
// If the JARs have a web-fragment.xml it will be parsed at this
// point.
Map<String, WebXml> fragments = processJarsForWebFragments(webXml);
// Step 2. Order the fragments.
Set<WebXml> orderedFragments = null;
orderedFragments = WebXml.orderWebFragments(webXml, fragments, sContext);
// Step 3. Look for ServletContainerInitializer implementations
if (ok) {
processServletContainerInitializers();
}
if (!webXml.isMetadataComplete() || typeInitializerMap.size() > 0) {
// Step 4. Process /WEB-INF/classes for annotations
if (ok) {
// Hack required by Eclipse's "serve modules without
// publishing" feature since this backs WEB-INF/classes by
// multiple locations rather than one.
NamingEnumeration<Binding> listBindings = null;
try {
try {
listBindings = context.getResources().listBindings("/WEB-INF/classes");
} catch (NameNotFoundException ignore) {
}
while (listBindings != null && listBindings.hasMoreElements()) {
Binding binding = listBindings.nextElement();
if (binding.getObject() instanceof FileDirContext) {
File webInfClassDir = new File(((FileDirContext) binding.getObject()).getDocBase());
processAnnotationsFile(webInfClassDir, webXml, webXml.isMetadataComplete());
} else if ("META-INF".equals(binding.getName())) {
// Skip the META-INF directory from any JARs that have been
// expanded in to WEB-INF/classes (sometimes IDEs do this).
} else {
String resource = "/WEB-INF/classes/" + binding.getName();
try {
URL url = sContext.getResource(resource);
processAnnotationsUrl(url, webXml, webXml.isMetadataComplete());
} catch (MalformedURLException e) {
log.error(sm.getString("contextConfig.webinfClassesUrl", resource), e);
}
}
}
} catch (NamingException e) {
log.error(sm.getString("contextConfig.webinfClassesUrl", "/WEB-INF/classes"), e);
}
}
// those fragments we are going to use
if (ok) {
processAnnotations(orderedFragments, webXml.isMetadataComplete());
}
// Cache, if used, is no longer required so clear it
javaClassCache.clear();
}
if (!webXml.isMetadataComplete()) {
// file.
if (ok) {
ok = webXml.merge(orderedFragments);
}
// Step 7. Apply global defaults
// Have to merge defaults before JSP conversion since defaults
// provide JSP servlet definition.
webXml.merge(defaults);
// Step 8. Convert explicitly mentioned jsps to servlets
if (ok) {
convertJsps(webXml);
}
// Step 9. Apply merged web.xml to Context
if (ok) {
webXml.configureContext(context);
}
} else {
webXml.merge(defaults);
convertJsps(webXml);
webXml.configureContext(context);
}
// Step 9a. Make the merged web.xml available to other
// components, specifically Jasper, to save those components
// from having to re-generate it.
// TODO Use a ServletContainerInitializer for Jasper
String mergedWebXml = webXml.toXml();
sContext.setAttribute(org.apache.tomcat.util.scan.Constants.MERGED_WEB_XML, mergedWebXml);
if (context.getLogEffectiveWebXml()) {
log.info("web.xml:\n" + mergedWebXml);
}
// Step 10. Look for static resources packaged in JARs
if (ok) {
// Spec does not define an order.
// Use ordered JARs followed by remaining JARs
Set<WebXml> resourceJars = new LinkedHashSet<WebXml>();
for (WebXml fragment : orderedFragments) {
resourceJars.add(fragment);
}
for (WebXml fragment : fragments.values()) {
if (!resourceJars.contains(fragment)) {
resourceJars.add(fragment);
}
}
processResourceJARs(resourceJars);
// See also StandardContext.resourcesStart() for
// WEB-INF/classes/META-INF/resources configuration
}
// context
if (ok) {
for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializerClassMap.entrySet()) {
if (entry.getValue().isEmpty()) {
context.addServletContainerInitializer(entry.getKey(), null);
} else {
context.addServletContainerInitializer(entry.getKey(), entry.getValue());
}
}
}
}Example 16
| Project: classlib6-master File: CNBindingEnumeration.java View source code |
/**
* Returns the next binding in the list.
* @exception NamingException any naming exception.
*/
public java.lang.Object next() throws NamingException {
if (more && counter >= _bindingList.value.length) {
getMore();
}
if (more && counter < _bindingList.value.length) {
org.omg.CosNaming.Binding bndg = _bindingList.value[counter];
counter++;
return mapBinding(bndg);
} else {
throw new NoSuchElementException();
}
}Example 17
| Project: ikvm-openjdk-master File: CNBindingEnumeration.java View source code |
/**
* Returns the next binding in the list.
* @exception NamingException any naming exception.
*/
public java.lang.Object next() throws NamingException {
if (more && counter >= _bindingList.value.length) {
getMore();
}
if (more && counter < _bindingList.value.length) {
org.omg.CosNaming.Binding bndg = _bindingList.value[counter];
counter++;
return mapBinding(bndg);
} else {
throw new NoSuchElementException();
}
}Example 18
| Project: jdk7u-jdk-master File: CNBindingEnumeration.java View source code |
/**
* Returns the next binding in the list.
* @exception NamingException any naming exception.
*/
public java.lang.Object next() throws NamingException {
if (more && counter >= _bindingList.value.length) {
getMore();
}
if (more && counter < _bindingList.value.length) {
org.omg.CosNaming.Binding bndg = _bindingList.value[counter];
counter++;
return mapBinding(bndg);
} else {
throw new NoSuchElementException();
}
}Example 19
| Project: ManagedRuntimeInitiative-master File: CNBindingEnumeration.java View source code |
/**
* Returns the next binding in the list.
* @exception NamingException any naming exception.
*/
public java.lang.Object next() throws NamingException {
if (more && counter >= _bindingList.value.length) {
getMore();
}
if (more && counter < _bindingList.value.length) {
org.omg.CosNaming.Binding bndg = _bindingList.value[counter];
counter++;
return mapBinding(bndg);
} else {
throw new NoSuchElementException();
}
}Example 20
| Project: wildfly-master File: NamingContext.java View source code |
/** {@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());
}
}Example 21
| Project: activemq-artemis-master File: InVMNamingContext.java View source code |
@Override public NamingEnumeration<Binding> listBindings(String contextName) throws NamingException { contextName = trimSlashes(contextName); if (!"".equals(contextName) && !".".equals(contextName)) { try { return ((InVMNamingContext) lookup(contextName)).listBindings(""); } catch (Throwable t) { throw new NamingException(t.getMessage()); } } List<Binding> l = new ArrayList<>(); for (Object element : map.keySet()) { String name = (String) element; Object object = map.get(name); l.add(new Binding(name, object)); } return new NamingEnumerationImpl<>(l.iterator()); }
Example 22
| Project: activemq-master File: SimpleCachedLDAPAuthorizationMap.java View source code |
/**
* Handler for removed policy entries in the directory.
*
* @param namingEvent
* the removed entry event that occurred
* @param destinationType
* the type of the destination to which the event applies
* @param permissionType
* the permission type to which the event applies
*/
public void objectRemoved(NamingEvent namingEvent, DestinationType destinationType, PermissionType permissionType) {
LOG.debug("Removing object: {}", namingEvent.getOldBinding());
Binding result = namingEvent.getOldBinding();
try {
DefaultAuthorizationMap map = this.map.get();
LdapName name = new LdapName(result.getName());
AuthorizationEntry entry = getEntry(map, name, destinationType);
applyAcl(entry, permissionType, new HashSet<Object>());
} catch (InvalidNameException e) {
LOG.error("Policy not applied! Error parsing DN for object removal for removal of {}", result.getName(), e);
} catch (Exception e) {
LOG.error("Policy not applied! Error processing object removal for removal of {}", result.getName(), e);
}
}Example 23
| Project: bc-java-master File: JndiDANEFetcherFactory.java View source code |
public List getEntries() throws DANEException {
List entries = new ArrayList();
try {
DirContext ctx = new InitialDirContext(env);
NamingEnumeration bindings;
if (domainName.indexOf("_smimecert.") > 0) {
// need to use fully qualified domain name if using named DNS server.
Attributes attrs = ctx.getAttributes(domainName, new String[] { DANE_TYPE });
Attribute smimeAttr = attrs.get(DANE_TYPE);
if (smimeAttr != null) {
addEntries(entries, domainName, smimeAttr);
}
} else {
bindings = ctx.listBindings("_smimecert." + domainName);
while (bindings.hasMore()) {
Binding b = (Binding) bindings.next();
DirContext sc = (DirContext) b.getObject();
String name = sc.getNameInNamespace().substring(1, sc.getNameInNamespace().length() - 1);
// need to use fully qualified domain name if using named DNS server.
Attributes attrs = ctx.getAttributes(name, new String[] { DANE_TYPE });
Attribute smimeAttr = attrs.get(DANE_TYPE);
if (smimeAttr != null) {
String fullName = sc.getNameInNamespace();
String domainName = fullName.substring(1, fullName.length() - 1);
addEntries(entries, domainName, smimeAttr);
}
}
}
return entries;
} catch (NamingException e) {
throw new DANEException("Exception dealing with DNS: " + e.getMessage(), e);
}
}Example 24
| Project: billpayevolutiondemo-master File: NamingContext.java View source code |
/*------------------------------------------------*/
/**
* Bind a name to an object
*
* @param name Name of the object
* @param obj object to bind
* @exception NamingException if an error occurs
*/
public void bind(Name name, Object obj) throws NamingException {
if (isLocked())
throw new NamingException("This context is immutable");
Name cname = toCanonicalName(name);
if (cname == null)
throw new NamingException("Name is null");
if (cname.size() == 0)
throw new NamingException("Name is empty");
//if no subcontexts, just bind it
if (cname.size() == 1) {
//get the object to be bound
Object objToBind = NamingManager.getStateToBind(obj, name, this, null);
// Check for Referenceable
if (objToBind instanceof Referenceable) {
objToBind = ((Referenceable) objToBind).getReference();
}
//anything else we should be able to bind directly
Binding binding = getBinding(cname);
if (binding == null)
addBinding(cname, objToBind);
else
throw new NameAlreadyBoundException(cname.toString());
} else {
if (Log.isDebugEnabled())
Log.debug("Checking for existing binding for name=" + cname + " for first element of name=" + cname.get(0));
//walk down the subcontext hierarchy
//need to ignore trailing empty "" name components
String firstComponent = cname.get(0);
Object ctx = null;
if (firstComponent.equals(""))
ctx = this;
else {
Binding binding = getBinding(firstComponent);
if (binding == null)
throw new NameNotFoundException(firstComponent + " is not bound");
ctx = binding.getObject();
if (ctx instanceof Reference) {
//deference the object
try {
ctx = NamingManager.getObjectInstance(ctx, getNameParser("").parse(firstComponent), this, _env);
} catch (NamingException e) {
throw e;
} catch (Exception e) {
Log.warn("", e);
throw new NamingException(e.getMessage());
}
}
}
if (ctx instanceof Context) {
((Context) ctx).bind(cname.getSuffix(1), obj);
} else
throw new NotContextException("Object bound at " + firstComponent + " is not a Context");
}
}Example 25
| Project: dumpinfo-buildwrapper-plugin-master File: JndiUtils.java View source code |
/**
* Get a sorted map of JNDI bindings.
*
* @return the sorted JNDI bindings
*/
public static SortedMap<String, String> getJndiBindings() {
final SortedMap<String, String> map = new TreeMap<String, String>();
try {
Context ctx = (Context) new InitialContext().lookup("java:comp/env");
NamingEnumeration list = ctx.listBindings("");
while (list.hasMore()) {
Binding item = (Binding) list.next();
map.put(item.getClassName(), item.getName());
// Object o = item.getObject();
// if (o instanceof javax.naming.Context)
// {
// listContext((Context) o, indent + " ");
// }
}
} catch (final NamingException e) {
LOG.log(Level.WARNING, e.getMessage(), e);
}
return map;
}Example 26
| Project: guiceyfruit-master File: JndiProviderTest.java View source code |
public void testJndiProvider() throws Exception {
InputStream in = getClass().getResourceAsStream("jndi-example.properties");
assertNotNull("Cannot find jndi-example.properties on the classpath!", in);
Properties properties = new Properties();
properties.load(in);
InitialContext context = new InitialContext(new Hashtable(properties));
if (verbose) {
NamingEnumeration<Binding> iter = context.listBindings("");
while (iter.hasMore()) {
Binding binding = iter.next();
System.out.println(" " + binding.getName() + " -> " + binding.getObject());
}
}
MyBean foo = assertLookup(context, "foo", MyBean.class);
assertEquals("foo.name", "Foo", foo.getName());
MyBean blah = assertLookup(context, "blah", MyBean.class);
assertEquals("blah.name", "Blah", blah.getName());
// lets check that Cheese has not been instantiated yet
assertEquals("Cheese instance count", 0, Cheese.instanceCount);
Cheese cheese = assertLookup(context, "cheese", Cheese.class);
assertEquals("cheese.type", "Edam", cheese.getType());
assertEquals("Cheese instance count", 1, Cheese.instanceCount);
SomeBean someBean = assertLookup(context, "org.guiceyfruit.jndi.example.SomeBean", SomeBean.class);
assertEquals("someBean.name", "James", someBean.getName());
// lets test we can find the injector with the default name
Injector injector = (Injector) context.lookup("com.google.inject.Injector");
assertNotNull("Injector should not be null", injector);
// lets try using the custom name defined in the properties file
injector = (Injector) context.lookup("myInjector");
assertNotNull("Injector should not be null", injector);
}Example 27
| Project: jboss-messaging-master File: InVMContext.java View source code |
public NamingEnumeration 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 l = new ArrayList();
for (Iterator i = map.keySet().iterator(); i.hasNext(); ) {
String name = (String) i.next();
Object object = map.get(name);
l.add(new Binding(name, object));
}
return new NamingEnumerationImpl(l.iterator());
}Example 28
| Project: org.eclipse.ecr-master File: RepositoryReloader.java View source code |
public static List<Repository> getRepositories() throws NamingException {
List<Repository> list = new LinkedList<Repository>();
InitialContext context = new InitialContext();
// @see NXCore#getRepository
for (String prefix : new String[] { "java:NXRepository", "NXRepository" }) {
NamingEnumeration<Binding> bindings;
try {
bindings = context.listBindings(prefix);
} catch (NamingException e) {
continue;
}
for (NamingEnumeration<Binding> e = bindings; e.hasMore(); ) {
Binding binding = e.nextElement();
String name = binding.getName();
if (binding.isRelative()) {
name = prefix + '/' + name;
}
Object object = context.lookup(name);
if (!(object instanceof Repository)) {
continue;
}
list.add((Repository) object);
}
}
return list;
}Example 29
| Project: penrose-server-master File: NISJNDIClient.java View source code |
public void lookup(String base, RDN rdn, String type, SearchResponse response) throws Exception {
boolean debug = log.isDebugEnabled();
String name;
if ("ipService".equals(type)) {
Object ipServicePort = rdn.get("ipServicePort");
Object ipServiceProtocol = rdn.get("ipServiceProtocol");
name = ipServicePort + "/" + ipServiceProtocol;
} else {
name = rdn.getValue().toString();
}
if (debug) {
log.debug(TextUtil.displaySeparator(70));
log.debug(TextUtil.displayLine("LOOKUP", 70));
log.debug(TextUtil.displayLine(" - Base: " + base, 70));
log.debug(TextUtil.displayLine(" - Name: " + name, 70));
log.debug(TextUtil.displayLine(" - Type: " + type, 70));
log.debug(TextUtil.displaySeparator(70));
}
try {
Context baseContext = (Context) context.lookup("system/" + base);
Object object = null;
if (name.startsWith("/")) {
if (debug)
log.debug("Bindings:");
NamingEnumeration ne = baseContext.listBindings("");
while (ne.hasMore()) {
Binding binding = (Binding) ne.next();
if (debug)
log.debug(" - " + binding.getName() + ": " + binding.getObject());
if (!name.equals(binding.getName()))
continue;
object = binding.getObject();
break;
}
} else {
object = baseContext.lookup(name);
}
if (object == null)
throw LDAP.createException(LDAP.NO_SUCH_OBJECT);
SearchResult searchResult = createSearchResult(base, type, name, object.toString());
if (searchResult == null)
throw LDAP.createException(LDAP.NO_SUCH_OBJECT);
if (debug) {
searchResult.print();
}
response.add(searchResult);
} finally {
response.close();
}
}Example 30
| Project: platform2-master File: LDAPConnection.java View source code |
/*private void dumpDirContext(DirContext dctx, String indent)
throws NamingException {
NamingEnumeration bindings = dctx.listBindings("");
while (bindings.hasMore()) {
Binding bd = (Binding) bindings.next();
DirContext sctx = (DirContext) bd.getObject();
System.out.println(indent + "<B>" + bd.getName() + "</B>");
Attributes a = sctx.getAttributes("");
NamingEnumeration attrlist = a.getAll();
while (attrlist.hasMore()) {
Attribute att = (Attribute) attrlist.next();
System.out.println(indent + " " + att.toString());
}
dumpDirContext(sctx, indent + " ");
}
}*/
public void findZFD() throws NamingException {
SearchControls cons = new SearchControls();
cons.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration searchResults = this.initDirContext.search("", "(ou=zfd)", cons);
while (searchResults.hasMore()) {
Binding bd = (Binding) searchResults.next();
//DirContext sctx = (DirContext) bd.getObject();
System.out.println("bd:" + bd.getName());
//System.out.println("Binding : " + bd.getClassName());
// System.out.println(" " + bd.getName() + " ");
Attributes a = this.initDirContext.getAttributes(bd.getName());
if (a != null) {
NamingEnumeration attrlist = a.getAll();
while (attrlist.hasMore()) {
Attribute att = (Attribute) attrlist.next();
System.out.println("Attribute: " + att.toString());
}
}
}
}Example 31
| Project: tomee-master File: Assembler.java View source code |
@Override
public void destroy() {
final ReentrantLock l = lock;
l.lock();
try {
final SystemInstance systemInstance = SystemInstance.get();
systemInstance.fireEvent(new ContainerSystemPreDestroy());
try {
EjbTimerServiceImpl.shutdown();
} catch (final Exception e) {
logger.warning("Unable to shutdown scheduler", e);
} catch (final NoClassDefFoundError ncdfe) {
}
logger.debug("Undeploying Applications");
final Assembler assembler = this;
final List<AppInfo> deployedApps = new ArrayList<AppInfo>(assembler.getDeployedApplications());
// if an app relies on the previous one it surely relies on it too at undeploy time
Collections.reverse(deployedApps);
for (final AppInfo appInfo : deployedApps) {
try {
assembler.destroyApplication(appInfo.path);
} catch (final UndeployException e) {
logger.error("Undeployment failed: " + appInfo.path, e);
} catch (final NoSuchApplicationException e) {
}
}
final Iterator<ObjectName> it = containerObjectNames.iterator();
final MBeanServer server = LocalMBeanServer.get();
while (it.hasNext()) {
try {
server.unregisterMBean(it.next());
} catch (final Exception ignored) {
}
it.remove();
}
try {
remoteResourceMonitor.unregister();
} catch (final Exception ignored) {
}
NamingEnumeration<Binding> namingEnumeration = null;
try {
namingEnumeration = containerSystem.getJNDIContext().listBindings("openejb/Resource");
} catch (final NamingException ignored) {
}
destroyResourceTree("", namingEnumeration);
try {
containerSystem.getJNDIContext().unbind("java:global");
} catch (final NamingException ignored) {
}
systemInstance.removeComponent(OpenEjbConfiguration.class);
systemInstance.removeComponent(JtaEntityManagerRegistry.class);
systemInstance.removeComponent(TransactionSynchronizationRegistry.class);
systemInstance.removeComponent(EjbResolver.class);
systemInstance.fireEvent(new AssemblerDestroyed());
systemInstance.removeObservers();
if (DestroyableResource.class.isInstance(this.securityService)) {
DestroyableResource.class.cast(this.securityService).destroyResource();
}
if (DestroyableResource.class.isInstance(this.transactionManager)) {
DestroyableResource.class.cast(this.transactionManager).destroyResource();
}
for (final Container c : this.containerSystem.containers()) {
if (DestroyableResource.class.isInstance(c)) {
// TODO: should we use auto closeable there?
DestroyableResource.class.cast(c).destroyResource();
}
}
SystemInstance.reset();
} finally {
l.unlock();
}
}Example 32
| Project: aries-master File: ServiceRegistryContextTest.java View source code |
@Test
public void checkServiceListListBindings() throws NamingException {
BundleMock mock = new BundleMock("scooby.doo", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
InitialContext ctx = new InitialContext();
String className = Runnable.class.getName();
MethodCall run = new MethodCall(Runnable.class, "run");
Runnable t = Skeleton.newMock(Runnable.class);
Runnable t2 = Skeleton.newMock(Runnable.class);
// we don't want the default service
reg.unregister();
ServiceRegistration reg = bc.registerService(className, t, null);
ServiceRegistration reg2 = bc.registerService(className, t2, null);
NamingEnumeration<Binding> ne = ctx.listBindings("osgi:servicelist/" + className);
assertTrue(ne.hasMoreElements());
Binding bnd = ne.nextElement();
assertEquals(String.valueOf(reg.getReference().getProperty(Constants.SERVICE_ID)), bnd.getName());
assertTrue("Class name not correct. Was: " + bnd.getClassName(), bnd.getClassName().contains("Proxy") || bnd.getClassName().contains("EnhancerByCGLIB"));
Runnable r = (Runnable) bnd.getObject();
assertNotNull(r);
r.run();
Skeleton.getSkeleton(t).assertCalledExactNumberOfTimes(run, 1);
Skeleton.getSkeleton(t2).assertNotCalled(run);
assertTrue(ne.hasMoreElements());
bnd = ne.nextElement();
assertEquals(String.valueOf(reg2.getReference().getProperty(Constants.SERVICE_ID)), bnd.getName());
assertTrue("Class name not correct. Was: " + bnd.getClassName(), bnd.getClassName().contains("Proxy") || bnd.getClassName().contains("EnhancerByCGLIB"));
r = (Runnable) bnd.getObject();
assertNotNull(r);
r.run();
Skeleton.getSkeleton(t).assertCalledExactNumberOfTimes(run, 1);
Skeleton.getSkeleton(t2).assertCalledExactNumberOfTimes(run, 1);
assertFalse(ne.hasMoreElements());
}Example 33
| Project: arquillian_deprecated-master File: OpenEJBTestEnricher.java View source code |
//TODO No, no no: we must look up a known location from metadata, not search for a matching type in the whole JNDI tree protected Object lookupRecursive(Class<?> fieldType, javax.naming.Context context, NamingEnumeration<Binding> contextNames) throws Exception { while (contextNames.hasMore()) { Binding contextName = contextNames.nextElement(); Object value = contextName.getObject(); if (javax.naming.Context.class.isInstance(value)) { javax.naming.Context subContext = (javax.naming.Context) value; return lookupRecursive(fieldType, subContext, subContext.listBindings("/")); } else { value = context.lookup(contextName.getName()); if (fieldType.isInstance(value)) { return value; } } } throw new RuntimeException("Could not lookup EJB reference for: " + fieldType); }
Example 34
| Project: beanlet-master File: NamingWireByTypeDependencyInjectionFactoryImpl.java View source code |
public boolean isSupported(ElementAnnotation<? extends Element, Inject> ea) {
boolean supported = false;
if (isWiringModeSupported(ea)) {
Class<?> type = getType(ea);
if (isTypeSupported(type)) {
try {
Set<Binding> bindings = new HashSet<Binding>();
Context context = getInitialContext(configuration, ea.getElement());
synchronized (context) {
addBindings(context, type, bindings);
}
if (bindings.size() == 1) {
supported = true;
} else if (bindings.isEmpty()) {
logger.finest("No jndi binding found for type: '" + type + "'.");
} else {
if (logger.isLoggable(Level.FINE)) {
List<String> names = new ArrayList<String>();
for (Binding binding : bindings) {
names.add(binding.getName());
}
logger.fine("Multiple jndi bindings match type: '" + type + "'. Duplicate bindings: " + names + ".");
}
}
} catch (NamingException e) {
throw new BeanletWiringException(configuration.getComponentName(), ea.getElement().getMember(), e);
}
}
}
return supported;
}Example 35
| Project: dashreports-master File: SetupEditJNDIDataSource.java View source code |
//http://denistek.blogspot.com/2008/08/list-jndi-names.html
private List<String> listJNDINames(Context ctx, String ident) throws NamingException {
List<String> names = new LinkedList<String>();
String indent = "";
NamingEnumeration<Binding> list = ctx.listBindings("");
while (list.hasMore()) {
Binding item = (Binding) list.next();
String className = item.getClassName();
String name = item.getName();
logger.debug(indent + className + " " + name);
Object o = item.getObject();
if (o instanceof javax.naming.Context) {
names.addAll(listJNDINames((Context) o, name));
} else {
names.add(ident + "/" + name);
}
}
return names;
}Example 36
| Project: esxx-master File: DNSHandler.java View source code |
private void addEntries(Document result, DirContext ctx, URI uri, String[] att, boolean recursive) throws URISyntaxException, javax.naming.NamingException {
try {
for (NamingEnumeration<Binding> ne = ctx.listBindings(uri.toString()); ne.hasMore(); ) {
Binding b = ne.next();
URI sub_uri = new URI(uri.getScheme(), uri.getAuthority(), "/" + b.getNameInNamespace(), null, null);
addEntry(result, ctx, sub_uri, att);
if (recursive) {
addEntries(result, ctx, sub_uri, att, true);
}
}
} catch (NullPointerException ex) {
}
}Example 37
| Project: geronimo-master File: BasicContextTest.java View source code |
public void testListBindings() throws NamingException {
NamingEnumeration ne;
ne = envContext.listBindings("");
int count = 0;
while (ne.hasMore()) {
count++;
Binding pair = (Binding) ne.next();
assertTrue(envBinding.containsKey(pair.getName()));
if (!(envBinding.get(pair.getName()) instanceof ReadOnlyContext)) {
assertEquals(pair.getObject(), envBinding.get(pair.getName()));
}
}
assertEquals(envBinding.size(), count);
try {
ne.next();
fail();
} catch (NoSuchElementException e) {
}
try {
ne.nextElement();
fail();
} catch (NoSuchElementException e) {
}
}Example 38
| Project: glassfish-main-master File: StandardContext.java View source code |
/**
* Start this Context component.
*
* @exception LifecycleException if a startup error occurs
*/
@Override
public synchronized void start() throws LifecycleException {
if (started) {
if (log.isLoggable(Level.INFO)) {
String msg = MessageFormat.format(rb.getString(CONTAINER_ALREADY_STARTED_EXCEPTION), logName());
log.log(Level.INFO, msg);
}
return;
}
long startupTimeStart = System.currentTimeMillis();
if (!initialized) {
try {
init();
} catch (Exception ex) {
throw new LifecycleException("Error initializaing ", ex);
}
}
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Starting " + ("".equals(getName()) ? "ROOT" : getName()));
}
// Set JMX object name for proper pipeline registration
preRegisterJMX();
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);
setAvailable(false);
setConfigured(false);
// Add missing components as necessary
if (webappResources == null) {
// (1) Required by Loader
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Configuring default Resources");
}
try {
if ((docBase != null) && (docBase.endsWith(".war")) && (!(new File(docBase).isDirectory())))
setResources(new WARDirContext());
else
setResources(new FileDirContext());
} catch (IllegalArgumentException e) {
throw new LifecycleException(rb.getString(INIT_RESOURCES_EXCEPTION), e);
}
}
resourcesStart();
// Add alternate resources
if (alternateDocBases != null && !alternateDocBases.isEmpty()) {
for (AlternateDocBase alternateDocBase : alternateDocBases) {
String docBase = alternateDocBase.getDocBase();
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Configuring alternate resources");
}
try {
if (docBase != null && docBase.endsWith(".war") && (!(new File(docBase).isDirectory()))) {
setAlternateResources(alternateDocBase, new WARDirContext());
} else {
setAlternateResources(alternateDocBase, new FileDirContext());
}
} catch (IllegalArgumentException e) {
throw new LifecycleException(rb.getString(INIT_RESOURCES_EXCEPTION), e);
}
}
alternateResourcesStart();
}
if (getLoader() == null) {
createLoader();
}
// Initialize character set mapper
getCharsetMapper();
// Post work directory
postWorkDirectory();
// Validate required extensions
try {
ExtensionValidator.validateApplication(getResources(), this);
} catch (IOException ioe) {
String msg = MessageFormat.format(rb.getString(DEPENDENCY_CHECK_EXCEPTION), this);
throw new LifecycleException(msg, ioe);
}
// Reading the "catalina.useNaming" environment variable
String useNamingProperty = System.getProperty("catalina.useNaming");
if ((useNamingProperty != null) && ("false".equals(useNamingProperty))) {
useNaming = false;
}
if (isUseNaming()) {
if (namingContextListener == null) {
namingContextListener = new NamingContextListener();
namingContextListener.setDebug(getDebug());
namingContextListener.setName(getNamingContextName());
addLifecycleListener(namingContextListener);
}
}
// Binding thread
// START OF SJSAS 8.1 6174179
//ClassLoader oldCCL = bindThread();
ClassLoader oldCCL = null;
try {
started = true;
// Start our subordinate components, if any
if ((loader != null) && (loader instanceof Lifecycle))
((Lifecycle) loader).start();
if ((logger != null) && (logger instanceof Lifecycle))
((Lifecycle) logger).start();
// Unbinding thread
// START OF SJSAS 8.1 6174179
//unbindThread(oldCCL);
// END OF SJSAS 8.1 6174179
// Binding thread
oldCCL = bindThread();
if ((realm != null) && (realm instanceof Lifecycle))
((Lifecycle) realm).start();
if ((resources != null) && (resources instanceof Lifecycle))
((Lifecycle) resources).start();
// Start our child containers, if any
for (Container child : findChildren()) {
if (child instanceof Lifecycle) {
((Lifecycle) child).start();
}
}
// if any
if (pipeline instanceof Lifecycle)
((Lifecycle) pipeline).start();
// START SJSAS 8.1 5049111
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(START_EVENT, null);
// END SJSAS 8.1 5049111
} catch (Throwable t) {
throw new LifecycleException(t);
} finally {
// Unbinding thread
unbindThread(oldCCL);
}
if (!getConfigured()) {
String msg = MessageFormat.format(rb.getString(STARTUP_CONTEXT_FAILED_EXCEPTION), getName());
throw new LifecycleException(msg);
}
// Store some required info as ServletContext attributes
postResources();
if (orderedLibs != null && !orderedLibs.isEmpty()) {
getServletContext().setAttribute(ServletContext.ORDERED_LIBS, orderedLibs);
context.setAttributeReadOnly(ServletContext.ORDERED_LIBS);
}
// Initialize associated mapper
mapper.setContext(getPath(), welcomeFiles, resources);
// Binding thread
oldCCL = bindThread();
try {
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);
// Support for pluggability : this has to be done before
// listener events are fired
callServletContainerInitializers();
// Configure and call application event listeners
contextListenerStart();
// Start manager
if ((manager != null) && (manager instanceof Lifecycle)) {
((Lifecycle) getManager()).start();
}
// Start ContainerBackgroundProcessor thread
super.threadStart();
// Configure and call application filters
filterStart();
// Load and initialize all "load on startup" servlets
loadOnStartup(findChildren());
} catch (Throwable t) {
String msg = MessageFormat.format(rb.getString(STARTUP_CONTEXT_FAILED_EXCEPTION), getName());
log.log(Level.SEVERE, msg);
try {
stop();
} catch (Throwable tt) {
log.log(Level.SEVERE, CLEANUP_FAILED_EXCEPTION, tt);
}
throw new LifecycleException(t);
} finally {
// Unbinding thread
unbindThread(oldCCL);
}
// Set available status depending upon startup success
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Startup successfully completed");
}
setAvailable(true);
// JMX registration
registerJMX();
startTimeMillis = System.currentTimeMillis();
startupTime = startTimeMillis - startupTimeStart;
// Send j2ee.state.running notification
if (getObjectName() != null) {
Notification notification = new Notification("j2ee.state.running", this, sequenceNumber++);
sendNotification(notification);
}
// of files on startup
if (getLoader() instanceof WebappLoader) {
((WebappLoader) getLoader()).closeJARs(true);
}
}Example 39
| Project: glassfish-master File: StandardContext.java View source code |
/**
* Start this Context component.
*
* @exception LifecycleException if a startup error occurs
*/
@Override
public synchronized void start() throws LifecycleException {
if (started) {
if (log.isLoggable(Level.INFO)) {
log.log(Level.INFO, LogFacade.CONTAINER_ALREADY_STARTED_EXCEPTION, logName());
}
return;
}
long startupTimeStart = System.currentTimeMillis();
if (!initialized) {
try {
init();
} catch (Exception ex) {
throw new LifecycleException("Error initializaing ", ex);
}
}
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Starting " + ("".equals(getName()) ? "ROOT" : getName()));
}
// Set JMX object name for proper pipeline registration
preRegisterJMX();
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);
setAvailable(false);
setConfigured(false);
// Add missing components as necessary
if (webappResources == null) {
// (1) Required by Loader
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Configuring default Resources");
}
try {
if ((docBase != null) && (docBase.endsWith(".war")) && (!(new File(docBase).isDirectory())))
setResources(new WARDirContext());
else
setResources(new WebDirContext());
} catch (IllegalArgumentException e) {
throw new LifecycleException(rb.getString(LogFacade.INIT_RESOURCES_EXCEPTION), e);
}
}
resourcesStart();
// Add alternate resources
if (alternateDocBases != null && !alternateDocBases.isEmpty()) {
for (AlternateDocBase alternateDocBase : alternateDocBases) {
String docBase = alternateDocBase.getDocBase();
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Configuring alternate resources");
}
try {
if (docBase != null && docBase.endsWith(".war") && (!(new File(docBase).isDirectory()))) {
setAlternateResources(alternateDocBase, new WARDirContext());
} else {
setAlternateResources(alternateDocBase, new FileDirContext());
}
} catch (IllegalArgumentException e) {
throw new LifecycleException(rb.getString(LogFacade.INIT_RESOURCES_EXCEPTION), e);
}
}
alternateResourcesStart();
}
if (getLoader() == null) {
createLoader();
}
// Initialize character set mapper
getCharsetMapper();
// Post work directory
postWorkDirectory();
// Validate required extensions
try {
ExtensionValidator.validateApplication(getResources(), this);
} catch (IOException ioe) {
String msg = MessageFormat.format(rb.getString(LogFacade.DEPENDENCY_CHECK_EXCEPTION), this);
throw new LifecycleException(msg, ioe);
}
// Reading the "catalina.useNaming" environment variable
String useNamingProperty = System.getProperty("catalina.useNaming");
if ((useNamingProperty != null) && ("false".equals(useNamingProperty))) {
useNaming = false;
}
if (isUseNaming()) {
if (namingContextListener == null) {
namingContextListener = new NamingContextListener();
namingContextListener.setDebug(getDebug());
namingContextListener.setName(getNamingContextName());
addLifecycleListener(namingContextListener);
}
}
// Binding thread
// START OF SJSAS 8.1 6174179
//ClassLoader oldCCL = bindThread();
ClassLoader oldCCL = null;
try {
started = true;
// Start our subordinate components, if any
if ((loader != null) && (loader instanceof Lifecycle))
((Lifecycle) loader).start();
if ((logger != null) && (logger instanceof Lifecycle))
((Lifecycle) logger).start();
// Unbinding thread
// START OF SJSAS 8.1 6174179
//unbindThread(oldCCL);
// END OF SJSAS 8.1 6174179
// Binding thread
oldCCL = bindThread();
if ((realm != null) && (realm instanceof Lifecycle))
((Lifecycle) realm).start();
if ((resources != null) && (resources instanceof Lifecycle))
((Lifecycle) resources).start();
// Start our child containers, if any
for (Container child : findChildren()) {
if (child instanceof Lifecycle) {
((Lifecycle) child).start();
}
}
// if any
if (pipeline instanceof Lifecycle)
((Lifecycle) pipeline).start();
// START SJSAS 8.1 5049111
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(START_EVENT, null);
// END SJSAS 8.1 5049111
} catch (Throwable t) {
throw new LifecycleException(t);
} finally {
// Unbinding thread
unbindThread(oldCCL);
}
if (!getConfigured()) {
String msg = MessageFormat.format(rb.getString(LogFacade.STARTUP_CONTEXT_FAILED_EXCEPTION), getName());
throw new LifecycleException(msg);
}
// Store some required info as ServletContext attributes
postResources();
if (orderedLibs != null && !orderedLibs.isEmpty()) {
getServletContext().setAttribute(ServletContext.ORDERED_LIBS, orderedLibs);
context.setAttributeReadOnly(ServletContext.ORDERED_LIBS);
}
// Initialize associated mapper
mapper.setContext(getPath(), welcomeFiles, ContextsAdapterUtility.wrap(resources));
// Binding thread
oldCCL = bindThread();
try {
// Set up the context init params
mergeParameters();
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);
// Support for pluggability : this has to be done before
// listener events are fired
callServletContainerInitializers();
// Configure and call application event listeners
contextListenerStart();
// Start manager
if ((manager != null) && (manager instanceof Lifecycle)) {
((Lifecycle) getManager()).start();
}
// Start ContainerBackgroundProcessor thread
super.threadStart();
// Configure and call application filters
filterStart();
// Load and initialize all "load on startup" servlets
loadOnStartup(findChildren());
} catch (Throwable t) {
log.log(Level.SEVERE, LogFacade.STARTUP_CONTEXT_FAILED_EXCEPTION, getName());
try {
stop();
} catch (Throwable tt) {
log.log(Level.SEVERE, LogFacade.CLEANUP_FAILED_EXCEPTION, tt);
}
throw new LifecycleException(t);
} finally {
// Unbinding thread
unbindThread(oldCCL);
}
// Set available status depending upon startup success
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Startup successfully completed");
}
setAvailable(true);
// JMX registration
registerJMX();
startTimeMillis = System.currentTimeMillis();
startupTime = startTimeMillis - startupTimeStart;
// Send j2ee.state.running notification
if (getObjectName() != null) {
Notification notification = new Notification("j2ee.state.running", this, sequenceNumber++);
sendNotification(notification);
}
// of files on startup
if (getLoader() instanceof WebappLoader) {
((WebappLoader) getLoader()).closeJARs(true);
}
}Example 40
| Project: gst-foundation-master File: VerySimpleInitialContextFactory.java View source code |
@SuppressWarnings("unchecked")
public Context getInitialContext(final Hashtable<?, ?> environment) throws NamingException {
// System.out.println("getInitialContext" + environment);
if (initial == null)
initial = new Context() {
@SuppressWarnings("rawtypes")
Hashtable env = new Hashtable(environment);
Map<String, Object> store = new HashMap<String, Object>();
public Object addToEnvironment(String propName, Object propVal) throws NamingException {
return env.put(propName, propVal);
}
public void bind(Name name, Object obj) throws NamingException {
store.put(name.toString(), obj);
}
public void bind(String name, Object obj) throws NamingException {
store.put(name.toString(), obj);
}
public void close() throws NamingException {
store.clear();
}
public Name composeName(Name name, Name prefix) throws NamingException {
return null;
}
public String composeName(String name, String prefix) throws NamingException {
return null;
}
public Context createSubcontext(Name name) throws NamingException {
return null;
}
public Context createSubcontext(String name) throws NamingException {
return null;
}
public void destroySubcontext(Name name) throws NamingException {
}
public void destroySubcontext(String name) throws NamingException {
}
public Hashtable<?, ?> getEnvironment() throws NamingException {
return env;
}
public String getNameInNamespace() throws NamingException {
return null;
}
public NameParser getNameParser(Name name) throws NamingException {
return null;
}
public NameParser getNameParser(String name) throws NamingException {
return null;
}
public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
return null;
}
public NamingEnumeration<NameClassPair> list(String name) throws NamingException {
return null;
}
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
return null;
}
public NamingEnumeration<Binding> listBindings(String name) throws NamingException {
return null;
}
public Object lookup(Name name) throws NamingException {
return store.get(name.toString());
}
public Object lookup(String name) throws NamingException {
return store.get(name);
}
public Object lookupLink(Name name) throws NamingException {
return null;
}
public Object lookupLink(String name) throws NamingException {
return null;
}
public void rebind(Name name, Object obj) throws NamingException {
store.put(name.toString(), obj);
}
public void rebind(String name, Object obj) throws NamingException {
store.put(name, obj);
}
public Object removeFromEnvironment(String propName) throws NamingException {
return null;
}
public void rename(Name oldName, Name newName) throws NamingException {
}
public void rename(String oldName, String newName) throws NamingException {
}
public void unbind(Name name) throws NamingException {
store.remove(name.toString());
}
public void unbind(String name) throws NamingException {
store.remove(name);
}
};
return initial;
}Example 41
| Project: ironjacamar-master File: JNDIViewer.java View source code |
/**
* List
* @param ctx The context
* @param indent The indentation
* @param buffer The buffer
* @exception Throwable Thrown if an error occurs
*/
private void list(Context ctx, String indent, StringBuilder buffer) throws Throwable {
NamingEnumeration<Binding> bindings = ctx.listBindings("");
while (bindings.hasMore()) {
Binding binding = bindings.next();
String name = binding.getName();
String className = binding.getClassName();
boolean recursive = Context.class.isAssignableFrom(binding.getObject().getClass());
boolean isLinkRef = LinkRef.class.isAssignableFrom(binding.getObject().getClass());
buffer.append(indent + " +- " + name);
if (isLinkRef) {
try {
Object obj = ctx.lookupLink(name);
LinkRef link = (LinkRef) obj;
buffer.append("[link -> ");
buffer.append(link.getLinkName());
buffer.append(']');
} catch (Throwable t) {
log.debugf(t, "Invalid LinkRef for: %s", name);
buffer.append("invalid]");
}
}
buffer.append(" (class: " + className + ")");
buffer.append(NEW_LINE);
if (recursive) {
try {
Object value = ctx.lookup(name);
if (value instanceof Context) {
Context subctx = (Context) value;
list(subctx, indent + " | ", buffer);
} else {
buffer.append(indent + " | NonContext: " + value);
buffer.append(NEW_LINE);
}
} catch (Throwable t) {
buffer.append("Failed to lookup: " + name + ", errmsg=" + t.getMessage());
buffer.append(NEW_LINE);
}
}
}
bindings.close();
}Example 42
| Project: javamelody-master File: TestPdfOtherReport.java View source code |
/** 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);
@SuppressWarnings("unchecked") 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);
}Example 43
| Project: javamelody-mirror-backup-master File: TestPdfOtherReport.java View source code |
/** 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);
@SuppressWarnings("unchecked") 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);
}Example 44
| Project: jetty-hadoop-fix-master File: NamingContext.java View source code |
/*------------------------------------------------*/
/**
* Bind a name to an object
*
* @param name Name of the object
* @param obj object to bind
* @exception NamingException if an error occurs
*/
public void bind(Name name, Object obj) throws NamingException {
if (isLocked())
throw new NamingException("This context is immutable");
Name cname = toCanonicalName(name);
if (cname == null)
throw new NamingException("Name is null");
if (cname.size() == 0)
throw new NamingException("Name is empty");
//if no subcontexts, just bind it
if (cname.size() == 1) {
//get the object to be bound
Object objToBind = NamingManager.getStateToBind(obj, name, this, null);
// Check for Referenceable
if (objToBind instanceof Referenceable) {
objToBind = ((Referenceable) objToBind).getReference();
}
//anything else we should be able to bind directly
Binding binding = getBinding(cname);
if (binding == null)
addBinding(cname, objToBind);
else
throw new NameAlreadyBoundException(cname.toString());
} else {
if (Log.isDebugEnabled())
Log.debug("Checking for existing binding for name=" + cname + " for first element of name=" + cname.get(0));
//walk down the subcontext hierarchy
//need to ignore trailing empty "" name components
String firstComponent = cname.get(0);
Object ctx = null;
if (firstComponent.equals(""))
ctx = this;
else {
Binding binding = getBinding(firstComponent);
if (binding == null)
throw new NameNotFoundException(firstComponent + " is not bound");
ctx = binding.getObject();
if (ctx instanceof Reference) {
//deference the object
try {
ctx = NamingManager.getObjectInstance(ctx, getNameParser("").parse(firstComponent), this, _env);
} catch (NamingException e) {
throw e;
} catch (Exception e) {
Log.warn("", e);
throw new NamingException(e.getMessage());
}
}
}
if (ctx instanceof Context) {
((Context) ctx).bind(cname.getSuffix(1), obj);
} else
throw new NotContextException("Object bound at " + firstComponent + " is not a Context");
}
}Example 45
| Project: jetty-plugin-support-master File: NamingContext.java View source code |
/*------------------------------------------------*/
/**
* Bind a name to an object
*
* @param name Name of the object
* @param obj object to bind
* @exception NamingException if an error occurs
*/
public void bind(Name name, Object obj) throws NamingException {
if (isLocked())
throw new NamingException("This context is immutable");
Name cname = toCanonicalName(name);
if (cname == null)
throw new NamingException("Name is null");
if (cname.size() == 0)
throw new NamingException("Name is empty");
//if no subcontexts, just bind it
if (cname.size() == 1) {
//get the object to be bound
Object objToBind = NamingManager.getStateToBind(obj, name, this, _env);
// Check for Referenceable
if (objToBind instanceof Referenceable) {
objToBind = ((Referenceable) objToBind).getReference();
}
//anything else we should be able to bind directly
addBinding(cname, objToBind);
} else {
if (__log.isDebugEnabled())
__log.debug("Checking for existing binding for name=" + cname + " for first element of name=" + cname.get(0));
//walk down the subcontext hierarchy
//need to ignore trailing empty "" name components
String firstComponent = cname.get(0);
Object ctx = null;
if (firstComponent.equals(""))
ctx = this;
else {
Binding binding = getBinding(firstComponent);
if (binding == null)
throw new NameNotFoundException(firstComponent + " is not bound");
ctx = binding.getObject();
if (ctx instanceof Reference) {
//deference the object
try {
ctx = NamingManager.getObjectInstance(ctx, getNameParser("").parse(firstComponent), this, _env);
} catch (NamingException e) {
throw e;
} catch (Exception e) {
__log.warn("", e);
throw new NamingException(e.getMessage());
}
}
}
if (ctx instanceof Context) {
((Context) ctx).bind(cname.getSuffix(1), obj);
} else
throw new NotContextException("Object bound at " + firstComponent + " is not a Context");
}
}Example 46
| Project: jetty-spdy-master File: NamingContext.java View source code |
/*------------------------------------------------*/
/**
* Bind a name to an object
*
* @param name Name of the object
* @param obj object to bind
* @exception NamingException if an error occurs
*/
public void bind(Name name, Object obj) throws NamingException {
if (isLocked())
throw new NamingException("This context is immutable");
Name cname = toCanonicalName(name);
if (cname == null)
throw new NamingException("Name is null");
if (cname.size() == 0)
throw new NamingException("Name is empty");
//if no subcontexts, just bind it
if (cname.size() == 1) {
//get the object to be bound
Object objToBind = NamingManager.getStateToBind(obj, name, this, _env);
// Check for Referenceable
if (objToBind instanceof Referenceable) {
objToBind = ((Referenceable) objToBind).getReference();
}
//anything else we should be able to bind directly
addBinding(cname, objToBind);
} else {
if (__log.isDebugEnabled())
__log.debug("Checking for existing binding for name=" + cname + " for first element of name=" + cname.get(0));
//walk down the subcontext hierarchy
//need to ignore trailing empty "" name components
String firstComponent = cname.get(0);
Object ctx = null;
if (firstComponent.equals(""))
ctx = this;
else {
Binding binding = getBinding(firstComponent);
if (binding == null)
throw new NameNotFoundException(firstComponent + " is not bound");
ctx = binding.getObject();
if (ctx instanceof Reference) {
//deference the object
try {
ctx = NamingManager.getObjectInstance(ctx, getNameParser("").parse(firstComponent), this, _env);
} catch (NamingException e) {
throw e;
} catch (Exception e) {
__log.warn("", e);
throw new NamingException(e.getMessage());
}
}
}
if (ctx instanceof Context) {
((Context) ctx).bind(cname.getSuffix(1), obj);
} else
throw new NotContextException("Object bound at " + firstComponent + " is not a Context");
}
}Example 47
| Project: jetty.project-master File: NamingContext.java View source code |
/*------------------------------------------------*/
/**
* Bind a name to an object
*
* @param name Name of the object
* @param obj object to bind
* @exception NamingException if an error occurs
*/
public void bind(Name name, Object obj) throws NamingException {
if (isLocked())
throw new NamingException("This context is immutable");
Name cname = toCanonicalName(name);
if (cname == null)
throw new NamingException("Name is null");
if (cname.size() == 0)
throw new NamingException("Name is empty");
//if no subcontexts, just bind it
if (cname.size() == 1) {
//get the object to be bound
Object objToBind = NamingManager.getStateToBind(obj, name, this, _env);
// Check for Referenceable
if (objToBind instanceof Referenceable) {
objToBind = ((Referenceable) objToBind).getReference();
}
//anything else we should be able to bind directly
addBinding(cname, objToBind);
} else {
if (__log.isDebugEnabled())
__log.debug("Checking for existing binding for name=" + cname + " for first element of name=" + cname.get(0));
//walk down the subcontext hierarchy
//need to ignore trailing empty "" name components
String firstComponent = cname.get(0);
Object ctx = null;
if (firstComponent.equals(""))
ctx = this;
else {
Binding binding = getBinding(firstComponent);
if (binding == null) {
if (_supportDeepBinding) {
Name subname = _parser.parse(firstComponent);
Context subctx = new NamingContext((Hashtable) _env.clone(), firstComponent, this, _parser);
addBinding(subname, subctx);
binding = getBinding(subname);
} else {
throw new NameNotFoundException(firstComponent + " is not bound");
}
}
ctx = binding.getObject();
if (ctx instanceof Reference) {
//deference the object
try {
ctx = NamingManager.getObjectInstance(ctx, getNameParser("").parse(firstComponent), this, _env);
} catch (NamingException e) {
throw e;
} catch (Exception e) {
__log.warn("", e);
throw new NamingException(e.getMessage());
}
}
}
if (ctx instanceof Context) {
((Context) ctx).bind(cname.getSuffix(1), obj);
} else
throw new NotContextException("Object bound at " + firstComponent + " is not a Context");
}
}Example 48
| Project: kaleido-repository-master File: StartupListener.java View source code |
/**
* create an {@link EnvironmentInitializer} from the current webapp servlet context
* @param servletContext
* @param applicationInitClass
* @return
*/
public static EnvironmentInitializer createEnvironmentInitializerFrom(ServletContext servletContext, Class<?> applicationInitClass) {
ServletContextProvider.init(servletContext);
// can specify a class from your application, in order to get the version of your application
String applicationClassName = servletContext.getInitParameter(EnvironmentConstants.INITIALIZER_CLASS_PROPERTY);
Class<?> applicationClass = applicationInitClass;
try {
if (!StringHelper.isEmpty(applicationClassName)) {
applicationClass = Class.forName(applicationClassName);
}
} catch (ClassNotFoundException cnfe) {
throw new IllegalArgumentException(EnvironmentConstants.INITIALIZER_CLASS_PROPERTY + "=" + applicationClassName);
} catch (Throwable th) {
LOGGER.error("Error loading class {}", applicationClassName, th);
}
// create the initializer
EnvironmentInitializer initializer = new EnvironmentInitializer(applicationClass);
// load operating system and java system env variables
initializer.init();
// Then, load web application init parameters
@SuppressWarnings("unchecked") Enumeration<String> names = servletContext.getInitParameterNames();
while (names != null && names.hasMoreElements()) {
String name = names.nextElement();
initializer.getEnvironments().put(name, servletContext.getInitParameter(name));
}
// Then load web application environment parameters
try {
Context initCtx = new InitialContext();
NamingEnumeration<Binding> bindingsEnum = initCtx.listBindings("java:comp/env");
while (bindingsEnum.hasMore()) {
Binding binding = bindingsEnum.next();
initializer.getEnvironments().put(binding.getName(), binding.getObject().toString());
LOGGER.info(WebMessageBundle.getMessage("loader.define.environment.parameter", binding.getName(), binding.getObject().toString()));
}
} catch (NamingException e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Loading webapp environment entries is not enabled", e);
} else {
LOGGER.warn("Loading webapp environment entries is not enabled");
}
}
return initializer;
}Example 49
| Project: miso-java-master File: NamingContext.java View source code |
/*------------------------------------------------*/
/**
* Bind a name to an object
*
* @param name Name of the object
* @param obj object to bind
* @exception NamingException if an error occurs
*/
public void bind(Name name, Object obj) throws NamingException {
if (isLocked())
throw new NamingException("This context is immutable");
Name cname = toCanonicalName(name);
if (cname == null)
throw new NamingException("Name is null");
if (cname.size() == 0)
throw new NamingException("Name is empty");
//if no subcontexts, just bind it
if (cname.size() == 1) {
//get the object to be bound
Object objToBind = NamingManager.getStateToBind(obj, name, this, null);
// Check for Referenceable
if (objToBind instanceof Referenceable) {
objToBind = ((Referenceable) objToBind).getReference();
}
//anything else we should be able to bind directly
Binding binding = getBinding(cname);
if (binding == null)
addBinding(cname, objToBind);
else
throw new NameAlreadyBoundException(cname.toString());
} else {
if (Log.isDebugEnabled())
Log.debug("Checking for existing binding for name=" + cname + " for first element of name=" + cname.get(0));
//walk down the subcontext hierarchy
//need to ignore trailing empty "" name components
String firstComponent = cname.get(0);
Object ctx = null;
if (firstComponent.equals(""))
ctx = this;
else {
Binding binding = getBinding(firstComponent);
if (binding == null)
throw new NameNotFoundException(firstComponent + " is not bound");
ctx = binding.getObject();
if (ctx instanceof Reference) {
//deference the object
try {
ctx = NamingManager.getObjectInstance(ctx, getNameParser("").parse(firstComponent), this, _env);
} catch (NamingException e) {
throw e;
} catch (Exception e) {
Log.warn("", e);
throw new NamingException(e.getMessage());
}
}
}
if (ctx instanceof Context) {
((Context) ctx).bind(cname.getSuffix(1), obj);
} else
throw new NotContextException("Object bound at " + firstComponent + " is not a Context");
}
}Example 50
| Project: ocustomer-master File: LdapUtil.java View source code |
/**
* reads the oc ldap groups from ldap server
* @return a list of group names (DN)
* @throws NamingException
*/
public List<String> getLdapGroups() throws NamingException {
List<String> groupList = new ArrayList<String>();
InitialDirContext ctx = new InitialDirContext(env);
NamingEnumeration<Binding> enm = ctx.listBindings(SystemConfiguration.getInstance().getStringValue(SystemConfiguration.Key.LDAP_GROUP_PREFIX));
while (enm.hasMore()) {
Binding b = enm.next();
groupList.add(b.getName());
}
return groupList;
}Example 51
| Project: oodt-master File: RMIContext.java View source code |
public NamingEnumeration listBindings(String name) throws NamingException {
if (name.length() > 0) {
throw new NotContextException("Subcontexts not supported");
}
final Iterator i = getCurrentBindings().iterator();
return new NamingEnumeration() {
public void close() {
}
public boolean hasMore() {
return i.hasNext();
}
public Object next() throws NamingException {
String n = "urn:eda:rmi:" + (String) i.next();
return new javax.naming.Binding(n, lookup(n));
}
public boolean hasMoreElements() {
return hasMore();
}
public Object nextElement() {
Object next = null;
try {
next = next();
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ignore) {
}
return next;
}
};
}Example 52
| Project: openshift-nexus-master File: NamingContext.java View source code |
/*------------------------------------------------*/
/**
* Bind a name to an object
*
* @param name Name of the object
* @param obj object to bind
* @exception NamingException if an error occurs
*/
public void bind(Name name, Object obj) throws NamingException {
if (isLocked())
throw new NamingException("This context is immutable");
Name cname = toCanonicalName(name);
if (cname == null)
throw new NamingException("Name is null");
if (cname.size() == 0)
throw new NamingException("Name is empty");
//if no subcontexts, just bind it
if (cname.size() == 1) {
//get the object to be bound
Object objToBind = NamingManager.getStateToBind(obj, name, this, null);
// Check for Referenceable
if (objToBind instanceof Referenceable) {
objToBind = ((Referenceable) objToBind).getReference();
}
//anything else we should be able to bind directly
Binding binding = getBinding(cname);
if (binding == null)
addBinding(cname, objToBind);
else
throw new NameAlreadyBoundException(cname.toString());
} else {
if (Log.isDebugEnabled())
Log.debug("Checking for existing binding for name=" + cname + " for first element of name=" + cname.get(0));
//walk down the subcontext hierarchy
//need to ignore trailing empty "" name components
String firstComponent = cname.get(0);
Object ctx = null;
if (firstComponent.equals(""))
ctx = this;
else {
Binding binding = getBinding(firstComponent);
if (binding == null)
throw new NameNotFoundException(firstComponent + " is not bound");
ctx = binding.getObject();
if (ctx instanceof Reference) {
//deference the object
try {
ctx = NamingManager.getObjectInstance(ctx, getNameParser("").parse(firstComponent), this, _env);
} catch (NamingException e) {
throw e;
} catch (Exception e) {
Log.warn("", e);
throw new NamingException(e.getMessage());
}
}
}
if (ctx instanceof Context) {
((Context) ctx).bind(cname.getSuffix(1), obj);
} else
throw new NotContextException("Object bound at " + firstComponent + " is not a Context");
}
}Example 53
| Project: Payara-master File: StandardContext.java View source code |
/**
* Start this Context component.
*
* @exception LifecycleException if a startup error occurs
*/
@Override
public synchronized void start() throws LifecycleException {
if (started) {
if (log.isLoggable(Level.INFO)) {
log.log(Level.INFO, CONTAINER_ALREADY_STARTED_EXCEPTION, logName());
}
return;
}
long startupTimeStart = System.currentTimeMillis();
if (!initialized) {
try {
init();
} catch (Exception ex) {
throw new LifecycleException("Error initializaing ", ex);
}
}
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Starting " + ("".equals(getName()) ? "ROOT" : getName()));
}
// Set JMX object name for proper pipeline registration
preRegisterJMX();
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);
setAvailable(false);
setConfigured(false);
// Add missing components as necessary
if (webappResources == null) {
// (1) Required by Loader
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Configuring default Resources");
}
try {
if ((docBase != null) && (docBase.endsWith(".war")) && (!(new File(docBase).isDirectory())))
setResources(new WARDirContext());
else
setResources(new WebDirContext());
} catch (IllegalArgumentException e) {
throw new LifecycleException(rb.getString(INIT_RESOURCES_EXCEPTION), e);
}
}
resourcesStart();
// Add alternate resources
if (alternateDocBases != null && !alternateDocBases.isEmpty()) {
for (AlternateDocBase alternateDocBase : alternateDocBases) {
String docBase = alternateDocBase.getDocBase();
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Configuring alternate resources");
}
try {
if (docBase != null && docBase.endsWith(".war") && (!(new File(docBase).isDirectory()))) {
setAlternateResources(alternateDocBase, new WARDirContext());
} else {
setAlternateResources(alternateDocBase, new FileDirContext());
}
} catch (IllegalArgumentException e) {
throw new LifecycleException(rb.getString(INIT_RESOURCES_EXCEPTION), e);
}
}
alternateResourcesStart();
}
if (getLoader() == null) {
createLoader();
}
// Initialize character set mapper
getCharsetMapper();
// Post work directory
postWorkDirectory();
// Validate required extensions
try {
ExtensionValidator.validateApplication(getResources(), this);
} catch (IOException ioe) {
String msg = MessageFormat.format(rb.getString(DEPENDENCY_CHECK_EXCEPTION), this);
throw new LifecycleException(msg, ioe);
}
// Reading the "catalina.useNaming" environment variable
String useNamingProperty = System.getProperty("catalina.useNaming");
if ((useNamingProperty != null) && ("false".equals(useNamingProperty))) {
useNaming = false;
}
if (isUseNaming()) {
if (namingContextListener == null) {
namingContextListener = new NamingContextListener();
namingContextListener.setDebug(getDebug());
namingContextListener.setName(getNamingContextName());
addLifecycleListener(namingContextListener);
}
}
// Binding thread
// START OF SJSAS 8.1 6174179
//ClassLoader oldCCL = bindThread();
ClassLoader oldCCL = null;
try {
started = true;
// Start our subordinate components, if any
if ((loader != null) && (loader instanceof Lifecycle))
((Lifecycle) loader).start();
if ((logger != null) && (logger instanceof Lifecycle))
((Lifecycle) logger).start();
// Unbinding thread
// START OF SJSAS 8.1 6174179
//unbindThread(oldCCL);
// END OF SJSAS 8.1 6174179
// Binding thread
oldCCL = bindThread();
if ((realm != null) && (realm instanceof Lifecycle))
((Lifecycle) realm).start();
if ((resources != null) && (resources instanceof Lifecycle))
((Lifecycle) resources).start();
// Start our child containers, if any
for (Container child : findChildren()) {
if (child instanceof Lifecycle) {
((Lifecycle) child).start();
}
}
// if any
if (pipeline instanceof Lifecycle)
((Lifecycle) pipeline).start();
// START SJSAS 8.1 5049111
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(START_EVENT, null);
// END SJSAS 8.1 5049111
} catch (Throwable t) {
throw new LifecycleException(t);
} finally {
// Unbinding thread
unbindThread(oldCCL);
}
if (!getConfigured()) {
String msg = MessageFormat.format(rb.getString(STARTUP_CONTEXT_FAILED_EXCEPTION), getName());
throw new LifecycleException(msg);
}
// Store some required info as ServletContext attributes
postResources();
if (orderedLibs != null && !orderedLibs.isEmpty()) {
getServletContext().setAttribute(ServletContext.ORDERED_LIBS, orderedLibs);
context.setAttributeReadOnly(ServletContext.ORDERED_LIBS);
}
// Initialize associated mapper
mapper.setContext(getPath(), welcomeFiles, ContextsAdapterUtility.wrap(resources));
// Binding thread
oldCCL = bindThread();
try {
// Set up the context init params
mergeParameters();
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);
// Support for pluggability : this has to be done before
// listener events are fired
callServletContainerInitializers();
// Configure and call application event listeners
contextListenerStart();
// Start manager
if ((manager != null) && (manager instanceof Lifecycle)) {
((Lifecycle) getManager()).start();
}
// Start ContainerBackgroundProcessor thread
super.threadStart();
// Configure and call application filters
filterStart();
// Load and initialize all "load on startup" servlets
loadOnStartup(findChildren());
} catch (Throwable t) {
log.log(Level.SEVERE, STARTUP_CONTEXT_FAILED_EXCEPTION, getName());
try {
stop();
} catch (Throwable tt) {
log.log(Level.SEVERE, CLEANUP_FAILED_EXCEPTION, tt);
}
throw new LifecycleException(t);
} finally {
// Unbinding thread
unbindThread(oldCCL);
}
// Set available status depending upon startup success
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Startup successfully completed");
}
setAvailable(true);
// JMX registration
registerJMX();
startTimeMillis = System.currentTimeMillis();
startupTime = startTimeMillis - startupTimeStart;
// Send j2ee.state.running notification
if (getObjectName() != null) {
Notification notification = new Notification("j2ee.state.running", this, sequenceNumber++);
sendNotification(notification);
}
// of files on startup
if (getLoader() instanceof WebappLoader) {
((WebappLoader) getLoader()).closeJARs(true);
}
}Example 54
| Project: picketlink-idm-master File: TestBase.java View source code |
// subsequent remove of javax.naming.Context
public void removeContext(Context mainCtx, String name) throws Exception {
Context deleteCtx = (Context) mainCtx.lookup(name);
NamingEnumeration subDirs = mainCtx.listBindings(name);
while (subDirs.hasMoreElements()) {
Binding binding = (Binding) subDirs.nextElement();
String subName = binding.getName();
removeContext(deleteCtx, subName);
}
mainCtx.unbind(name);
}Example 55
| Project: restrepo-master File: NamingContext.java View source code |
/*------------------------------------------------*/
/**
* Bind a name to an object
*
* @param name Name of the object
* @param obj object to bind
* @exception NamingException if an error occurs
*/
public void bind(Name name, Object obj) throws NamingException {
if (isLocked())
throw new NamingException("This context is immutable");
Name cname = toCanonicalName(name);
if (cname == null)
throw new NamingException("Name is null");
if (cname.size() == 0)
throw new NamingException("Name is empty");
//if no subcontexts, just bind it
if (cname.size() == 1) {
//get the object to be bound
Object objToBind = NamingManager.getStateToBind(obj, name, this, null);
// Check for Referenceable
if (objToBind instanceof Referenceable) {
objToBind = ((Referenceable) objToBind).getReference();
}
//anything else we should be able to bind directly
Binding binding = getBinding(cname);
if (binding == null)
addBinding(cname, objToBind);
else
throw new NameAlreadyBoundException(cname.toString());
} else {
if (Log.isDebugEnabled())
Log.debug("Checking for existing binding for name=" + cname + " for first element of name=" + cname.get(0));
//walk down the subcontext hierarchy
//need to ignore trailing empty "" name components
String firstComponent = cname.get(0);
Object ctx = null;
if (firstComponent.equals(""))
ctx = this;
else {
Binding binding = getBinding(firstComponent);
if (binding == null)
throw new NameNotFoundException(firstComponent + " is not bound");
ctx = binding.getObject();
if (ctx instanceof Reference) {
//deference the object
try {
ctx = NamingManager.getObjectInstance(ctx, getNameParser("").parse(firstComponent), this, _env);
} catch (NamingException e) {
throw e;
} catch (Exception e) {
Log.warn("", e);
throw new NamingException(e.getMessage());
}
}
}
if (ctx instanceof Context) {
((Context) ctx).bind(cname.getSuffix(1), obj);
} else
throw new NotContextException("Object bound at " + firstComponent + " is not a Context");
}
}Example 56
| Project: SmallMind-master File: JavaContext.java View source code |
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { ContextNamePair contextNamePair; NamingEnumeration<Binding> internalEnumeration; contextNamePair = nameTranslator.fromInternalNameToExternalContext(internalContext, name); if ((internalEnumeration = contextNamePair.getContext().listBindings(contextNamePair.getName())) != null) { return new JavaNamingEnumeration<Binding>(Binding.class, internalEnumeration, contextNamePair.getContext().getClass(), environment, nameTranslator, nameParser, modifiable); } return null; }
Example 57
| Project: jboss-naming-master File: Protocol.java View source code |
public List<Binding> execute(final Channel channel, final Object... args) throws IOException, NamingException { if (args.length != 1 || !(args[0] instanceof Name)) { throw new IllegalArgumentException("List requires a name argument."); } final Name name = Name.class.cast(args[0]); final ClassLoadingNamedIoFuture<List<Binding>> future = new ClassLoadingNamedIoFuture<List<Binding>>(name, Thread.currentThread().getContextClassLoader()); final int correlationId = reserveNextCorrelationId(future); try { write(channel, new WriteUtil.Writer() { public void write(final DataOutput output) throws IOException { output.writeByte(getCommandId()); output.writeInt(correlationId); final Marshaller marshaller = prepareForMarshalling(output); marshaller.writeByte(NAME); marshaller.writeObject(name); marshaller.finish(); } }); final IoFuture.Status result = future.await(DEFAULT_TIMEOUT, TimeUnit.SECONDS); switch(result) { case FAILED: if (future.getHeldException() != null) { throw future.getHeldException(); } throw future.getException(); case DONE: return future.get(); default: throw new NamingException("Unable to invoke listBindings, status=" + result.toString()); } } catch (NamingException e) { throw e; } catch (Exception e) { throw namingException("Failed to list bindings", e); } finally { releaseCorrelationId(correlationId); } }
Example 58
| Project: arquillian-container-openejb-master File: OpenEJBTestEnricher.java View source code |
//TODO No, no no: we must look up a known location from metadata, not search for a matching type in the whole JNDI tree protected Object lookupRecursive(Class<?> fieldType, Context context, NamingEnumeration<Binding> contextNames) throws Exception { while (contextNames.hasMore()) { Binding contextName = contextNames.nextElement(); Object value = contextName.getObject(); if (Context.class.isInstance(value)) { Context subContext = (Context) value; return lookupRecursive(fieldType, subContext, subContext.listBindings("/")); } else { value = context.lookup(contextName.getName()); if (fieldType.isInstance(value)) { return value; } } } throw new RuntimeException("Could not lookup EJB reference for: " + fieldType); }
Example 59
| Project: directory-server-master File: EventListenerAdapter.java View source code |
/* (non-Javadoc)
* @see org.apache.directory.server.core.event.DirectoryListener#entryAdded(org.apache.directory.server.core.interceptor.context.AddOperationContext)
*/
public void entryAdded(AddOperationContext addContext) {
try {
Binding binding = new Binding(addContext.getDn().getName(), ServerEntryUtils.toBasicAttributes(addContext.getEntry()), false);
NamingEvent evt = new NamingEvent(source, NamingEvent.OBJECT_ADDED, binding, null, addContext);
if (listener instanceof NamespaceChangeListener) {
((NamespaceChangeListener) listener).objectAdded(evt);
}
} catch (Exception e) {
deliverNamingExceptionEvent(e);
}
}Example 60
| Project: geoserver-master File: LDAPTestUtils.java View source code |
/**
* Clear the directory sub-tree starting with the node represented by the
* supplied distinguished name.
*
* @param ctx The DirContext to use for cleaning the tree.
* @param name the distinguished name of the root node.
* @throws NamingException if anything goes wrong removing the sub-tree.
*/
public static void clearSubContexts(DirContext ctx, Name name) throws NamingException {
NamingEnumeration enumeration = null;
try {
enumeration = ctx.listBindings(name);
while (enumeration.hasMore()) {
Binding element = (Binding) enumeration.next();
DistinguishedName childName = new DistinguishedName(element.getName());
childName.prepend((DistinguishedName) name);
try {
ctx.destroySubcontext(childName);
} catch (ContextNotEmptyException e) {
clearSubContexts(ctx, childName);
ctx.destroySubcontext(childName);
}
}
} catch (NamingException e) {
e.printStackTrace();
} finally {
try {
enumeration.close();
} catch (Exception e) {
}
}
}Example 61
| Project: jboss-switchboard-master File: JNDIDependencyItem.java View source code |
@Override
public void objectAdded(NamingEvent namingEvent) {
Binding binding = namingEvent.getNewBinding();
String boundJNDIName = binding.getName();
if (logger.isTraceEnabled()) {
logger.trace(this + " received OBJECT_ADDED event for jndi-name: " + boundJNDIName);
}
if (this.jndiName.equals(boundJNDIName)) {
this.setResolved(true);
logger.debug("Resolved jndi-name dependency: " + this.jndiName + " based on naming event for switchboard: " + this.switchBoard.getId());
}
}Example 62
| Project: mycontainer-master File: MyContainerContext.java View source code |
public void bind(Name name, Object obj) throws NamingException {
String key = name.get(0);
if (name.size() == 1) {
if (elements.containsKey(key)) {
throw new NameAlreadyBoundException(key);
}
if (LOG.isTraceEnabled()) {
LOG.trace("Binding: " + key);
}
elements.put(key, obj);
return;
}
name = name.getSuffix(1);
Object o = lookupInstance(key, name);
if (o != null && !(o instanceof Context)) {
throw new NameAlreadyBoundException(key);
}
Context ctx = (Context) o;
if (ctx == null) {
ctx = createNewSubContext();
if (LOG.isTraceEnabled()) {
LOG.trace("Binding: " + key);
}
elements.put(key, ctx);
}
ctx.bind(name, obj);
}Example 63
| Project: nextop-client-master File: DNSContext.java View source code |
/**
* Lists all names along with corresponding class names contained by given
* context.
*
* @param name
* context name to list
* @param contentSwt
* method will return enumeration of <code>NameClassPair</code>
* objects if this switch is set to
* <code>1<code>; enumeration of <code>Binding</code> if the switch is set
* to <code>2</code>
* @return enumeration of <code>NameClassPair</code> or
* <code>Binding</code> objects
* @throws NamingException
*
* TODO better resolve situation then the zone just has been transferred and
* then ANY_QTYPE request is performed; we could take the result from
* resolver's cache since we are sure the cache is up to date and contains
* absolutely all records from target zone
*/
@SuppressWarnings("unchecked")
private <T> NamingEnumeration<T> list_common(Name name, int contentSwt) throws NamingException {
DNSName nameToList = null;
DNSName altName = null;
CompositeName remainingName = null;
NamingEnumeration<T> result = null;
if (contentSwt != 1 && contentSwt != 2) {
//$NON-NLS-1$
throw new IllegalArgumentException(Messages.getString("jndi.50"));
}
if (name == null) {
//$NON-NLS-1$
throw new NullPointerException(Messages.getString("jndi.2E"));
} else // analyze given name object
if (name.size() == 0) {
// attributes of the current context are requested
nameToList = (DNSName) contextName.clone();
} else if (name instanceof CompositeName) {
// treat the first component of the given composite name as
// a domain name and the rest as a Next Naming System name
String tmp = name.get(0);
// check if it is really a domain name
altName = (DNSName) nameParser.parse(tmp);
// if (!altName.isAbsolute()) {
nameToList = (DNSName) composeName(altName, contextName);
// }
if (name.size() > 1) {
remainingName = (CompositeName) name.getSuffix(1);
}
} else if (name instanceof DNSName) {
// if (!((DNSName) name).isAbsolute()) {
nameToList = (DNSName) composeName(name, contextName);
// } else {
// nameToList = (DNSName) name.clone();
// }
} else {
//$NON-NLS-1$
throw new InvalidNameException(Messages.getString("jndi.4B"));
}
// we should have correct nameToLookFor at this point
if (remainingName != null) {
CannotProceedException cpe = constructCannotProceedException(altName, remainingName);
Context nnsContext = DirectoryManager.getContinuationContext(cpe);
result = (NamingEnumeration<T>) nnsContext.list(remainingName);
} else {
// do the job
try {
Enumeration<ResourceRecord> resEnum = resolver.list(nameToList.toString());
Hashtable<String, T> entries = new Hashtable<String, T>();
DNSContext targetCtx = new DNSContext(this, nameToList);
// collecting direct children
while (resEnum.hasMoreElements()) {
ResourceRecord rr = resEnum.nextElement();
// fullName is an full name of current record
Name curName = nameParser.parse(rr.getName());
// if contains direct child of current context
if (curName.startsWith(nameToList) && curName.size() > nameToList.size()) {
// extract relative name of direct child
String elNameStr = curName.get(nameToList.size());
// if we don't have such child yet
if (!entries.containsKey(elNameStr)) {
Object elObj;
T objToPut = null;
// absolute name of direct child
DNSName elNameAbs = null;
// relative name of direct child
DNSName elNameRel = null;
// context that represents direct child
DNSContext elCtx;
elNameRel = new DNSName();
elNameRel.add(elNameStr);
elNameAbs = (DNSName) nameToList.clone();
elNameAbs.add(elNameStr);
elCtx = new DNSContext(this, elNameAbs);
elObj = DirectoryManager.getObjectInstance(elCtx, elNameRel, targetCtx, environment, null);
switch(contentSwt) {
case 1:
// NameClassPair
objToPut = (T) new NameClassPair(elNameStr, elObj.getClass().getName(), true);
break;
case 2:
// Binding
objToPut = (T) new Binding(elNameStr, elObj, true);
break;
}
entries.put(elNameStr, objToPut);
}
}
}
result = new BasicNamingEnumerator<T>(entries.elements());
} catch (SecurityException e) {
throw e;
} catch (NamingException e) {
throw e;
} catch (Exception e) {
NamingException e2 = new NamingException(e.getMessage());
e2.setRootCause(e);
throw e2;
}
}
return result;
}Example 64
| Project: spring-cloud-sap-master File: HCPRelationalServiceInfoCreatorFactory.java View source code |
/**
* Scans the environment (= JNDI) and searches for a default {@link DataSource} provided automatically by the runtime.
*
* <p>For further information please refer to:
* https://help.hana.ondemand.com/help/frameset.htm?39b1fcd42c864eea9fcdf381a64c13b8.html
* </p>
*
* @return The default {@link DataSource} or <code>null</code> if no default {@link DataSource} was found
* @throws In case of an error finding the default {@link DataSource}
*/
public static DataSource getDefaultDS() throws CloudException {
final String jndiNameRootName = "java:comp/env/jdbc";
final String defaultJndiName = "defaultManagedDataSource";
InitialContext ctx = null;
DataSource retVal = null;
// check if we can obtain a DataSource via JNDI
try {
ctx = new InitialContext();
// loop bindings in context
NamingEnumeration<Binding> bindingEnum = ctx.listBindings(jndiNameRootName);
int i = 0;
boolean defaultNameFound = false;
while (bindingEnum != null && bindingEnum.hasMoreElements()) {
Binding binding = bindingEnum.next();
try {
if (binding.getObject() instanceof DataSource) {
if (LOG.isLoggable(Level.FINE)) {
LOG.logp(Level.FINE, HCPRelationalServiceInfoCreatorFactory.class.getName(), "getDefaultDS", "Found DataSource defined in JNDI: {0}", binding.getName());
}
if (binding.getName().equals(defaultJndiName)) {
defaultNameFound = true;
retVal = (DataSource) binding.getObject();
break;
} else {
if (i == 0) {
retVal = (DataSource) binding.getObject();
}
}
i++;
}
} catch (Exception e) {
}
}
if (// in case we found a single datasource or the default datasource
(i == 1) || defaultNameFound) {
// all is well
} else {
if (i == 0) {
final String msg = MessageFormat.format("No unique service matching {0} found. Expected 1, found {1}", DataSource.class.toString(), 0);
throw new CloudException(msg);
} else {
final String msg = MessageFormat.format("No unique service matching {0} found. Expected exactly 1 or one with name '{1}', but found {2} with other names.", DataSource.class.toString(), defaultJndiName, i);
throw new CloudException(msg);
}
}
} catch (NamingException ex) {
final String msg = MessageFormat.format("No unique service matching {0} found. Expected 1, found {1}", DataSource.class.toString(), 0);
throw new CloudException(msg);
}
return retVal;
}Example 65
| Project: spring-framework-2.5.x-master File: SimpleNamingContextTests.java View source code |
public void testNamingContextBuilder() throws NamingException {
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
InitialContextFactory factory = builder.createInitialContextFactory(null);
DataSource ds = new DriverManagerDataSource();
builder.bind("java:comp/env/jdbc/myds", ds);
Object obj = new Object();
builder.bind("myobject", obj);
Context context1 = factory.getInitialContext(null);
assertTrue("Correct DataSource registered", context1.lookup("java:comp/env/jdbc/myds") == ds);
assertTrue("Correct Object registered", context1.lookup("myobject") == obj);
Hashtable env2 = new Hashtable();
env2.put("key1", "value1");
Context context2 = factory.getInitialContext(env2);
assertTrue("Correct DataSource registered", context2.lookup("java:comp/env/jdbc/myds") == ds);
assertTrue("Correct Object registered", context2.lookup("myobject") == obj);
assertTrue("Correct environment", context2.getEnvironment() != env2);
assertTrue("Correct key1", "value1".equals(context2.getEnvironment().get("key1")));
Integer i = new Integer(0);
context1.rebind("myinteger", i);
String s = "";
context2.bind("mystring", s);
Context context3 = (Context) context2.lookup("");
context3.rename("java:comp/env/jdbc/myds", "jdbc/myds");
context3.unbind("myobject");
assertTrue("Correct environment", context3.getEnvironment() != context2.getEnvironment());
context3.addToEnvironment("key2", "value2");
assertTrue("key2 added", "value2".equals(context3.getEnvironment().get("key2")));
context3.removeFromEnvironment("key1");
assertTrue("key1 removed", context3.getEnvironment().get("key1") == null);
assertTrue("Correct DataSource registered", context1.lookup("jdbc/myds") == ds);
try {
context1.lookup("myobject");
fail("Should have thrown NameNotFoundException");
} catch (NameNotFoundException ex) {
}
assertTrue("Correct Integer registered", context1.lookup("myinteger") == i);
assertTrue("Correct String registered", context1.lookup("mystring") == s);
assertTrue("Correct DataSource registered", context2.lookup("jdbc/myds") == ds);
try {
context2.lookup("myobject");
fail("Should have thrown NameNotFoundException");
} catch (NameNotFoundException ex) {
}
assertTrue("Correct Integer registered", context2.lookup("myinteger") == i);
assertTrue("Correct String registered", context2.lookup("mystring") == s);
assertTrue("Correct DataSource registered", context3.lookup("jdbc/myds") == ds);
try {
context3.lookup("myobject");
fail("Should have thrown NameNotFoundException");
} catch (NameNotFoundException ex) {
}
assertTrue("Correct Integer registered", context3.lookup("myinteger") == i);
assertTrue("Correct String registered", context3.lookup("mystring") == s);
Map bindingMap = new HashMap();
NamingEnumeration bindingEnum = context3.listBindings("");
while (bindingEnum.hasMoreElements()) {
Binding binding = (Binding) bindingEnum.nextElement();
bindingMap.put(binding.getName(), binding);
}
assertTrue("Correct jdbc subcontext", ((Binding) bindingMap.get("jdbc")).getObject() instanceof Context);
assertTrue("Correct jdbc subcontext", SimpleNamingContext.class.getName().equals(((Binding) bindingMap.get("jdbc")).getClassName()));
Context jdbcContext = (Context) context3.lookup("jdbc");
jdbcContext.bind("mydsX", ds);
Map subBindingMap = new HashMap();
NamingEnumeration subBindingEnum = jdbcContext.listBindings("");
while (subBindingEnum.hasMoreElements()) {
Binding binding = (Binding) subBindingEnum.nextElement();
subBindingMap.put(binding.getName(), binding);
}
assertTrue("Correct DataSource registered", ds.equals(((Binding) subBindingMap.get("myds")).getObject()));
assertTrue("Correct DataSource registered", DriverManagerDataSource.class.getName().equals(((Binding) subBindingMap.get("myds")).getClassName()));
assertTrue("Correct DataSource registered", ds.equals(((Binding) subBindingMap.get("mydsX")).getObject()));
assertTrue("Correct DataSource registered", DriverManagerDataSource.class.getName().equals(((Binding) subBindingMap.get("mydsX")).getClassName()));
assertTrue("Correct Integer registered", i.equals(((Binding) bindingMap.get("myinteger")).getObject()));
assertTrue("Correct Integer registered", Integer.class.getName().equals(((Binding) bindingMap.get("myinteger")).getClassName()));
assertTrue("Correct String registered", s.equals(((Binding) bindingMap.get("mystring")).getObject()));
assertTrue("Correct String registered", String.class.getName().equals(((Binding) bindingMap.get("mystring")).getClassName()));
context1.createSubcontext("jdbc").bind("sub/subds", ds);
Map pairMap = new HashMap();
NamingEnumeration pairEnum = context2.list("jdbc");
while (pairEnum.hasMore()) {
NameClassPair pair = (NameClassPair) pairEnum.next();
pairMap.put(pair.getName(), pair.getClassName());
}
assertTrue("Correct sub subcontext", SimpleNamingContext.class.getName().equals(pairMap.get("sub")));
Context subContext = (Context) context2.lookup("jdbc/sub");
Map subPairMap = new HashMap();
NamingEnumeration subPairEnum = subContext.list("");
while (subPairEnum.hasMoreElements()) {
NameClassPair pair = (NameClassPair) subPairEnum.next();
subPairMap.put(pair.getName(), pair.getClassName());
}
assertTrue("Correct DataSource registered", DriverManagerDataSource.class.getName().equals(subPairMap.get("subds")));
assertTrue("Correct DataSource registered", DriverManagerDataSource.class.getName().equals(pairMap.get("myds")));
assertTrue("Correct DataSource registered", DriverManagerDataSource.class.getName().equals(pairMap.get("mydsX")));
pairMap.clear();
pairEnum = context1.list("jdbc/");
while (pairEnum.hasMore()) {
NameClassPair pair = (NameClassPair) pairEnum.next();
pairMap.put(pair.getName(), pair.getClassName());
}
assertTrue("Correct DataSource registered", DriverManagerDataSource.class.getName().equals(pairMap.get("myds")));
assertTrue("Correct DataSource registered", DriverManagerDataSource.class.getName().equals(pairMap.get("mydsX")));
}Example 66
| Project: spring-framework-master File: SimpleNamingContextTests.java View source code |
@Test
public void testNamingContextBuilder() throws NamingException {
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
InitialContextFactory factory = builder.createInitialContextFactory(null);
DataSource ds = new StubDataSource();
builder.bind("java:comp/env/jdbc/myds", ds);
Object obj = new Object();
builder.bind("myobject", obj);
Context context1 = factory.getInitialContext(null);
assertTrue("Correct DataSource registered", context1.lookup("java:comp/env/jdbc/myds") == ds);
assertTrue("Correct Object registered", context1.lookup("myobject") == obj);
Hashtable<String, String> env2 = new Hashtable<>();
env2.put("key1", "value1");
Context context2 = factory.getInitialContext(env2);
assertTrue("Correct DataSource registered", context2.lookup("java:comp/env/jdbc/myds") == ds);
assertTrue("Correct Object registered", context2.lookup("myobject") == obj);
assertTrue("Correct environment", context2.getEnvironment() != env2);
assertTrue("Correct key1", "value1".equals(context2.getEnvironment().get("key1")));
Integer i = new Integer(0);
context1.rebind("myinteger", i);
String s = "";
context2.bind("mystring", s);
Context context3 = (Context) context2.lookup("");
context3.rename("java:comp/env/jdbc/myds", "jdbc/myds");
context3.unbind("myobject");
assertTrue("Correct environment", context3.getEnvironment() != context2.getEnvironment());
context3.addToEnvironment("key2", "value2");
assertTrue("key2 added", "value2".equals(context3.getEnvironment().get("key2")));
context3.removeFromEnvironment("key1");
assertTrue("key1 removed", context3.getEnvironment().get("key1") == null);
assertTrue("Correct DataSource registered", context1.lookup("jdbc/myds") == ds);
try {
context1.lookup("myobject");
fail("Should have thrown NameNotFoundException");
} catch (NameNotFoundException ex) {
}
assertTrue("Correct Integer registered", context1.lookup("myinteger") == i);
assertTrue("Correct String registered", context1.lookup("mystring") == s);
assertTrue("Correct DataSource registered", context2.lookup("jdbc/myds") == ds);
try {
context2.lookup("myobject");
fail("Should have thrown NameNotFoundException");
} catch (NameNotFoundException ex) {
}
assertTrue("Correct Integer registered", context2.lookup("myinteger") == i);
assertTrue("Correct String registered", context2.lookup("mystring") == s);
assertTrue("Correct DataSource registered", context3.lookup("jdbc/myds") == ds);
try {
context3.lookup("myobject");
fail("Should have thrown NameNotFoundException");
} catch (NameNotFoundException ex) {
}
assertTrue("Correct Integer registered", context3.lookup("myinteger") == i);
assertTrue("Correct String registered", context3.lookup("mystring") == s);
Map<String, Binding> bindingMap = new HashMap<>();
NamingEnumeration<?> bindingEnum = context3.listBindings("");
while (bindingEnum.hasMoreElements()) {
Binding binding = (Binding) bindingEnum.nextElement();
bindingMap.put(binding.getName(), binding);
}
assertTrue("Correct jdbc subcontext", bindingMap.get("jdbc").getObject() instanceof Context);
assertTrue("Correct jdbc subcontext", SimpleNamingContext.class.getName().equals(bindingMap.get("jdbc").getClassName()));
Context jdbcContext = (Context) context3.lookup("jdbc");
jdbcContext.bind("mydsX", ds);
Map<String, Binding> subBindingMap = new HashMap<>();
NamingEnumeration<?> subBindingEnum = jdbcContext.listBindings("");
while (subBindingEnum.hasMoreElements()) {
Binding binding = (Binding) subBindingEnum.nextElement();
subBindingMap.put(binding.getName(), binding);
}
assertTrue("Correct DataSource registered", ds.equals(subBindingMap.get("myds").getObject()));
assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(subBindingMap.get("myds").getClassName()));
assertTrue("Correct DataSource registered", ds.equals(subBindingMap.get("mydsX").getObject()));
assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(subBindingMap.get("mydsX").getClassName()));
assertTrue("Correct Integer registered", i.equals(bindingMap.get("myinteger").getObject()));
assertTrue("Correct Integer registered", Integer.class.getName().equals(bindingMap.get("myinteger").getClassName()));
assertTrue("Correct String registered", s.equals(bindingMap.get("mystring").getObject()));
assertTrue("Correct String registered", String.class.getName().equals(bindingMap.get("mystring").getClassName()));
context1.createSubcontext("jdbc").bind("sub/subds", ds);
Map<String, String> pairMap = new HashMap<>();
NamingEnumeration<?> pairEnum = context2.list("jdbc");
while (pairEnum.hasMore()) {
NameClassPair pair = (NameClassPair) pairEnum.next();
pairMap.put(pair.getName(), pair.getClassName());
}
assertTrue("Correct sub subcontext", SimpleNamingContext.class.getName().equals(pairMap.get("sub")));
Context subContext = (Context) context2.lookup("jdbc/sub");
Map<String, String> subPairMap = new HashMap<>();
NamingEnumeration<?> subPairEnum = subContext.list("");
while (subPairEnum.hasMoreElements()) {
NameClassPair pair = (NameClassPair) subPairEnum.next();
subPairMap.put(pair.getName(), pair.getClassName());
}
assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(subPairMap.get("subds")));
assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("myds")));
assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("mydsX")));
pairMap.clear();
pairEnum = context1.list("jdbc/");
while (pairEnum.hasMore()) {
NameClassPair pair = (NameClassPair) pairEnum.next();
pairMap.put(pair.getName(), pair.getClassName());
}
assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("myds")));
assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("mydsX")));
}Example 67
| Project: spring-js-master File: SimpleNamingContextTests.java View source code |
@Test
public void testNamingContextBuilder() throws NamingException {
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
InitialContextFactory factory = builder.createInitialContextFactory(null);
DataSource ds = new StubDataSource();
builder.bind("java:comp/env/jdbc/myds", ds);
Object obj = new Object();
builder.bind("myobject", obj);
Context context1 = factory.getInitialContext(null);
assertTrue("Correct DataSource registered", context1.lookup("java:comp/env/jdbc/myds") == ds);
assertTrue("Correct Object registered", context1.lookup("myobject") == obj);
Hashtable<String, String> env2 = new Hashtable<String, String>();
env2.put("key1", "value1");
Context context2 = factory.getInitialContext(env2);
assertTrue("Correct DataSource registered", context2.lookup("java:comp/env/jdbc/myds") == ds);
assertTrue("Correct Object registered", context2.lookup("myobject") == obj);
assertTrue("Correct environment", context2.getEnvironment() != env2);
assertTrue("Correct key1", "value1".equals(context2.getEnvironment().get("key1")));
Integer i = new Integer(0);
context1.rebind("myinteger", i);
String s = "";
context2.bind("mystring", s);
Context context3 = (Context) context2.lookup("");
context3.rename("java:comp/env/jdbc/myds", "jdbc/myds");
context3.unbind("myobject");
assertTrue("Correct environment", context3.getEnvironment() != context2.getEnvironment());
context3.addToEnvironment("key2", "value2");
assertTrue("key2 added", "value2".equals(context3.getEnvironment().get("key2")));
context3.removeFromEnvironment("key1");
assertTrue("key1 removed", context3.getEnvironment().get("key1") == null);
assertTrue("Correct DataSource registered", context1.lookup("jdbc/myds") == ds);
try {
context1.lookup("myobject");
fail("Should have thrown NameNotFoundException");
} catch (NameNotFoundException ex) {
}
assertTrue("Correct Integer registered", context1.lookup("myinteger") == i);
assertTrue("Correct String registered", context1.lookup("mystring") == s);
assertTrue("Correct DataSource registered", context2.lookup("jdbc/myds") == ds);
try {
context2.lookup("myobject");
fail("Should have thrown NameNotFoundException");
} catch (NameNotFoundException ex) {
}
assertTrue("Correct Integer registered", context2.lookup("myinteger") == i);
assertTrue("Correct String registered", context2.lookup("mystring") == s);
assertTrue("Correct DataSource registered", context3.lookup("jdbc/myds") == ds);
try {
context3.lookup("myobject");
fail("Should have thrown NameNotFoundException");
} catch (NameNotFoundException ex) {
}
assertTrue("Correct Integer registered", context3.lookup("myinteger") == i);
assertTrue("Correct String registered", context3.lookup("mystring") == s);
Map<String, Binding> bindingMap = new HashMap<String, Binding>();
NamingEnumeration<?> bindingEnum = context3.listBindings("");
while (bindingEnum.hasMoreElements()) {
Binding binding = (Binding) bindingEnum.nextElement();
bindingMap.put(binding.getName(), binding);
}
assertTrue("Correct jdbc subcontext", bindingMap.get("jdbc").getObject() instanceof Context);
assertTrue("Correct jdbc subcontext", SimpleNamingContext.class.getName().equals(bindingMap.get("jdbc").getClassName()));
Context jdbcContext = (Context) context3.lookup("jdbc");
jdbcContext.bind("mydsX", ds);
Map<String, Binding> subBindingMap = new HashMap<String, Binding>();
NamingEnumeration<?> subBindingEnum = jdbcContext.listBindings("");
while (subBindingEnum.hasMoreElements()) {
Binding binding = (Binding) subBindingEnum.nextElement();
subBindingMap.put(binding.getName(), binding);
}
assertTrue("Correct DataSource registered", ds.equals(subBindingMap.get("myds").getObject()));
assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(subBindingMap.get("myds").getClassName()));
assertTrue("Correct DataSource registered", ds.equals(subBindingMap.get("mydsX").getObject()));
assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(subBindingMap.get("mydsX").getClassName()));
assertTrue("Correct Integer registered", i.equals(bindingMap.get("myinteger").getObject()));
assertTrue("Correct Integer registered", Integer.class.getName().equals(bindingMap.get("myinteger").getClassName()));
assertTrue("Correct String registered", s.equals(bindingMap.get("mystring").getObject()));
assertTrue("Correct String registered", String.class.getName().equals(bindingMap.get("mystring").getClassName()));
context1.createSubcontext("jdbc").bind("sub/subds", ds);
Map<String, String> pairMap = new HashMap<String, String>();
NamingEnumeration<?> pairEnum = context2.list("jdbc");
while (pairEnum.hasMore()) {
NameClassPair pair = (NameClassPair) pairEnum.next();
pairMap.put(pair.getName(), pair.getClassName());
}
assertTrue("Correct sub subcontext", SimpleNamingContext.class.getName().equals(pairMap.get("sub")));
Context subContext = (Context) context2.lookup("jdbc/sub");
Map<String, String> subPairMap = new HashMap<String, String>();
NamingEnumeration<?> subPairEnum = subContext.list("");
while (subPairEnum.hasMoreElements()) {
NameClassPair pair = (NameClassPair) subPairEnum.next();
subPairMap.put(pair.getName(), pair.getClassName());
}
assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(subPairMap.get("subds")));
assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("myds")));
assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("mydsX")));
pairMap.clear();
pairEnum = context1.list("jdbc/");
while (pairEnum.hasMore()) {
NameClassPair pair = (NameClassPair) pairEnum.next();
pairMap.put(pair.getName(), pair.getClassName());
}
assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("myds")));
assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("mydsX")));
}Example 68
| Project: geode-master File: ContextImpl.java View source code |
/** * 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)); } } }
Example 69
| Project: JBossAS51-master File: NamingRestartUnitTestCase.java View source code |
public void testListBindings() throws Exception {
log.info("Running testListBindings()");
Properties env = createNamingEnvironment(NAMING_PORT);
Context ctx1 = new InitialContext(env);
assertEquals(ObjectBinder.VALUE, ctx1.lookup(ObjectBinder.NAME));
// HOLD ONTO REF to ctx1 so the ref to it does not get gc'ed from
// static map in org.jnp.interfaces.NamingContext.
// Redeploy the naming service
redeployNaming();
Context ctx2 = new InitialContext(env);
try {
NamingEnumeration list = ctx2.listBindings(ObjectBinder.SUBCONTEXT_NAME);
assertNotNull("NamingEnumeration returned", list);
assertTrue("NamingEnumeration has entry", list.hasMoreElements());
Binding binding = (Binding) list.next();
assertEquals(ObjectBinder.NAME, binding.getName());
} catch (NamingException e) {
log.error("Caught NamingException", e);
fail(e.getMessage());
}
// Confirm the original context is still good
assertEquals(ObjectBinder.VALUE, ctx1.lookup(ObjectBinder.NAME));
}Example 70
| Project: JBossAS_5_1_EDG-master File: EJBTestRunnerBean.java View source code |
/** Run the specified test method on the given class name using a Properties
* map built from all java:comp/env entries.
*
* @param className the name of the test class
* @param methodName the name of the test method
* @throws RemoteTestException If any throwable is thrown during
* execution of the method, it is wrapped with a RemoteTestException and
* rethrown.
*/
public void run(String className, String methodName) throws RemoteTestException {
Properties props = new Properties();
try {
InitialContext ctx = new InitialContext();
NamingEnumeration bindings = ctx.listBindings("java:comp/env");
while (bindings.hasMore()) {
Binding binding = (Binding) bindings.next();
String name = binding.getName();
String value = binding.getObject().toString();
props.setProperty(name, value);
}
} catch (NamingException e) {
throw new RemoteTestException(e);
}
run(className, methodName, props);
}Example 71
| Project: liferay-portal-master File: LDAPUserImporterImpl.java View source code |
@Override
public User importUser(long ldapServerId, long companyId, String emailAddress, String screenName) throws Exception {
LdapContext ldapContext = null;
NamingEnumeration<SearchResult> enu = null;
try {
LDAPServerConfiguration ldapServerConfiguration = _ldapServerConfigurationProvider.getConfiguration(companyId, ldapServerId);
String baseDN = ldapServerConfiguration.baseDN();
ldapContext = _portalLDAP.getContext(ldapServerId, companyId);
if (ldapContext == null) {
_log.error("Unable to bind to the LDAP server");
return null;
}
String filter = ldapServerConfiguration.authSearchFilter();
if (_log.isDebugEnabled()) {
_log.debug("Search filter before transformation " + filter);
}
filter = StringUtil.replace(filter, new String[] { "@company_id@", "@email_address@", "@screen_name@" }, new String[] { String.valueOf(companyId), emailAddress, screenName });
LDAPUtil.validateFilter(filter);
if (_log.isDebugEnabled()) {
_log.debug("Search filter after transformation " + filter);
}
Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId);
String userMappingsScreenName = GetterUtil.getString(userMappings.getProperty("screenName"));
userMappingsScreenName = StringUtil.toLowerCase(userMappingsScreenName);
SearchControls searchControls = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, new String[] { userMappingsScreenName }, false, false);
enu = ldapContext.search(baseDN, filter, searchControls);
if (enu.hasMoreElements()) {
if (_log.isDebugEnabled()) {
_log.debug("Search filter returned at least one result");
}
Binding binding = enu.nextElement();
Attributes attributes = _portalLDAP.getUserAttributes(ldapServerId, companyId, ldapContext, _portalLDAP.getNameInNamespace(ldapServerId, companyId, binding));
return importUser(ldapServerId, companyId, ldapContext, attributes, null);
} else {
return null;
}
} catch (Exception e) {
if (_log.isWarnEnabled()) {
_log.warn("Problem accessing LDAP server " + e.getMessage());
}
if (_log.isDebugEnabled()) {
_log.debug(e, e);
}
throw new SystemException("Problem accessing LDAP server " + e.getMessage());
} finally {
if (enu != null) {
enu.close();
}
if (ldapContext != null) {
ldapContext.close();
}
}
}Example 72
| Project: OEPv2-master File: ManagerLdap.java View source code |
public Binding getUser(long companyId, String screenName) throws Exception { LdapContext ctx = getContext(companyId); if (ctx == null) { return null; } String baseDN = PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_BASE_DN); Properties userMappings = getUserMappings(companyId); StringBuilder filter = new StringBuilder(); filter.append(StringPool.OPEN_PARENTHESIS); filter.append(userMappings.getProperty("screenName")); filter.append(StringPool.EQUAL); filter.append(screenName); filter.append(StringPool.CLOSE_PARENTHESIS); SearchControls cons = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, null, false, false); NamingEnumeration<SearchResult> enu = ctx.search(baseDN, filter.toString(), cons); //System.out.println("TTTTTTTTT " + baseDN + " --------- " + filter.toString() + " ==== " + cons + ""); ctx.close(); if (enu.hasMoreElements()) { Binding binding = enu.nextElement(); // System.out.println("TTTTTTTTT " + binding); return binding; } else { return null; } }
Example 73
| Project: aperte-workflow-core-master File: LdapBridge.java View source code |
public static Binding getUser(long ldapServerId, long companyId, String screenName) throws Exception { String postfix = getPropertyPostfix(ldapServerId); LdapContext ldapContext = getContext(ldapServerId, companyId); // if (ldapContext == null) { // return null; // } NamingEnumeration<SearchResult> enu = null; try { String baseDN = PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_BASE_DN + postfix); Properties userMappings = getUserMappings(ldapServerId, companyId); StringBundler filter = new StringBundler(5).append(StringPool.OPEN_PARENTHESIS).append(userMappings.getProperty("screenName")).append(StringPool.EQUAL).append(screenName).append(StringPool.CLOSE_PARENTHESIS); SearchControls searchControls = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, null, false, false); enu = ldapContext.search(baseDN, filter.toString(), searchControls); } catch (Exception e) { throw e; } finally { if (ldapContext != null) { ldapContext.close(); } } if (enu.hasMoreElements()) { Binding binding = enu.nextElement(); enu.close(); return binding; } else { return null; } }
Example 74
| Project: ffmq-master File: FFMQJNDIContext.java View source code |
/*
* (non-Javadoc)
* @see javax.naming.Context#listBindings(javax.naming.Name)
*/
@Override
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
if (name.isEmpty())
return new ListOfBindings(bindings.keys());
Object target = lookup(name);
if (target instanceof Context) {
try {
return ((Context) target).listBindings("");
} finally {
((Context) target).close();
}
}
throw new NotContextException(name + " cannot be listed");
}Example 75
| Project: keycloak-master File: LDAPOperationManager.java View source code |
/**
* <p>
* Destroys a subcontext with the given DN from the LDAP tree.
* </p>
*
* @param dn
*/
private void destroySubcontext(LdapContext context, final String dn) {
try {
NamingEnumeration<Binding> enumeration = null;
try {
enumeration = context.listBindings(dn);
while (enumeration.hasMore()) {
Binding binding = enumeration.next();
String name = binding.getNameInNamespace();
destroySubcontext(context, name);
}
context.unbind(dn);
} finally {
try {
enumeration.close();
} catch (Exception e) {
}
}
} catch (Exception e) {
throw new ModelException("Could not unbind DN [" + dn + "]", e);
}
}Example 76
| Project: nuxeo-tycho-osgi-master File: NamingContext.java View source code |
/**
* Lists all bindings for Context with name <code>name</code>. If
* <code>name</code> is empty, then this Context is assumed.
*
* @param name name of Context, relative to this Context
* @return <code>NamingEnumeration</code> of all name-object pairs. Each
* element from the enumeration is instance of <code>Binding</code>
* @throws NoPermissionException if this context has been destroyed
* @throws InvalidNameException if <code>name</code> is
* <code>CompositeName</code> that spans more than one naming
* system
* @throws NameNotFoundException if <code>name</code> can not be found
* @throws NotContextException component of <code>name</code> is not bound
* to instance of <code>NamingContext</code>, when
* <code>name</code> is not an atomic name
* @throws NamingException if any other naming error occurs
* @see javax.naming.Context#listBindings(javax.naming.Name)
*/
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
checkIsDestroyed();
Name parsedName = getParsedName(name);
if (parsedName.isEmpty()) {
Vector<Binding> bindings = new Vector<Binding>();
for (Object o : objects.keySet()) {
String bindingName = (String) o;
bindings.addElement(new Binding(bindingName, objects.get(bindingName)));
}
return new NamingEnumerationImpl(bindings);
} else {
Object subContext = objects.get(parsedName.get(0));
if (subContext instanceof Context) {
return ((Context) subContext).listBindings(parsedName.getSuffix(1));
}
if (subContext == null && !objects.containsKey(parsedName.get(0))) {
throw new NameNotFoundException("Name " + name + " not found");
} else {
throw new NotContextException("Expected Context but found " + subContext);
}
}
}Example 77
| Project: AndroidMvc-master File: TestEventBus.java View source code |
@Test
public void should_subscribers_methods_inherited_from_system_classes() {
//Arrange
class Event1 {
}
class Event2 {
}
class Event3 {
}
//Test java.xxx
class Subscriber extends java.io.InputStream {
public void onEvent(Event1 event1) {
}
@Override
public int read() throws IOException {
return 0;
}
}
Subscriber sub = new Subscriber();
//Action
EventBusImpl eventBus1 = new EventBusImpl();
eventBus1.register(sub);
//Assert
Assert.assertEquals(eventBus1.subscribers.size(), 1);
Assert.assertTrue(eventBus1.subscribers.keySet().contains(Event1.class));
eventBus1.unregister(sub);
Assert.assertEquals(eventBus1.subscribers.size(), 0);
//Test javax.xxx
class Subscriber2 extends javax.naming.Binding {
public Subscriber2(String name, Object obj) {
super(name, obj);
}
public void onEvent(Event1 event1) {
}
}
Subscriber2 sub2 = new Subscriber2("", "");
//Action
EventBusImpl eventBus2 = new EventBusImpl();
eventBus2.register(sub2);
//Assert
Assert.assertEquals(eventBus2.subscribers.size(), 1);
Assert.assertTrue(eventBus2.subscribers.keySet().contains(Event1.class));
eventBus2.unregister(sub2);
Assert.assertEquals(eventBus2.subscribers.size(), 0);
//Test android.xxx
class Subscriber3 extends android.Phone {
public void onEvent(Event2 event2) {
}
public void onEvent(Event3 event3) {
}
}
Subscriber3 sub3 = new Subscriber3();
EventBusImpl eventBus3 = new EventBusImpl();
eventBus3.register(sub3);
Assert.assertEquals(eventBus3.subscribers.size(), 2);
Assert.assertTrue(eventBus3.subscribers.keySet().contains(Event2.class));
Assert.assertTrue(eventBus3.subscribers.keySet().contains(Event3.class));
eventBus3.unregister(sub3);
Assert.assertEquals(eventBus3.subscribers.size(), 0);
}Example 78
| Project: cemonitor-master File: CEGeneralDirContext.java View source code |
protected void fireEvents(Name target, int type, Object newObj, Object oldObj, Object changeInfo) throws NamingException {
CEEventManager.Tuple[] tuple = eventManager.getListeners(target, type);
for (int r = 0; r < tuple.length; r++) {
Name sourceName = tuple[r].getSource();
EventDirContext evnCtx = (EventDirContext) internalLookup(sourceName, true);
Name itemName = ((Name) target.clone()).getSuffix(sourceName.size());
Binding newBd = null;
Binding oldBd = null;
if (newObj != null)
newBd = new Binding(itemName.toString(), newObj);
if (oldObj != null)
oldBd = new Binding(itemName.toString(), oldObj);
NamingEvent evn = new NamingEvent(evnCtx, type, newBd, oldBd, changeInfo);
logger.debug("Firing " + tuple[r].getSource().toString());
switch(type) {
case NamingEvent.OBJECT_ADDED:
((NamespaceChangeListener) tuple[r].getListener()).objectAdded(evn);
break;
case NamingEvent.OBJECT_REMOVED:
((NamespaceChangeListener) tuple[r].getListener()).objectRemoved(evn);
break;
case NamingEvent.OBJECT_RENAMED:
((NamespaceChangeListener) tuple[r].getListener()).objectRenamed(evn);
break;
case NamingEvent.OBJECT_CHANGED:
((ObjectChangeListener) tuple[r].getListener()).objectChanged(evn);
}
}
}Example 79
| Project: picketlink-master File: LDAPOperationManager.java View source code |
/**
* <p>
* Destroys a subcontext with the given DN from the LDAP tree.
* </p>
*
* @param dn
*/
private void destroySubcontext(LdapContext context, final String dn) {
try {
NamingEnumeration<Binding> enumeration = null;
try {
enumeration = context.listBindings(dn);
while (enumeration.hasMore()) {
Binding binding = enumeration.next();
String name = binding.getNameInNamespace();
destroySubcontext(context, name);
}
context.unbind(dn);
} finally {
try {
enumeration.close();
} catch (Exception e) {
}
}
} catch (Exception e) {
LDAP_STORE_LOGGER.errorf(e, "Could not unbind DN [%s]", dn);
throw new RuntimeException(e);
}
}Example 80
| Project: tuscany-sca-2.x-master File: MockInitialContextFactory.java View source code |
public Context getInitialContext(Hashtable environment) throws NamingException {
return new Context() {
public Object addToEnvironment(String propName, Object propVal) throws NamingException {
// TODO Auto-generated method stub
return null;
}
public void bind(Name name, Object obj) throws NamingException {
// TODO Auto-generated method stub
}
public void bind(String name, Object obj) throws NamingException {
// TODO Auto-generated method stub
}
public void close() throws NamingException {
// TODO Auto-generated method stub
}
public Name composeName(Name name, Name prefix) throws NamingException {
// TODO Auto-generated method stub
return null;
}
public String composeName(String name, String prefix) throws NamingException {
// TODO Auto-generated method stub
return null;
}
public Context createSubcontext(Name name) throws NamingException {
// TODO Auto-generated method stub
return null;
}
public Context createSubcontext(String name) throws NamingException {
// TODO Auto-generated method stub
return null;
}
public void destroySubcontext(Name name) throws NamingException {
// TODO Auto-generated method stub
}
public void destroySubcontext(String name) throws NamingException {
// TODO Auto-generated method stub
}
public Hashtable<?, ?> getEnvironment() throws NamingException {
// TODO Auto-generated method stub
return null;
}
public String getNameInNamespace() throws NamingException {
// TODO Auto-generated method stub
return null;
}
public NameParser getNameParser(Name name) throws NamingException {
// TODO Auto-generated method stub
return null;
}
public NameParser getNameParser(String name) throws NamingException {
// TODO Auto-generated method stub
return null;
}
public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
// TODO Auto-generated method stub
return null;
}
public NamingEnumeration<NameClassPair> list(String name) throws NamingException {
// TODO Auto-generated method stub
return null;
}
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
// TODO Auto-generated method stub
return null;
}
public NamingEnumeration<Binding> listBindings(String name) throws NamingException {
// TODO Auto-generated method stub
return null;
}
public Object lookup(Name name) throws NamingException {
// TODO Auto-generated method stub
return null;
}
public Object lookup(String name) throws NamingException {
if (name.endsWith("ConnectionFactory")) {
return new ConnectionFactory() {
public Connection createConnection() throws JMSException {
return new Connection() {
public void close() throws JMSException {
// TODO Auto-generated method stub
}
public ConnectionConsumer createConnectionConsumer(Destination arg0, String arg1, ServerSessionPool arg2, int arg3) throws JMSException {
// TODO Auto-generated method stub
return null;
}
public ConnectionConsumer createDurableConnectionConsumer(Topic arg0, String arg1, String arg2, ServerSessionPool arg3, int arg4) throws JMSException {
// TODO Auto-generated method stub
return null;
}
public Session createSession(boolean arg0, int arg1) throws JMSException {
// TODO Auto-generated method stub
return new Session() {
public void close() throws JMSException {
// TODO Auto-generated method stub
}
public void commit() throws JMSException {
// TODO Auto-generated method stub
}
public QueueBrowser createBrowser(Queue arg0) throws JMSException {
// TODO Auto-generated method stub
return null;
}
public QueueBrowser createBrowser(Queue arg0, String arg1) throws JMSException {
// TODO Auto-generated method stub
return null;
}
public BytesMessage createBytesMessage() throws JMSException {
// TODO Auto-generated method stub
return new BytesMessage() {
public long getBodyLength() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public boolean readBoolean() throws JMSException {
// TODO Auto-generated method stub
return false;
}
public byte readByte() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public int readBytes(byte[] arg0) throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public int readBytes(byte[] arg0, int arg1) throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public char readChar() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public double readDouble() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public float readFloat() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public int readInt() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public long readLong() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public short readShort() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public String readUTF() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public int readUnsignedByte() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public int readUnsignedShort() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public void reset() throws JMSException {
// TODO Auto-generated method stub
}
public void writeBoolean(boolean arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void writeByte(byte arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void writeBytes(byte[] arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void writeBytes(byte[] arg0, int arg1, int arg2) throws JMSException {
// TODO Auto-generated method stub
}
public void writeChar(char arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void writeDouble(double arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void writeFloat(float arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void writeInt(int arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void writeLong(long arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void writeObject(Object arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void writeShort(short arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void writeUTF(String arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void acknowledge() throws JMSException {
// TODO Auto-generated method stub
}
public void clearBody() throws JMSException {
// TODO Auto-generated method stub
}
public void clearProperties() throws JMSException {
// TODO Auto-generated method stub
}
public boolean getBooleanProperty(String arg0) throws JMSException {
// TODO Auto-generated method stub
return false;
}
public byte getByteProperty(String arg0) throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public double getDoubleProperty(String arg0) throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public float getFloatProperty(String arg0) throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public int getIntProperty(String arg0) throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public String getJMSCorrelationID() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public byte[] getJMSCorrelationIDAsBytes() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public int getJMSDeliveryMode() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public Destination getJMSDestination() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public long getJMSExpiration() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public String getJMSMessageID() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public int getJMSPriority() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public boolean getJMSRedelivered() throws JMSException {
// TODO Auto-generated method stub
return false;
}
public Destination getJMSReplyTo() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public long getJMSTimestamp() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public String getJMSType() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public long getLongProperty(String arg0) throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public Object getObjectProperty(String arg0) throws JMSException {
// TODO Auto-generated method stub
return null;
}
public Enumeration getPropertyNames() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public short getShortProperty(String arg0) throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public String getStringProperty(String arg0) throws JMSException {
// TODO Auto-generated method stub
return null;
}
public boolean propertyExists(String arg0) throws JMSException {
// TODO Auto-generated method stub
return false;
}
public void setBooleanProperty(String arg0, boolean arg1) throws JMSException {
// TODO Auto-generated method stub
}
public void setByteProperty(String arg0, byte arg1) throws JMSException {
// TODO Auto-generated method stub
}
public void setDoubleProperty(String arg0, double arg1) throws JMSException {
// TODO Auto-generated method stub
}
public void setFloatProperty(String arg0, float arg1) throws JMSException {
// TODO Auto-generated method stub
}
public void setIntProperty(String arg0, int arg1) throws JMSException {
// TODO Auto-generated method stub
}
public void setJMSCorrelationID(String arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setJMSCorrelationIDAsBytes(byte[] arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setJMSDeliveryMode(int arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setJMSDestination(Destination arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setJMSExpiration(long arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setJMSMessageID(String arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setJMSPriority(int arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setJMSRedelivered(boolean arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setJMSReplyTo(Destination arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setJMSTimestamp(long arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setJMSType(String arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setLongProperty(String arg0, long arg1) throws JMSException {
// TODO Auto-generated method stub
}
public void setObjectProperty(String arg0, Object arg1) throws JMSException {
// TODO Auto-generated method stub
}
public void setShortProperty(String arg0, short arg1) throws JMSException {
// TODO Auto-generated method stub
}
public void setStringProperty(String arg0, String arg1) throws JMSException {
// TODO Auto-generated method stub
}
};
}
public MessageConsumer createConsumer(Destination arg0) throws JMSException {
// TODO Auto-generated method stub
return null;
}
public MessageConsumer createConsumer(Destination arg0, String arg1) throws JMSException {
// TODO Auto-generated method stub
return null;
}
public MessageConsumer createConsumer(Destination arg0, String arg1, boolean arg2) throws JMSException {
// TODO Auto-generated method stub
return null;
}
public TopicSubscriber createDurableSubscriber(Topic arg0, String arg1) throws JMSException {
// TODO Auto-generated method stub
return null;
}
public TopicSubscriber createDurableSubscriber(Topic arg0, String arg1, String arg2, boolean arg3) throws JMSException {
// TODO Auto-generated method stub
return null;
}
public MapMessage createMapMessage() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public Message createMessage() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public ObjectMessage createObjectMessage() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public ObjectMessage createObjectMessage(Serializable arg0) throws JMSException {
// TODO Auto-generated method stub
return null;
}
public MessageProducer createProducer(Destination arg0) throws JMSException {
return new MessageProducer() {
public void close() throws JMSException {
// TODO Auto-generated method stub
}
public int getDeliveryMode() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public Destination getDestination() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public boolean getDisableMessageID() throws JMSException {
// TODO Auto-generated method stub
return false;
}
public boolean getDisableMessageTimestamp() throws JMSException {
// TODO Auto-generated method stub
return false;
}
public int getPriority() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public long getTimeToLive() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public void send(Message arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void send(Destination arg0, Message arg1) throws JMSException {
// TODO Auto-generated method stub
}
public void send(Message arg0, int arg1, int arg2, long arg3) throws JMSException {
// TODO Auto-generated method stub
}
public void send(Destination arg0, Message arg1, int arg2, int arg3, long arg4) throws JMSException {
// TODO Auto-generated method stub
}
public void setDeliveryMode(int arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setDisableMessageID(boolean arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setDisableMessageTimestamp(boolean arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setPriority(int arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setTimeToLive(long arg0) throws JMSException {
MockInitialContextFactory.timeToLive = Long.valueOf(arg0);
synchronized (MockInitialContextFactory.lock) {
MockInitialContextFactory.lock.notifyAll();
}
}
};
}
public Queue createQueue(String arg0) throws JMSException {
// TODO Auto-generated method stub
return null;
}
public StreamMessage createStreamMessage() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public TemporaryQueue createTemporaryQueue() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public TemporaryTopic createTemporaryTopic() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public TextMessage createTextMessage() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public TextMessage createTextMessage(String arg0) throws JMSException {
// TODO Auto-generated method stub
return null;
}
public Topic createTopic(String arg0) throws JMSException {
// TODO Auto-generated method stub
return null;
}
public int getAcknowledgeMode() throws JMSException {
// TODO Auto-generated method stub
return 0;
}
public MessageListener getMessageListener() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public boolean getTransacted() throws JMSException {
// TODO Auto-generated method stub
return false;
}
public void recover() throws JMSException {
// TODO Auto-generated method stub
}
public void rollback() throws JMSException {
// TODO Auto-generated method stub
}
public void run() {
// TODO Auto-generated method stub
}
public void setMessageListener(MessageListener arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void unsubscribe(String arg0) throws JMSException {
// TODO Auto-generated method stub
}
};
}
public String getClientID() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public ExceptionListener getExceptionListener() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public ConnectionMetaData getMetaData() throws JMSException {
// TODO Auto-generated method stub
return null;
}
public void setClientID(String arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void setExceptionListener(ExceptionListener arg0) throws JMSException {
// TODO Auto-generated method stub
}
public void start() throws JMSException {
// TODO Auto-generated method stub
}
public void stop() throws JMSException {
// TODO Auto-generated method stub
}
};
}
public Connection createConnection(String arg0, String arg1) throws JMSException {
return null;
}
};
} else {
return new Queue() {
public String getQueueName() throws JMSException {
return null;
}
};
}
}
public Object lookupLink(Name name) throws NamingException {
// TODO Auto-generated method stub
return null;
}
public Object lookupLink(String name) throws NamingException {
// TODO Auto-generated method stub
return null;
}
public void rebind(Name name, Object obj) throws NamingException {
// TODO Auto-generated method stub
}
public void rebind(String name, Object obj) throws NamingException {
// TODO Auto-generated method stub
}
public Object removeFromEnvironment(String propName) throws NamingException {
// TODO Auto-generated method stub
return null;
}
public void rename(Name oldName, Name newName) throws NamingException {
// TODO Auto-generated method stub
}
public void rename(String oldName, String newName) throws NamingException {
// TODO Auto-generated method stub
}
public void unbind(Name name) throws NamingException {
// TODO Auto-generated method stub
}
public void unbind(String name) throws NamingException {
// TODO Auto-generated method stub
}
};
}Example 81
| Project: easybeans-master File: ContextImpl.java View source code |
/**
* 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
*/
public NamingEnumeration<Binding> listBindings(final String name) throws NamingException {
logger.debug("listBindings {0}", name);
if (name.length() == 0) {
// List this context
return new BindingsImpl(this.bindings);
}
Object obj = lookup(name);
if (obj instanceof Context) {
return ((Context) obj).listBindings("");
}
logger.error("CompNamingContext: can only list a Context");
throw new NotContextException(name);
}Example 82
| Project: wildfly-elytron-master File: LdapSecurityRealm.java View source code |
private void invokeCacheUpdateListener(NamingEvent evt) {
Binding oldBinding = evt.getOldBinding();
LdapName ldapName;
try {
ldapName = new LdapName(oldBinding.getName());
} catch (InvalidNameException e) {
throw log.ldapInvalidLdapName(oldBinding.getName(), e);
}
ldapName.getRdns().stream().filter( rdn -> rdn.getType().equals(identityMapping.rdnIdentifier)).map( rdn -> new NamePrincipal(rdn.getValue().toString())).findFirst().ifPresent(listener::accept);
}Example 83
| Project: wildfly-security-master File: LdapSecurityRealm.java View source code |
private void invokeCacheUpdateListener(NamingEvent evt) {
Binding oldBinding = evt.getOldBinding();
LdapName ldapName;
try {
ldapName = new LdapName(oldBinding.getName());
} catch (InvalidNameException e) {
throw log.ldapInvalidLdapName(oldBinding.getName(), e);
}
ldapName.getRdns().stream().filter( rdn -> rdn.getType().equals(identityMapping.rdnIdentifier)).map( rdn -> new NamePrincipal(rdn.getValue().toString())).findFirst().ifPresent(listener::accept);
}Example 84
| Project: jsmart-web-master File: BeanHandler.java View source code |
private void initJndiMapping() {
try {
String lookupName = CONFIG.getContent().getEjbLookup();
initialContext = new InitialContext();
// For glassfish implementation
NamingEnumeration<Binding> bindList = initialContext.listBindings("");
while (bindList.hasMore()) {
Binding bind = bindList.next();
if (bind != null && ("java:" + lookupName).equals(bind.getName()) && bind.getObject() instanceof Context) {
lookupInContext((Context) bind.getObject(), "java:" + lookupName);
}
}
// For Jboss implementation
if (jndiMapping.isEmpty()) {
lookupInContext((Context) initialContext.lookup("java:" + lookupName), "java:" + lookupName);
}
} catch (Exception ex) {
LOGGER.log(Level.WARNING, "JNDI for EJB mapping could not be initialized: " + ex.getMessage());
}
}Example 85
| Project: XMPP-for-Android-master File: DNSContext.java View source code |
/** * Lists all names along with corresponding class names contained by given * context. * * @param name * context name to list * @param contentSwt * method will return enumeration of <code>NameClassPair</code> * objects if this switch is set to * <code>1<code>; enumeration of <code>Binding</code> if the * switch is set to <code>2</code> * @return enumeration of <code>NameClassPair</code> or <code>Binding</code> * objects * @throws NamingException * * TODO better resolve situation then the zone just has been * transferred and then ANY_QTYPE request is performed; we could * take the result from resolver's cache since we are sure the * cache is up to date and contains absolutely all records from * target zone */ @SuppressWarnings("unchecked") private <T> NamingEnumeration<T> list_common(Name name, int contentSwt) throws NamingException { DNSName nameToList = null; DNSName altName = null; CompositeName remainingName = null; NamingEnumeration<T> result = null; if (contentSwt != 1 && contentSwt != 2) { //$NON-NLS-1$ throw new IllegalArgumentException(Messages.getString("jndi.50")); } if (name == null) { //$NON-NLS-1$ throw new NullPointerException(Messages.getString("jndi.2E")); } else // analyze given name object if (name.size() == 0) { // attributes of the current context are requested nameToList = (DNSName) contextName.clone(); } else if (name instanceof CompositeName) { // treat the first component of the given composite name as // a domain name and the rest as a Next Naming System name final String tmp = name.get(0); // check if it is really a domain name altName = (DNSName) nameParser.parse(tmp); // if (!altName.isAbsolute()) { nameToList = (DNSName) composeName(altName, contextName); // } if (name.size() > 1) { remainingName = (CompositeName) name.getSuffix(1); } } else if (name instanceof DNSName) { // if (!((DNSName) name).isAbsolute()) { nameToList = (DNSName) composeName(name, contextName); // } else { // nameToList = (DNSName) name.clone(); // } } else { //$NON-NLS-1$ throw new InvalidNameException(Messages.getString("jndi.4B")); } // we should have correct nameToLookFor at this point if (remainingName != null) { final CannotProceedException cpe = constructCannotProceedException(altName, remainingName); final Context nnsContext = NamingManager.getContinuationContext(cpe); result = (NamingEnumeration<T>) nnsContext.list(remainingName); } else { // do the job try { final Enumeration<ResourceRecord> resEnum = resolver.list(nameToList.toString()); final Hashtable<String, T> entries = new Hashtable<String, T>(); final DNSContext targetCtx = new DNSContext(this, nameToList); // collecting direct children while (resEnum.hasMoreElements()) { final ResourceRecord rr = resEnum.nextElement(); // fullName is an full name of current record final Name curName = nameParser.parse(rr.getName()); // if contains direct child of current context if (curName.startsWith(nameToList) && curName.size() > nameToList.size()) { // extract relative name of direct child final String elNameStr = curName.get(nameToList.size()); // if we don't have such child yet if (!entries.containsKey(elNameStr)) { Object elObj; T objToPut = null; // absolute name of direct child DNSName elNameAbs = null; // relative name of direct child DNSName elNameRel = null; // context that represents direct child DNSContext elCtx; elNameRel = new DNSName(); elNameRel.add(elNameStr); elNameAbs = (DNSName) nameToList.clone(); elNameAbs.add(elNameStr); elCtx = new DNSContext(this, elNameAbs); elObj = DirectoryManager.getObjectInstance(elCtx, elNameRel, targetCtx, environment, null); switch(contentSwt) { case 1: // NameClassPair objToPut = (T) new NameClassPair(elNameStr, elObj.getClass().getName(), true); break; case 2: // Binding objToPut = (T) new Binding(elNameStr, elObj, true); break; } entries.put(elNameStr, objToPut); } } } result = new BasicNamingEnumerator<T>(entries.elements()); } catch (final SecurityException e) { throw e; } catch (final NamingException e) { throw e; } catch (final Exception e) { final NamingException e2 = new NamingException(e.getMessage()); e2.setRootCause(e); throw e2; } } return result; }
Example 86
| Project: gda-dal-master File: BindingEnumeration.java View source code |
/*
* @see javax.naming.NamingEnumeration#next()
*/
@Override
public Binding next() throws NamingException {
return nextElement();
}Example 87
| Project: databene-benerator-master File: InitialContextFactoryMock.java View source code |
public NamingEnumeration<Binding> listBindings(Name name) {
return null;
}Example 88
| Project: jain-slee-master File: NotImplementedContext.java View source code |
@Override
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
throw new UnsupportedOperationException();
}Example 89
| Project: quercus-master File: QBindingEnumeration.java View source code |
public Binding next() throws NamingException { String name = (String) _list.get(_index++); Object obj = _context.lookup(name); return new Binding(name, obj, true); }
Example 90
| Project: resin-master File: QBindingEnumeration.java View source code |
public Binding next() throws NamingException { String name = (String) _list.get(_index++); Object obj = _context.lookup(name); return new Binding(name, obj, true); }
Example 91
| Project: cdi-unit-master File: CdiUnitContext.java View source code |
@Override
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
return null;
}Example 92
| Project: dwoss-master File: UnClosableContext.java View source code |
@Override
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
return context.listBindings(name);
}Example 93
| Project: etk-component-master File: SimpleContext.java View source code |
public NamingEnumeration<Binding> listBindings(Name arg0) throws NamingException {
throw new NamingException("Not supported");
}Example 94
| Project: haskell-java-parser-master File: NamingEvent.java View source code |
public Binding getOldBinding() {
return oldBinding;
}Example 95
| Project: jboss-jpa-master File: BrainlessContext.java View source code |
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
throw new OperationNotSupportedException();
}Example 96
| Project: pgjdbc-master File: MiniJndiContext.java View source code |
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
return null;
}Example 97
| Project: seed-master File: JndiContext.java View source code |
@Override
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
throw new UnsupportedOperationException();
}Example 98
| Project: spring-insight-plugins-master File: JndiTestContext.java View source code |
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
return listBindings(StringUtil.safeToString(name));
}Example 99
| Project: transactions-essentials-master File: AtomikosContext.java View source code |
@Override
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
throw new OperationNotSupportedException();
}Example 100
| Project: virgo.web-master File: RedirectingOpenEJBContext.java View source code |
@Override
public NamingEnumeration<Binding> listBindings(Name arg0) throws NamingException {
return getThreadContext().listBindings(arg0);
}Example 101
| Project: workandroid-master File: HelloAndroidActivity.java View source code |
/**
* Called when the connection with the service has been unexpectedly disconnected -
* ie, its process crashed.
* Because it is running in our same process we should never see this happen.
*/
@Override
public void onServiceDisconnected(ComponentName name) {
myBoundService = null;
Toast.makeText(/*Binding.this*/
HelloAndroidActivity.this, R.string.my_service_disconnected, Toast.LENGTH_SHORT).show();
}