Esempio n. 1
0
  /**
   * Tests that we can get a connection from the DataSource bound in JNDI during test setup
   *
   * @throws Exception if an error occurs
   */
  public void testDataSource() throws Exception {
    NameParser nameParser = this.ctx.getNameParser("");
    Name datasourceName = nameParser.parse("_test");
    Object obj = this.ctx.lookup(datasourceName);
    DataSource boundDs = null;

    if (obj instanceof DataSource) {
      boundDs = (DataSource) obj;
    } else if (obj instanceof Reference) {
      //
      // For some reason, this comes back as a Reference instance under CruiseControl !?
      //
      Reference objAsRef = (Reference) obj;
      ObjectFactory factory =
          (ObjectFactory) Class.forName(objAsRef.getFactoryClassName()).newInstance();
      boundDs =
          (DataSource)
              factory.getObjectInstance(
                  objAsRef, datasourceName, this.ctx, new Hashtable<Object, Object>());
    }

    assertTrue("Datasource not bound", boundDs != null);

    Connection con = boundDs.getConnection();
    con.close();
    assertTrue("Connection can not be obtained from data source", con != null);
  }
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      String methodName = method.getName();
      if (methodName.equals("toString") == true) return "Client ENC(" + clientName + ")";

      if (methodName.equals("lookup") == false)
        throw new OperationNotSupportedException("Only lookup is supported, op=" + method);
      NameParser parser = lookupCtx.getNameParser("");
      Name name = null;
      if (args[0] instanceof String) name = parser.parse((String) args[0]);
      else name = (Name) args[0];

      // Check for special objects not in the env
      if (name.size() < 2
          || "java:comp".equals(name.get(0)) == false
          || "env".equals(name.get(1)) == false) return getSpecialObject(name);
      // Lookup the client application context from the server
      Context clientCtx = (Context) lookupCtx.lookup(clientName);

      // JBAS-3967: EJB3 Client container hack
      try {
        clientCtx = (Context) clientCtx.lookup("env");
      } catch (NamingException e) {
        // ignore
        log.trace("No env sub context found", e);
      }

      // Strip the comp/env prefix
      Name bindingName = name.getSuffix(2);
      Object binding = clientCtx.lookup(bindingName);

      return binding;
    }
Esempio n. 3
0
  /**
   * 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();
  }
Esempio n. 4
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);
  }
Esempio n. 5
0
  /**
   * 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();
  }
  /**
   * 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;
  }
  static {
    try {
      __javaNameParser = new javaNameParser();
      __nameRoot = new NamingContext(null, null, null, __javaNameParser);

      StringRefAddr parserAddr = new StringRefAddr("parser", __javaNameParser.getClass().getName());

      Reference ref =
          new Reference(
              "javax.naming.Context", parserAddr, ContextFactory.class.getName(), (String) null);

      // bind special object factory at comp
      __nameRoot.bind("comp", ref);
    } catch (Exception e) {
      __log.warn(e);
    }
  }
Esempio n. 8
0
 /**
  * Not supported.
  *
  * @param name a <code>String</code> value
  * @exception NamingException if an error occurs
  */
 public void unbind(String name) throws NamingException {
   unbind(_parser.parse(name));
 }
Esempio n. 9
0
 /**
  * Overwrite or create a binding from Name to Object
  *
  * @param name a <code>String</code> value
  * @param obj an <code>Object</code> value
  * @exception NamingException if an error occurs
  */
 public void rebind(String name, Object obj) throws NamingException {
   rebind(_parser.parse(name), obj);
 }
Esempio n. 10
0
 /**
  * List all Bindings at Name
  *
  * @param name a <code>String</code> value
  * @return a <code>NamingEnumeration</code> value
  * @exception NamingException if an error occurs
  */
 public NamingEnumeration listBindings(String name) throws NamingException {
   return listBindings(_parser.parse(name));
 }
Esempio n. 11
0
 /**
  * Lookup link bound to name
  *
  * @param name name of link binding
  * @return LinkRef or plain object bound at name
  * @exception NamingException if an error occurs
  */
 public Object lookupLink(String name) throws NamingException {
   return lookupLink(_parser.parse(name));
 }
Esempio n. 12
0
 /**
  * @param name name of subcontext to remove
  * @exception NamingException if an error occurs
  */
 public void destroySubcontext(String name) throws NamingException {
   removeBinding(_parser.parse(name));
 }
Esempio n. 13
0
 /**
  * Create a Context as a child of this one
  *
  * @param name a <code>String</code> value
  * @return a <code>Context</code> value
  * @exception NamingException if an error occurs
  */
 public Context createSubcontext(String name) throws NamingException {
   return createSubcontext(_parser.parse(name));
 }
