public List<Binding> listBindings(final Name name) throws NamingException {
   final ServiceName lookupName = buildServiceName(name);
   final ServiceName floor = boundServices.floor(lookupName);
   if (floor != null && floor.isParentOf(lookupName)) {
     // Parent might be a reference or a link
     Object obj = lookup(name.toString(), floor);
     if (obj != null) throw new RequireResolveException(convert(floor));
   }
   final List<ServiceName> children = listChildren(lookupName);
   final String[] lookupParts = lookupName.toArray();
   final Set<String> childContexts = new HashSet<String>();
   final List<Binding> results = new ArrayList<Binding>();
   for (ServiceName child : children) {
     final String[] childParts = child.toArray();
     if (childParts.length > lookupParts.length + 1) {
       childContexts.add(childParts[lookupParts.length]);
     } else {
       final Object binding = lookup(name.toString(), child);
       results.add(new Binding(childParts[childParts.length - 1], binding));
     }
   }
   for (String contextName : childContexts) {
     results.add(
         new Binding(
             contextName, new NamingContext(((Name) name.clone()).add(contextName), this, null)));
   }
   return results;
 }
  /**
   * Add a name to object binding to this Context.
   *
   * @param name a <code>Name</code> value
   * @param obj an <code>Object</code> value
   */
  public void addBinding(Name name, Object obj) throws NameAlreadyBoundException {
    String key = name.toString();
    Binding binding = new Binding(key, obj);

    Collection<Listener> list = findListeners();

    for (Listener listener : list) {
      binding = listener.bind(this, binding);
      if (binding == null) break;
    }

    if (__log.isDebugEnabled())
      __log.debug(
          "Adding binding with key="
              + key
              + " obj="
              + obj
              + " for context="
              + _name
              + " as "
              + binding);

    if (binding != null) {
      if (_bindings.containsKey(key)) {
        if (_supportDeepBinding) {
          // quietly return (no exception)
          // this is jndi spec breaking, but is added to support broken
          // jndi users like openejb.
          return;
        }
        throw new NameAlreadyBoundException(name.toString());
      }
      _bindings.put(key, binding);
    }
  }
  /** Resolves to nns associated with 'name' and set Continuation to the result. */
  protected void resolve_to_nns_and_continue(Name name, Continuation cont) throws NamingException {
    if (debug > 0) System.out.println("RESOLVE TO NNS AND CONTINUE" + name.toString());

    if (resolve_to_penultimate_context_nns(name, cont)) {
      Object nns = a_lookup_nns(name.toString(), cont);
      if (nns != null) cont.setContinue(nns, name, this);
    }
  }
Exemple #4
0
 protected String getComponentName(Name name) throws NamingException {
   if (name instanceof CompositeName) {
     if (name.size() > 1) {
       throw new InvalidNameException(
           name.toString() + " has more components than namespace can handle");
     }
     return name.get(0);
   } else {
     // compound name
     return name.toString();
   }
 }
  public void bind(final Name name, final Object object) throws NamingException {
    final WriteOwner owner = requireOwner();

    final ServiceName bindName = buildServiceName(name);
    final BindListener listener = new BindListener();

    final BinderService binderService = new BinderService(name.toString());
    final ServiceBuilder<?> builder =
        owner
            .target
            .addService(bindName, binderService)
            .addDependency(
                getServiceNameBase(),
                ServiceBasedNamingStore.class,
                binderService.getNamingStoreInjector())
            .addInjection(
                binderService.getManagedObjectInjector(),
                new ValueManagedReferenceFactory(new ImmediateValue<Object>(object)))
            .setInitialMode(ServiceController.Mode.ACTIVE)
            .addListener(listener);
    for (ServiceName dependency : owner.dependencies) {
      builder.addDependency(dependency);
    }
    builder.install();
    try {
      listener.await();
    } catch (Exception e) {
      throw namingException("Failed to bind [" + object + "] at location [" + bindName + "]", e);
    }
  }
  /**
   * Resolves to penultimate context named by 'name'. Returns true if penultimate context has been
   * reached (i.e. name only has one atomic component left). Returns false otherwise, and sets
   * Continuation to parts of name not yet resolved.
   */
  protected boolean resolve_to_penultimate_context(Name name, Continuation cont)
      throws NamingException {
    String target = name.toString();

    if (debug > 0) System.out.println("RESOLVE TO PENULTIMATE" + target);

    StringHeadTail ht = c_parseComponent(target, cont);
    String tail = ht.getTail();
    String head = ht.getHead();
    if (head == null) {
      // something is wrong; no name at all
      InvalidNameException e = new InvalidNameException();
      throw cont.fillInException(e);
    }

    if (!isEmpty(tail)) {
      // more components; hence not at penultimate context yet
      try {
        Object headCtx = a_lookup(head, cont);
        if (headCtx != null) cont.setContinue(headCtx, head, this, tail);
        else if (cont.isContinue()) cont.appendRemainingComponent(tail);
      } catch (NamingException e) {
        e.appendRemainingComponent(tail);
        throw e;
      }
    } else {
      // already at penultimate context
      cont.setSuccess(); // clear
      return true;
    }
    return false;
  }
  /**
   * Resolve to context named by 'name'. Returns true if at named context (i.e. 'name' is empty
   * name). Returns false otherwise, and sets Continuation on parts of 'name' not yet resolved.
   */
  protected boolean resolve_to_context(Name name, Continuation cont) throws NamingException {
    String target = name.toString();

    StringHeadTail ht = c_parseComponent(target, cont);
    String tail = ht.getTail();
    String head = ht.getHead();

    if (debug > 0)
      System.out.println("RESOLVE TO CONTEXT(" + target + ") = {" + head + ", " + tail + "}");

    if (head == null) {
      // something is wrong; no name at all
      InvalidNameException e = new InvalidNameException();
      throw cont.fillInException(e);
    }
    if (!isEmpty(head)) {
      // if there is head is a non-empty name
      // this means more resolution to be done
      try {
        Object headCtx = a_lookup(head, cont);
        //              System.out.println("answer " + headCtx);
        if (headCtx != null) cont.setContinue(headCtx, head, this, (tail == null ? "" : tail));
        else if (cont.isContinue()) cont.appendRemainingComponent(tail);
      } catch (NamingException e) {
        e.appendRemainingComponent(tail);
        throw e;
      }
    } else {
      cont.setSuccess(); // clear
      return true;
    }
    return false;
  }
