Search in sources :

Example 1 with NameParser

use of javax.naming.NameParser in project jetty.project by eclipse.

the class TestMailSessionReference method testMailSessionReference.

@Test
public void testMailSessionReference() throws Exception {
    InitialContext icontext = new InitialContext();
    MailSessionReference sref = new MailSessionReference();
    sref.setUser("janb");
    sref.setPassword("OBF:1xmk1w261z0f1w1c1xmq");
    Properties props = new Properties();
    props.put("mail.smtp.host", "xxx");
    props.put("mail.debug", "true");
    sref.setProperties(props);
    NamingUtil.bind(icontext, "mail/Session", sref);
    Object x = icontext.lookup("mail/Session");
    assertNotNull(x);
    assertTrue(x instanceof javax.mail.Session);
    javax.mail.Session session = (javax.mail.Session) x;
    Properties sessionProps = session.getProperties();
    assertEquals(props, sessionProps);
    assertTrue(session.getDebug());
    Context foo = icontext.createSubcontext("foo");
    NameParser parser = icontext.getNameParser("");
    Name objectNameInNamespace = parser.parse(icontext.getNameInNamespace());
    objectNameInNamespace.addAll(parser.parse("mail/Session"));
    NamingUtil.bind(foo, "mail/Session", new LinkRef(objectNameInNamespace.toString()));
    Object o = foo.lookup("mail/Session");
    assertNotNull(o);
    Session fooSession = (Session) o;
    assertEquals(props, fooSession.getProperties());
    assertTrue(fooSession.getDebug());
    icontext.destroySubcontext("mail");
    icontext.destroySubcontext("foo");
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) Session(javax.mail.Session) Properties(java.util.Properties) InitialContext(javax.naming.InitialContext) NameParser(javax.naming.NameParser) Session(javax.mail.Session) Name(javax.naming.Name) LinkRef(javax.naming.LinkRef) Test(org.junit.Test)

Example 2 with NameParser

use of javax.naming.NameParser in project jetty.project by eclipse.

the class NamingUtil method flattenBindings.

/**
     * 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 if unable to flatten bindings
     */
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;
}
Also used : Context(javax.naming.Context) Binding(javax.naming.Binding) HashMap(java.util.HashMap) NamingEnumeration(javax.naming.NamingEnumeration) NameParser(javax.naming.NameParser) Name(javax.naming.Name)

Example 3 with NameParser

use of javax.naming.NameParser in project jetty.project by eclipse.

the class ContextFactory method newNamingContext.

/**
     * Create a new NamingContext.
     * @param obj the object to create
     * @param loader the classloader for the naming context
     * @param env the jndi env for the entry
     * @param name the name of the entry
     * @param parentCtx the parent context of the entry
     * @return the newly created naming context
     * @throws Exception if unable to create a new naming context
     */
public NamingContext newNamingContext(Object obj, ClassLoader loader, Hashtable env, Name name, Context parentCtx) throws Exception {
    Reference ref = (Reference) obj;
    StringRefAddr parserAddr = (StringRefAddr) ref.get("parser");
    String parserClassName = (parserAddr == null ? null : (String) parserAddr.getContent());
    NameParser parser = (NameParser) (parserClassName == null ? null : loader.loadClass(parserClassName).newInstance());
    return new NamingContext(env, name.get(0), (NamingContext) parentCtx, parser);
}
Also used : StringRefAddr(javax.naming.StringRefAddr) Reference(javax.naming.Reference) NameParser(javax.naming.NameParser)

Example 4 with NameParser

use of javax.naming.NameParser in project jetty.project by eclipse.

the class NamingEntryUtil method getContextForScope.

public static Context getContextForScope(Object scope) throws NamingException {
    InitialContext ic = new InitialContext();
    NameParser parser = ic.getNameParser("");
    Name name = parser.parse("");
    if (scope != null) {
        name.add(canonicalizeScope(scope));
    }
    return (Context) ic.lookup(name);
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) InitialContext(javax.naming.InitialContext) NameParser(javax.naming.NameParser) Name(javax.naming.Name)

Example 5 with NameParser

use of javax.naming.NameParser in project tomcat by apache.

the class JNDIRealm method getRoles.

/**
     * Return a List of roles associated with the given User.  Any
     * roles present in the user's directory entry are supplemented by
     * a directory search. If no roles are associated with this user,
     * a zero-length List is returned.
     *
     * @param context The directory context we are searching
     * @param user The User to be checked
     * @return the list of role names
     * @exception NamingException if a directory server error occurs
     */