Esempio n. 14
0
  /**
   * 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");
    }
  }
Esempio n. 15
0
  protected boolean authenticate(String username, String password) throws LoginException {

    MessageFormat userSearchMatchingFormat;
    boolean userSearchSubtreeBool;

    DirContext context = null;

    if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) {
      ActiveMQServerLogger.LOGGER.debug("Create the LDAP initial context.");
    }
    try {
      context = open();
    } catch (NamingException ne) {
      FailedLoginException ex = new FailedLoginException("Error opening LDAP connection");
      ex.initCause(ne);
      throw ex;
    }

    if (!isLoginPropertySet(USER_SEARCH_MATCHING)) return false;

    userSearchMatchingFormat = new MessageFormat(getLDAPPropertyValue(USER_SEARCH_MATCHING));
    userSearchSubtreeBool =
        Boolean.valueOf(getLDAPPropertyValue(USER_SEARCH_SUBTREE)).booleanValue();

    try {

      String filter = userSearchMatchingFormat.format(new String[] {doRFC2254Encoding(username)});
      SearchControls constraints = new SearchControls();
      if (userSearchSubtreeBool) {
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
      } else {
        constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
      }

      // setup attributes
      List<String> list = new ArrayList<String>();
      if (isLoginPropertySet(USER_ROLE_NAME)) {
        list.add(getLDAPPropertyValue(USER_ROLE_NAME));
      }
      String[] attribs = new String[list.size()];
      list.toArray(attribs);
      constraints.setReturningAttributes(attribs);

      if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) {
        ActiveMQServerLogger.LOGGER.debug("Get the user DN.");
        ActiveMQServerLogger.LOGGER.debug("Looking for the user in LDAP with ");
        ActiveMQServerLogger.LOGGER.debug("  base DN: " + getLDAPPropertyValue(USER_BASE));
        ActiveMQServerLogger.LOGGER.debug("  filter: " + filter);
      }

      NamingEnumeration<SearchResult> results =
          context.search(getLDAPPropertyValue(USER_BASE), filter, constraints);

      if (results == null || !results.hasMore()) {
        ActiveMQServerLogger.LOGGER.warn("User " + username + " not found in LDAP.");
        throw new FailedLoginException("User " + username + " not found in LDAP.");
      }

      SearchResult result = results.next();

      if (results.hasMore()) {
        // ignore for now
      }

      String dn;
      if (result.isRelative()) {
        ActiveMQServerLogger.LOGGER.debug("LDAP returned a relative name: " + result.getName());

        NameParser parser = context.getNameParser("");
        Name contextName = parser.parse(context.getNameInNamespace());
        Name baseName = parser.parse(getLDAPPropertyValue(USER_BASE));
        Name entryName = parser.parse(result.getName());
        Name name = contextName.addAll(baseName);
        name = name.addAll(entryName);
        dn = name.toString();
      } else {
        ActiveMQServerLogger.LOGGER.debug("LDAP returned an absolute name: " + result.getName());

        try {
          URI uri = new URI(result.getName());
          String path = uri.getPath();

          if (path.startsWith("/")) {
            dn = path.substring(1);
          } else {
            dn = path;
          }
        } catch (URISyntaxException e) {
          if (context != null) {
            close(context);
          }
          FailedLoginException ex = new FailedLoginException("Error parsing absolute name as URI.");
          ex.initCause(e);
          throw ex;
        }
      }

      if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) {
        ActiveMQServerLogger.LOGGER.debug("Using DN [" + dn + "] for binding.");
      }

      Attributes attrs = result.getAttributes();
      if (attrs == null) {
        throw new FailedLoginException("User found, but LDAP entry malformed: " + username);
      }
      List<String> roles = null;
      if (isLoginPropertySet(USER_ROLE_NAME)) {
        roles = addAttributeValues(getLDAPPropertyValue(USER_ROLE_NAME), attrs, roles);
      }

      // check the credentials by binding to server
      if (bindUser(context, dn, password)) {
        // if authenticated add more roles
        roles = getRoles(context, dn, username, roles);
        if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) {
          ActiveMQServerLogger.LOGGER.debug("Roles " + roles + " for user " + username);
        }
        for (int i = 0; i < roles.size(); i++) {
          groups.add(new RolePrincipal(roles.get(i)));
        }
      } else {
        throw new FailedLoginException("Password does not match for user: "******"Error contacting LDAP");
      ex.initCause(e);
      throw ex;
    } catch (NamingException e) {
      if (context != null) {
        close(context);
      }
      FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
      ex.initCause(e);
      throw ex;
    }

    return true;
  }