Exemple #8
0
  /**
   * Constructs a JNDI Binding object from the COS Naming binding object.
   *
   * @exception NameNotFound No objects under the name.
   * @exception CannotProceed Unable to obtain a continuation context
   * @exception InvalidName Name not understood.
   * @exception NamingException One of the above.
   */
  private javax.naming.Binding mapBinding(org.omg.CosNaming.Binding bndg) throws NamingException {
    java.lang.Object obj = _ctx.callResolve(bndg.binding_name);

    Name cname = CNNameParser.cosNameToName(bndg.binding_name);

    try {
      obj = NamingManager.getObjectInstance(obj, cname, _ctx, _env);
    } catch (NamingException e) {
      throw e;
    } catch (Exception e) {
      NamingException ne = new NamingException("problem generating object using object factory");
      ne.setRootCause(e);
      throw ne;
    }

    // Use cname.toString() instead of bindingName because the name
    // in the binding should be a composite name
    String cnameStr = cname.toString();
    javax.naming.Binding jbndg = new javax.naming.Binding(cnameStr, obj);

    NameComponent[] comps = _ctx.makeFullName(bndg.binding_name);
    String fullName = CNNameParser.cosNameToInsString(comps);
    jbndg.setNameInNamespace(fullName);
    return jbndg;
  }
  /**
   * Construct a DirContextAdapter given the supplied paramters. The <code>name</code> is normally a
   * JNDI <code>CompositeName</code>, which needs to be handled with particuclar care. Specifically
   * the escaping of a <code>CompositeName</code> destroys proper escaping of Distinguished Names.
   * Also, the name might contain referral information, in which case we need to separate the server
   * information from the actual Distinguished Name so that we can create a representing
   * DirContextAdapter.
   *
   * @param attrs the attributes
   * @param name the Name, typically a <code>CompositeName</code>, possibly including referral
   *     information.
   * @param nameInNamespace the Name in namespace.
   * @return a {@link DirContextAdapter} representing the specified information.
   */
  DirContextAdapter constructAdapterFromName(Attributes attrs, Name name, String nameInNamespace) {
    String nameString;
    String referralUrl = "";

    if (name instanceof CompositeName) {
      // Which it most certainly will be, and therein lies the
      // problem. CompositeName.toString() completely screws up the
      // formatting
      // in some cases, particularly when backslashes are involved.
      nameString = LdapUtils.convertCompositeNameToString((CompositeName) name);
    } else {
      LOG.warn(
          "Expecting a CompositeName as input to getObjectInstance but received a '"
              + name.getClass().toString()
              + "' - using toString and proceeding with undefined results");
      nameString = name.toString();
    }

    if (nameString.startsWith(LDAP_PROTOCOL_PREFIX)
        || nameString.startsWith(LDAPS_PROTOCOL_PREFIX)) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "Received name '"
                + nameString
                + "' contains protocol delimiter; indicating a referral."
                + "Stripping protocol and address info to enable construction of a proper LdapName");
      }
      try {
        URI url = new URI(nameString);
        String pathString = url.getPath();
        referralUrl = nameString.substring(0, nameString.length() - pathString.length());

        if (StringUtils.hasLength(pathString) && pathString.startsWith("/")) {
          // We don't want any slash in the beginning of the
          // Distinguished Name.
          pathString = pathString.substring(1);
        }

        nameString = pathString;
      } catch (URISyntaxException e) {
        throw new IllegalArgumentException(
            "Supplied name starts with protocol prefix indicating a referral,"
                + " but is not possible to parse to an URI",
            e);
      }
      if (LOG.isDebugEnabled()) {
        LOG.debug("Resulting name after removal of referral information: '" + nameString + "'");
      }
    }

    DirContextAdapter dirContextAdapter =
        new DirContextAdapter(
            attrs,
            LdapUtils.newLdapName(nameString),
            LdapUtils.newLdapName(nameInNamespace),
            referralUrl);
    dirContextAdapter.setUpdateMode(true);
    return dirContextAdapter;
  }
  /**
   * Join two names together. These are treated as CompoundNames.
   *
   * @param name a <code>Name</code> value
   * @param prefix a <code>Name</code> value
   * @return a <code>Name</code> value
   * @exception NamingException if an error occurs
   */
  public String composeName(String name, String prefix) throws NamingException {
    if (name == null) throw new NamingException("Name cannot be null");
    if (prefix == null) throw new NamingException("Prefix cannot be null");

    Name compoundName = _parser.parse(prefix);
    compoundName.add(name);
    return compoundName.toString();
  }
 protected void c_unbind_nns(Name name, Continuation cont) throws NamingException {
   if (_contextType == _ATOMIC) {
     if (resolve_to_penultimate_context_nns(name, cont)) a_unbind_nns(name.toString(), cont);
   } else {
     // use ComponentContext
     super.c_unbind_nns(name, cont);
   }
 }