protected List<String> getRoles(DirContext context, User user) throws NamingException {
    if (user == null)
        return null;
    String dn = user.getDN();
    String username = user.getUserName();
    String userRoleId = user.getUserRoleId();
    if (dn == null || username == null)
        return null;
    if (containerLog.isTraceEnabled())
        containerLog.trace("  getRoles(" + dn + ")");
    // Start with roles retrieved from the user entry
    List<String> list = new ArrayList<>();
    List<String> userRoles = user.getRoles();
    if (userRoles != null) {
        list.addAll(userRoles);
    }
    if (commonRole != null)
        list.add(commonRole);
    if (containerLog.isTraceEnabled()) {
        containerLog.trace("  Found " + list.size() + " user internal roles");
        containerLog.trace("  Found user internal roles " + list.toString());
    }
    // Are we configured to do role searches?
    if ((roleFormat == null) || (roleName == null))
        return list;
    // Set up parameters for an appropriate search
    String filter = roleFormat.format(new String[] { doRFC2254Encoding(dn), username, userRoleId });
    SearchControls controls = new SearchControls();
    if (roleSubtree)
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    else
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    controls.setReturningAttributes(new String[] { roleName });
    String base = null;
    if (roleBaseFormat != null) {
        NameParser np = context.getNameParser("");
        Name name = np.parse(dn);
        String[] nameParts = new String[name.size()];
        for (int i = 0; i < name.size(); i++) {
            nameParts[i] = name.get(i);
        }
        base = roleBaseFormat.format(nameParts);
    } else {
        base = "";
    }
    // Perform the configured search and process the results
    NamingEnumeration<SearchResult> results = searchAsUser(context, user, base, filter, controls, isRoleSearchAsUser());
    if (results == null)
        // Should never happen, but just in case ...
        return list;
    HashMap<String, String> groupMap = new HashMap<>();
    try {
        while (results.hasMore()) {
            SearchResult result = results.next();
            Attributes attrs = result.getAttributes();
            if (attrs == null)
                continue;
            String dname = getDistinguishedName(context, roleBase, result);
            String name = getAttributeValue(roleName, attrs);
            if (name != null && dname != null) {
                groupMap.put(dname, name);
            }
        }
    } catch (PartialResultException ex) {
        if (!adCompat)
            throw ex;
    } finally {
        results.close();
    }
    if (containerLog.isTraceEnabled()) {
        Set<Entry<String, String>> entries = groupMap.entrySet();
        containerLog.trace("  Found " + entries.size() + " direct roles");
        for (Entry<String, String> entry : entries) {
            containerLog.trace("  Found direct role " + entry.getKey() + " -> " + entry.getValue());
        }
    }
    // if nested group search is enabled, perform searches for nested groups until no new group is found
    if (getRoleNested()) {
        // The following efficient algorithm is known as memberOf Algorithm, as described in "Practices in
        // Directory Groups". It avoids group slurping and handles cyclic group memberships as well.
        // See http://middleware.internet2.edu/dir/ for details
        Map<String, String> newGroups = new HashMap<>(groupMap);
        while (!newGroups.isEmpty()) {
            // Stores the groups we find in this iteration
            Map<String, String> newThisRound = new HashMap<>();
            for (Entry<String, String> group : newGroups.entrySet()) {
                filter = roleFormat.format(new String[] { group.getKey(), group.getValue(), group.getValue() });
                if (containerLog.isTraceEnabled()) {
                    containerLog.trace("Perform a nested group search with base " + roleBase + " and filter " + filter);
                }
                results = searchAsUser(context, user, roleBase, filter, controls, isRoleSearchAsUser());
                try {
                    while (results.hasMore()) {
                        SearchResult result = results.next();
                        Attributes attrs = result.getAttributes();
                        if (attrs == null)
                            continue;
                        String dname = getDistinguishedName(context, roleBase, result);
                        String name = getAttributeValue(roleName, attrs);
                        if (name != null && dname != null && !groupMap.keySet().contains(dname)) {
                            groupMap.put(dname, name);
                            newThisRound.put(dname, name);
                            if (containerLog.isTraceEnabled()) {
                                containerLog.trace("  Found nested role " + dname + " -> " + name);
                            }
                        }
                    }
                } catch (PartialResultException ex) {
                    if (!adCompat)
                        throw ex;
                } finally {
                    results.close();
                }
            }
            newGroups = newThisRound;
        }
    }
    list.addAll(groupMap.values());
    return list;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) PartialResultException(javax.naming.PartialResultException) CompositeName(javax.naming.CompositeName) Name(javax.naming.Name) Entry(java.util.Map.Entry) SearchControls(javax.naming.directory.SearchControls) NameParser(javax.naming.NameParser)

Aggregations

NameParser (javax.naming.NameParser)24 Name (javax.naming.Name)21 InitialContext (javax.naming.InitialContext)9 NamingException (javax.naming.NamingException)8 HashMap (java.util.HashMap)7 Context (javax.naming.Context)7 CompositeName (javax.naming.CompositeName)6 CoreException (com.cosylab.acs.maci.CoreException)4 ArrayList (java.util.ArrayList)4 Attributes (javax.naming.directory.Attributes)4 SearchControls (javax.naming.directory.SearchControls)4 SearchResult (javax.naming.directory.SearchResult)4 URI (java.net.URI)3 URISyntaxException (java.net.URISyntaxException)3 Entry (java.util.Map.Entry)3 NameNotFoundException (javax.naming.NameNotFoundException)3 PartialResultException (javax.naming.PartialResultException)3 Test (org.junit.Test)3 Map (java.util.Map)2 InvalidNameException (javax.naming.InvalidNameException)2