Exemple #12
0
  public void rename(Name oldName, Name newName) throws NamingException {
    Object value = lookup(oldName);
    unbind(oldName);

    if (value instanceof ContextImpl) ((ContextImpl) value).setName(newName.toString());

    bind(newName, value);
  }
Exemple #13
0
  /** Returns the full name for the context. */
  protected String getFullPath(Name name) {
    if (_name == null || _name.equals("")) return name.toString();
    else if (name == null || name.size() == 0) return _name;

    String sep = getSeparatorString();

    return _name + sep + name;
  }
 /*------------------------------------------------*/
 public void removeBinding(Name name) {
   String key = name.toString();
   if (__log.isDebugEnabled()) __log.debug("Removing binding with key=" + key);
   Binding binding = _bindings.remove(key);
   if (binding != null) {
     Collection<Listener> list = findListeners();
     for (Listener listener : list) listener.unbind(this, binding);
   }
 }
Exemple #15
0
  /**
   * Save the NamingEntry for later use.
   *
   * <p>Saving is done by binding the NamingEntry itself, and the value it represents into JNDI. In
   * this way, we can link to the value it represents later, but also still retrieve the NamingEntry
   * itself too.
   *
   * <p>The object is bound at the jndiName passed in. This NamingEntry is bound at __/jndiName.
   *
   * <p>eg
   *
   * <p>jdbc/foo : DataSource __/jdbc/foo : NamingEntry
   *
   * @throws NamingException
   */
  protected void save(Object object) throws NamingException {
    __log.debug("SAVE {} in {}", this, _scope);
    InitialContext ic = new InitialContext();
    NameParser parser = ic.getNameParser("");
    Name prefix = NamingEntryUtil.getNameForScope(_scope);

    // bind the NamingEntry into the context
    Name namingEntryName = NamingEntryUtil.makeNamingEntryName(parser, getJndiName());
    namingEntryName.addAll(0, prefix);
    _namingEntryNameString = namingEntryName.toString();
    NamingUtil.bind(ic, _namingEntryNameString, this);

    // bind the object as well
    Name objectName = parser.parse(getJndiName());
    objectName.addAll(0, prefix);
    _objectNameString = objectName.toString();
    NamingUtil.bind(ic, _objectNameString, object);
  }
  /**
   * Create a context as a child of this one
   *
   * @param name a <code>Name</code> value
   * @return a <code>Context</code> value
   * @exception NamingException if an error occurs
   */
  public Context createSubcontext(Name name) throws NamingException {
    if (isLocked()) {
      NamingException ne = new NamingException("This context is immutable");
      ne.setRemainingName(name);
      throw ne;
    }

    Name cname = toCanonicalName(name);

    if (cname == null) throw new NamingException("Name is null");
    if (cname.size() == 0) throw new NamingException("Name is empty");

    if (cname.size() == 1) {
      // not permitted to bind if something already bound at that name
      Binding binding = getBinding(cname);
      if (binding != null) throw new NameAlreadyBoundException(cname.toString());

      Context ctx = new NamingContext((Hashtable) _env.clone(), cname.get(0), this, _parser);
      addBinding(cname, ctx);
      return ctx;
    }

    // If the name has multiple subcontexts, walk the hierarchy by
    // fetching the first one. All intermediate subcontexts in the
    // name must already exist.
    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
        if (__log.isDebugEnabled())
          __log.debug("Object bound at " + firstComponent + " is a Reference");
        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) {
      return ((Context) ctx).createSubcontext(cname.getSuffix(1));
    } else throw new NotContextException(firstComponent + " is not a Context");
  }
 protected Context c_createSubcontext_nns(Name name, Continuation cont) throws NamingException {
   if (_contextType == _ATOMIC) {
     if (resolve_to_penultimate_context_nns(name, cont))
       return a_createSubcontext_nns(name.toString(), cont);
     else return null;
   } else {
     // use ComponentContext
     return super.c_createSubcontext_nns(name, cont);
   }
 }
 protected Object c_lookup(Name name, Continuation cont) throws NamingException {
   Object ret = null;
   if (resolve_to_penultimate_context(name, cont)) {
     ret = a_lookup(name.toString(), cont);
     if (ret != null && ret instanceof LinkRef) {
       cont.setContinue(ret, name, this);
       ret = null;
     }
   }
   return ret;
 }
  /**
   * Get the full name of this Context node by visiting it's ancestors back to root.
   *
   * <p>NOTE: if this Context has a URL namespace then the URL prefix will be missing
   *
   * @return the full name of this Context
   * @exception NamingException if an error occurs
   */
  public String getNameInNamespace() throws NamingException {
    Name name = _parser.parse("");

    NamingContext c = this;
    while (c != null) {
      String str = c.getName();
      if (str != null) name.add(0, str);
      c = (NamingContext) c.getParent();
    }
    return name.toString();
  }
 public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment)
     throws Exception {
   String s = name.toString();
   if (getLog().isTraceEnabled())
     getLog()
         .trace(
             "getObjectInstance: obj.getClass().getName=\""
                 + obj.getClass().getName()
                 + "\n                   name="
                 + s);
   if (NAMING_NAME.equals(s)) return namingService;
   else return null;
 }
Exemple #21
0
  /**
   * This postparses a namingEnumeration of NameClassPairs, after it has been returned from the jndi
   * operation. Usefull to over-ride if the names in the enumeration need to be unescaped or
   * reformatted.
   *
   * @param e the post jndi operation namingEnumeration.
   * @param base the 'base' dn from which the names in the enumeration (may) be relative. If the
   *     Names in the enumeration are suffixed by the searchBase, they are unaltered, otherwise the
   *     searchBase is added to the names to give the full DN in the namespace.
   * @return the re-formatted version used by the application.
   */
  public NamingEnumeration postParseNameClassPairs(NamingEnumeration e, Name base)
      throws NamingException {
    log.log(Level.FINER, "parsing with base :" + base.toString());
    DXNamingEnumeration dxe = new DXNamingEnumeration();

    String baseString = null;

    if (base != null && base.isEmpty() == false) baseString = base.toString();

    try {
      while (e.hasMore()) {
        NameClassPair ncp = (NameClassPair) e.next();

        String rawName = postParseString(ncp.getName()).toString();

        // IMPORTANT!
        // This appends the 'base' DN to the enumerated DNs in order to get absolute DNs...

        if (ncp.isRelative() && baseString != null) {
          if (rawName.length() != 0) rawName = rawName + "," + baseString;
          else rawName = baseString;
        }

        log.log(Level.FINER, "ended up with: '" + rawName + "'");
        ncp.setName(rawName);
        dxe.add(ncp);
      }
    } catch (NamingException ex) {
      CBUtility.error(
          CBIntText.get("Search partially failed! - only ")
              + dxe.size()
              + CBIntText.get(" entries returned."),
          ex);
    }

    return dxe;
  }
  public Object lookup(final Name name) throws NamingException {
    if (name.isEmpty()) {
      return new NamingContext(EMPTY_NAME, this, null);
    }
    final ServiceName lookupName = buildServiceName(name);
    Object obj = lookup(name.toString(), lookupName);
    if (obj == null) {
      final ServiceName lower = boundServices.lower(lookupName);
      if (lower != null && lower.isParentOf(lookupName)) {
        // Parent might be a reference or a link
        obj = lookup(name.toString(), lower);
        checkReferenceForContinuation(name, obj);
        return new ResolveResult(obj, suffix(lower, lookupName));
      }

      final ServiceName ceiling = boundServices.ceiling(lookupName);
      if (ceiling != null && lookupName.isParentOf(ceiling)) {
        return new NamingContext((Name) name.clone(), this, null);
      }
      throw new NameNotFoundException(name.toString() + " -- " + lookupName);
    }

    return obj;
  }
 protected Object c_lookup_nns(Name name, Continuation cont) throws NamingException {
   if (_contextType == _ATOMIC) {
     Object ret = null;
     if (resolve_to_penultimate_context_nns(name, cont)) {
       ret = a_lookup_nns(name.toString(), cont);
       if (ret != null && ret instanceof LinkRef) {
         cont.setContinue(ret, name, this);
         ret = null;
       }
     }
     return ret;
   } else {
     return super.c_lookup_nns(name, cont);
   }
 }
  protected Name stripProtocol(Name name) throws NamingException {
    if ((name != null) && (name.size() > 0)) {
      String head = name.get(0);

      if (__log.isDebugEnabled()) __log.debug("Head element of name is: " + head);

      if (head.startsWith(URL_PREFIX)) {
        head = head.substring(URL_PREFIX.length());
        name.remove(0);
        if (head.length() > 0) name.add(0, head);

        if (__log.isDebugEnabled()) __log.debug("name modified to " + name.toString());
      }
    }

    return name;
  }
  /**
   * This function is similar to resolve_to_penultimate_context() except it should only be called by
   * the nns() functions. This function fixes any exception or continuations so that it will have
   * the proper nns name.
   */
  protected boolean resolve_to_penultimate_context_nns(Name name, Continuation cont)
      throws NamingException {
    try {
      if (debug > 0) System.out.println("RESOLVE TO PENULTIMATE NNS" + name.toString());
      boolean answer = resolve_to_penultimate_context(name, cont);

      // resolve_to_penultimate_context() only calls a_lookup().
      // Any continuation it sets is lacking the nns, so
      // we need to add it back
      if (cont.isContinue()) cont.appendRemainingComponent("");

      return answer;
    } catch (NamingException e) {
      // resolve_to_penultimate_context() only calls a_lookup().
      // Any exceptions it throws is lacking the nns, so
      // we need to add it back.
      e.appendRemainingComponent("");
      throw e;
    }
  }
  /**
   * Do a deep listing of the bindings for a context.
   *
   * @param ctx the context containing the name for which to list the bindings
   * @param name the name in the context to list
   * @return map: key is fully qualified name, value is the bound object
   * @throws NamingException
   */
  public static Map flattenBindings(Context ctx, String name) throws NamingException {
    HashMap map = new HashMap();

    // the context representation of name arg
    Context c = (Context) ctx.lookup(name);
    NameParser parser = c.getNameParser("");
    NamingEnumeration enm = ctx.listBindings(name);
    while (enm.hasMore()) {
      Binding b = (Binding) enm.next();

      if (b.getObject() instanceof Context) {
        map.putAll(flattenBindings(c, b.getName()));
      } else {
        Name compoundName = parser.parse(c.getNameInNamespace());
        compoundName.add(b.getName());
        map.put(compoundName.toString(), b.getObject());
      }
    }

    return map;
  }
 public String getNameInNamespace() throws NamingException {
   return prefix.toString();
 }
Exemple #28
0
 /**
  * Return the name parser for the specified name.
  *
  * @return the NameParser instance.
  * @throws NamingException if there is an exception.
  */
 @Override
 public NameParser getNameParser(Name name) throws NamingException {
   // Flat namespace; no federation; just call string version
   return getNameParser(name.toString());
 }
Exemple #29
0
 public String toString() {
   return name.toString();
 }
Exemple #30
0
 @Override
 public String composeName(String name, String prefix) throws NamingException {
   Name result = composeName(new CompositeName(name), new CompositeName(prefix));
   return result.toString();
 }