Java 类javax.naming.directory.DirContext 实例源码

项目:plugin-id-ldap    文件:GroupLdapRepository.java   
@Override
public void addAttributes(final String dn, final String attribute, final Collection<String> values) {
    if (values.isEmpty()) {
        // Ignore this call
        return;
    }

    // Build the modification operation
    final ModificationItem[] mods = values.stream().map(v -> new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute(attribute, v)))
            .toArray(ModificationItem[]::new);
    try {
        // Perform the addition
        template.modifyAttributes(org.springframework.ldap.support.LdapUtils.newLdapName(dn), mods);
    } catch (final org.springframework.ldap.AttributeInUseException aiue) {
        if (!aiue.getMessage().matches(".*(value #0 already exists|error code 20|ATTRIBUTE_OR_VALUE_EXISTS).*")) {
            throw aiue;
        }
        log.info("{} is already member of {}", values, dn);
    }
}
项目:lazycat    文件:ContainerBase.java   
/**
 * Set the resources DirContext object with which this Container is
 * associated.
 *
 * @param resources
 *            The newly associated DirContext
 */
@Override
public synchronized void setResources(DirContext resources) {
    // Called from StandardContext.setResources()
    // <- StandardContext.start()
    // <- ContainerBase.addChildInternal()

    // Change components if necessary
    DirContext oldResources = this.resources;
    if (oldResources == resources)
        return;
    Hashtable<String, String> env = new Hashtable<String, String>();
    if (getParent() != null)
        env.put(ProxyDirContext.HOST, getParent().getName());
    env.put(ProxyDirContext.CONTEXT, getName());
    this.resources = new ProxyDirContext(env, resources);
    // Report this property change to interested listeners
    support.firePropertyChange("resources", oldResources, this.resources);

}
项目:Equella    文件:LDAPServiceImpl.java   
@Override
public String getTokenFromUsername(final LDAP ldap, final String username)
{
    return ldap.doAsAdmin(new InContext<String>()
    {
        @Override
        public String execute(DirContext ctx)
        {

            Name results = ldap.searchFirstResultAllBases(ctx, ldap.getUsernameFilter(username),
                new FullNameHitsCollector(), true);
            if( results != null )
            {
                return results.toString();
            }
            return null;
        }
    });
}
项目:OpenJSharp    文件:DirectoryManager.java   
/**
  * Creates a context in which to continue a <tt>DirContext</tt> operation.
  * Operates just like <tt>NamingManager.getContinuationContext()</tt>,
  * only the continuation context returned is a <tt>DirContext</tt>.
  *
  * @param cpe
  *         The non-null exception that triggered this continuation.
  * @return A non-null <tt>DirContext</tt> object for continuing the operation.
  * @exception NamingException If a naming exception occurred.
  *
  * @see NamingManager#getContinuationContext(CannotProceedException)
  */
@SuppressWarnings("unchecked")
public static DirContext getContinuationDirContext(
        CannotProceedException cpe) throws NamingException {

    Hashtable<Object,Object> env = (Hashtable<Object,Object>)cpe.getEnvironment();
    if (env == null) {
        env = new Hashtable<>(7);
    } else {
        // Make a (shallow) copy of the environment.
        env = (Hashtable<Object,Object>) env.clone();
    }
    env.put(CPE, cpe);

    return (new ContinuationDirContext(cpe, env));
}
项目:oscm    文件:LdapAccessServiceBeanTest.java   
@SuppressWarnings("unchecked")
@Before
public void setup() throws Exception {
    bean = spy(new LdapAccessServiceBean());
    dcMock = mock(DirContext.class);
    neMock = mock(NamingEnumeration.class);
    srMock = mock(SearchResult.class);
    aMock = mock(Attributes.class);

    doReturn(new Integer(5)).when(bean).getSearchLimit();
    doReturn(dcMock).when(bean).getDirContext(any(Properties.class));

    when(dcMock.search(anyString(), anyString(), any(SearchControls.class)))
            .thenReturn(neMock);

    when(Boolean.valueOf(neMock.hasMore())).thenReturn(Boolean.TRUE,
            Boolean.FALSE);
    when(neMock.next()).thenReturn(srMock);
    when(srMock.getAttributes()).thenReturn(aMock);
}
项目:lams    文件:JNDIRealm.java   
/**
 * Return a User object containing information about the user
 * with the specified username, if found in the directory;
 * otherwise return <code>null</code>.
 *
 * If the <code>userPassword</code> configuration attribute is
 * specified, the value of that attribute is retrieved from the
 * user's directory entry. If the <code>userRoleName</code>
 * configuration attribute is specified, all values of that
 * attribute are retrieved from the directory entry.
 *
 * @param context The directory context
 * @param username Username to be looked up
 * @param credentials User credentials (optional)
 * @param curUserPattern Index into userPatternFormatArray
 *
 * @exception NamingException if a directory server error occurs
 */
protected User getUser(DirContext context, String username,
                       String credentials, int curUserPattern)
    throws NamingException {

    User user = null;

    // Get attributes to retrieve from user entry
    ArrayList<String> list = new ArrayList<String>();
    if (userPassword != null)
        list.add(userPassword);
    if (userRoleName != null)
        list.add(userRoleName);
    String[] attrIds = new String[list.size()];
    list.toArray(attrIds);

    // Use pattern or search for user entry
    if (userPatternFormatArray != null && curUserPattern >= 0) {
        user = getUserByPattern(context, username, credentials, attrIds, curUserPattern);
    } else {
        user = getUserBySearch(context, username, attrIds);
    }

    return user;
}
项目:BaseClient    文件:ServerAddress.java   
/**
 * Returns a server's address and port for the specified hostname, looking up the SRV record if possible
 */
private static String[] getServerAddress(String p_78863_0_)
{
    try
    {
        String s = "com.sun.jndi.dns.DnsContextFactory";
        Class.forName("com.sun.jndi.dns.DnsContextFactory");
        Hashtable hashtable = new Hashtable();
        hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        hashtable.put("java.naming.provider.url", "dns:");
        hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
        DirContext dircontext = new InitialDirContext(hashtable);
        Attributes attributes = dircontext.getAttributes("_minecraft._tcp." + p_78863_0_, new String[] {"SRV"});
        String[] astring = attributes.get("srv").get().toString().split(" ", 4);
        return new String[] {astring[3], astring[2]};
    }
    catch (Throwable var6)
    {
        return new String[] {p_78863_0_, Integer.toString(25565)};
    }
}
项目:lams    文件:JNDIRealm.java   
/**
 * Check whether the given User can be authenticated with the
 * given credentials. If the <code>userPassword</code>
 * configuration attribute is specified, the credentials
 * previously retrieved from the directory are compared explicitly
 * with those presented by the user. Otherwise the presented
 * credentials are checked by binding to the directory as the
 * user.
 *
 * @param context The directory context
 * @param user The User to be authenticated
 * @param credentials The credentials presented by the user
 *
 * @exception NamingException if a directory server error occurs
 */
protected boolean checkCredentials(DirContext context,
                                 User user,
                                 String credentials)
     throws NamingException {

     boolean validated = false;

     if (userPassword == null) {
         validated = bindAsUser(context, user, credentials);
     } else {
         validated = compareCredentials(context, user, credentials);
     }

     if (containerLog.isTraceEnabled()) {
         if (validated) {
             containerLog.trace(sm.getString("jndiRealm.authenticateSuccess",
                              user.username));
         } else {
             containerLog.trace(sm.getString("jndiRealm.authenticateFailure",
                              user.username));
         }
     }
     return (validated);
 }
项目:tomcat7    文件:ApplicationContext.java   
/**
 * List resource paths (recursively), and store all of them in the given
 * Set.
 */
private static void listCollectionPaths(Set<String> set,
        DirContext resources, String path) throws NamingException {

    Enumeration<Binding> childPaths = resources.listBindings(path);
    while (childPaths.hasMoreElements()) {
        Binding binding = childPaths.nextElement();
        String name = binding.getName();
        StringBuilder childPath = new StringBuilder(path);
        if (!"/".equals(path) && !path.endsWith("/"))
            childPath.append("/");
        childPath.append(name);
        Object object = binding.getObject();
        if (object instanceof DirContext) {
            childPath.append("/");
        }
        set.add(childPath.toString());
    }

}
项目:lams    文件:ContainerBase.java   
/**
 * Set the resources DirContext object with which this Container is
 * associated.
 *
 * @param resources The newly associated DirContext
 */
public synchronized void setResources(DirContext resources) {
    // Called from StandardContext.setResources()
    //              <- StandardContext.start() 
    //              <- ContainerBase.addChildInternal() 

    // Change components if necessary
    DirContext oldResources = this.resources;
    if (oldResources == resources)
        return;
    Hashtable env = new Hashtable();
    if (getParent() != null)
        env.put(ProxyDirContext.HOST, getParent().getName());
    env.put(ProxyDirContext.CONTEXT, getName());
    this.resources = new ProxyDirContext(env, resources);
    // Report this property change to interested listeners
    support.firePropertyChange("resources", oldResources, this.resources);

}
项目:tomcat7    文件:ContainerBase.java   
/**
 * Set the resources DirContext object with which this Container is
 * associated.
 *
 * @param resources The newly associated DirContext
 */
@Override
public synchronized void setResources(DirContext resources) {
    // Called from StandardContext.setResources()
    //              <- StandardContext.start() 
    //              <- ContainerBase.addChildInternal() 

    // Change components if necessary
    DirContext oldResources = this.resources;
    if (oldResources == resources)
        return;
    Hashtable<String, String> env = new Hashtable<String, String>();
    if (getParent() != null)
        env.put(ProxyDirContext.HOST, getParent().getName());
    env.put(ProxyDirContext.CONTEXT, getName());
    this.resources = new ProxyDirContext(env, resources);
    // Report this property change to interested listeners
    support.firePropertyChange("resources", oldResources, this.resources);

}
项目:lams    文件:ApplicationContext.java   
/**
 * Return the requested resource as an <code>InputStream</code>.  The
 * path must be specified according to the rules described under
 * <code>getResource</code>.  If no such resource can be identified,
 * return <code>null</code>.
 *
 * @param path The path to the desired resource.
 */
public InputStream getResourceAsStream(String path) {

    if (path == null || (Globals.STRICT_SERVLET_COMPLIANCE && !path.startsWith("/")))
        return (null);

    path = RequestUtil.normalize(path);
    if (path == null)
        return (null);

    DirContext resources = context.getResources();
    if (resources != null) {
        try {
            Object resource = resources.lookup(path);
            if (resource instanceof Resource)
                return (((Resource) resource).streamContent());
        } catch (Exception e) {
        }
    }
    return (null);

}
项目:Equella    文件:LDAP.java   
public LDAPResult getGroupResult(DirContext ctx, String groupID, String[] attrs)
{
    if( !Check.isEmpty(groupIdField) )
    {
        SingleFilter nv1 = new SingleFilter(OBJECTCLASS, getGroupObject());
        SingleFilter nv2 = new SingleFilter(groupIdField, groupID);
        return searchFirstResultAllBases(ctx, new AndFilter(nv1, nv2), new LdapResultHitsCollector(attrs), true);
    }

    try
    {
        Name name = LDAP.parse(groupID);
        return new LDAPResult(name, getAttributes(ctx, name, attrs));
    }
    catch( InvalidNameException e )
    {
        LOGGER.debug(e, e);
        return null;
    }
}
项目:jerrydog    文件:ApplicationContext.java   
/**
 * Return a Set containing the resource paths of resources member of the
 * specified collection. Each path will be a String starting with
 * a "/" character. The returned set is immutable.
 *
 * @param path Collection path
 */
public Set getResourcePaths(String path) {

    DirContext resources = context.getResources();
    if (resources != null) {
        if (System.getSecurityManager() != null) {
            PrivilegedAction dp =
                new PrivilegedGetResourcePaths(resources, path);
            return ((Set) AccessController.doPrivileged(dp));
        } else {
            return (getResourcePathsInternal(resources, path));
        }
    }
    return (null);

}
项目:Equella    文件:LDAP.java   
public <T> List<T> searchAllBases(DirContext ctx, Filter filter, HitsCollector<T> collector, boolean recurse)
{
    for( Name element : getBases() )
    {
        search(ctx, element, filter, collector, recurse);
    }
    return collector.getResults();
}
项目:lams    文件:DirContextURLStreamHandler.java   
/**
 * Binds a directory context to a class loader.
 */
public static void bind(DirContext dirContext) {
    ClassLoader currentCL = 
        Thread.currentThread().getContextClassLoader();
    if (currentCL != null)
        clBindings.put(currentCL, dirContext);
}
项目:wherehowsX    文件:AuthenticationManager.java   
public static Map<String, String> getUserAttributes(DirContext ctx, String searchBase, String userName,
    String principalDomain, String... attributeNames)
    throws NamingException {
  if (StringUtils.isBlank(userName)) {
    throw new IllegalArgumentException("Username and password can not be blank.");
  }

  if (attributeNames.length == 0) {
    return Collections.emptyMap();
  }

  Attributes matchAttr = new BasicAttributes(true);
  BasicAttribute basicAttr = new BasicAttribute("userPrincipalName", userName + principalDomain);
  matchAttr.put(basicAttr);

  NamingEnumeration<? extends SearchResult> searchResult = ctx.search(searchBase, matchAttr, attributeNames);

  if (ctx != null) {
    ctx.close();
  }

  Map<String, String> result = new HashMap<>();

  if (searchResult.hasMore()) {
    NamingEnumeration<? extends Attribute> attributes = searchResult.next().getAttributes().getAll();

    while (attributes.hasMore()) {
      Attribute attr = attributes.next();
      String attrId = attr.getID();
      String attrValue = (String) attr.get();

      result.put(attrId, attrValue);
    }
  }
  return result;
}
项目:hadoop-oss    文件:DNS.java   
/**
 * Returns the hostname associated with the specified IP address by the
 * provided nameserver.
 *
 * Loopback addresses 
 * @param hostIp The address to reverse lookup
 * @param ns The host name of a reachable DNS server
 * @return The host name associated with the provided IP
 * @throws NamingException If a NamingException is encountered
 */
public static String reverseDns(InetAddress hostIp, @Nullable String ns)
  throws NamingException {
  //
  // Builds the reverse IP lookup form
  // This is formed by reversing the IP numbers and appending in-addr.arpa
  //
  String[] parts = hostIp.getHostAddress().split("\\.");
  String reverseIP = parts[3] + "." + parts[2] + "." + parts[1] + "."
    + parts[0] + ".in-addr.arpa";

  DirContext ictx = new InitialDirContext();
  Attributes attribute;
  try {
    attribute = ictx.getAttributes("dns://"               // Use "dns:///" if the default
                       + ((ns == null) ? "" : ns) +
                       // nameserver is to be used
                       "/" + reverseIP, new String[] { "PTR" });
  } finally {
    ictx.close();
  }

  String hostname = attribute.get("PTR").get().toString();
  int hostnameLength = hostname.length();
  if (hostname.charAt(hostnameLength - 1) == '.') {
    hostname = hostname.substring(0, hostnameLength - 1);
  }
  return hostname;
}
项目:lams    文件:ProxyDirContext.java   
/**
 * Retrieves the named object as a cache entry, without any exception.
 * 
 * @param name the name of the object to look up
 * @return the cache entry bound to name
 */
public CacheEntry lookupCache(String name) {
    CacheEntry entry = cacheLookup(name);
    if (entry == null) {
        entry = new CacheEntry();
        entry.name = name;
        try {
            Object object = dirContext.lookup(parseName(name));
            if (object instanceof InputStream) {
                entry.resource = new Resource((InputStream) object);
            } else if (object instanceof DirContext) {
                entry.context = (DirContext) object;
            } else if (object instanceof Resource) {
                entry.resource = (Resource) object;
            } else {
                entry.resource = new Resource(new ByteArrayInputStream
                    (object.toString().getBytes()));
            }
            Attributes attributes = dirContext.getAttributes(parseName(name));
            if (!(attributes instanceof ResourceAttributes)) {
                attributes = new ResourceAttributes(attributes);
            }
            entry.attributes = (ResourceAttributes) attributes;
        } catch (NamingException e) {
            entry.exists = false;
        }
    }
    return entry;
}
项目:hadoop    文件:DNS.java   
/**
 * Returns the hostname associated with the specified IP address by the
 * provided nameserver.
 *
 * Loopback addresses 
 * @param hostIp The address to reverse lookup
 * @param ns The host name of a reachable DNS server
 * @return The host name associated with the provided IP
 * @throws NamingException If a NamingException is encountered
 */
public static String reverseDns(InetAddress hostIp, String ns)
  throws NamingException {
  //
  // Builds the reverse IP lookup form
  // This is formed by reversing the IP numbers and appending in-addr.arpa
  //
  String[] parts = hostIp.getHostAddress().split("\\.");
  String reverseIP = parts[3] + "." + parts[2] + "." + parts[1] + "."
    + parts[0] + ".in-addr.arpa";

  DirContext ictx = new InitialDirContext();
  Attributes attribute;
  try {
    attribute = ictx.getAttributes("dns://"               // Use "dns:///" if the default
                       + ((ns == null) ? "" : ns) +
                       // nameserver is to be used
                       "/" + reverseIP, new String[] { "PTR" });
  } finally {
    ictx.close();
  }

  String hostname = attribute.get("PTR").get().toString();
  int hostnameLength = hostname.length();
  if (hostname.charAt(hostnameLength - 1) == '.') {
    hostname = hostname.substring(0, hostnameLength - 1);
  }
  return hostname;
}
项目:apache-tomcat-7.0.73-with-comment    文件:JNDIRealm.java   
/**
 * Check credentials by binding to the directory as the user
 *
 * @param context The directory context
 * @param user The User to be authenticated
 * @param credentials Authentication credentials
 *
 * @exception NamingException if a directory server error occurs
 */
 protected boolean bindAsUser(DirContext context,
                              User user,
                              String credentials)
     throws NamingException {

     if (credentials == null || user == null)
         return (false);

     String dn = user.getDN();
     if (dn == null)
         return (false);

     // Validate the credentials specified by the user
     if (containerLog.isTraceEnabled()) {
         containerLog.trace("  validating credentials by binding as the user");
    }

    userCredentialsAdd(context, dn, credentials);

    // Elicit an LDAP bind operation
    boolean validated = false;
    try {
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  binding as "  + dn);
        }
        context.getAttributes("", null);
        validated = true;
    }
    catch (AuthenticationException e) {
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("  bind attempt failed");
        }
    }

    userCredentialsRemove(context);

    return validated;
}
项目:ARCLib    文件:DummySSLLdapContextSource.java   
@Override
protected DirContext getDirContextInstance(Hashtable<String, Object> env) throws NamingException {
    String url = (String) env.get(Context.PROVIDER_URL);
    try {
        if (new URI(url).getScheme().equalsIgnoreCase("ldaps")) {
            env.put("java.naming.ldap.factory.socket", "cz.inqool.uas.security.ldap.ssl.DummySSLSocketFactory");
        }
    } catch (URISyntaxException e) {
        log.error("LDAP URL {} is wrong", url, e);
    }
    return new InitialLdapContext(env, null);
}
项目:jerrydog    文件:ApplicationContext.java   
/**
 * Return the requested resource as an <code>InputStream</code>.  The
 * path must be specified according to the rules described under
 * <code>getResource</code>.  If no such resource can be identified,
 * return <code>null</code>.
 *
 * @param path The path to the desired resource.
 */
public InputStream getResourceAsStream(String path) {

    DirContext resources = context.getResources();
    if (resources != null) {
        try {
            Object resource = resources.lookup(path);
            if (resource instanceof Resource)
                return (((Resource) resource).streamContent());
        } catch (Exception e) {
        }
    }
    return (null);

}
项目:ChronoBike    文件:LdapThread.java   
public void run()
  {
Log.logNormal("LDap request " + m_nRequestId + ": trying to get ldap info from server " + m_csServer);
int nNbTries = 0;
while(nNbTries < 2)
{
          Hashtable<String, String> env = new Hashtable<String, String>();
          env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
          env.put(Context.PROVIDER_URL, "ldap://"+m_csServer+"/");
          env.put(Context.SECURITY_AUTHENTICATION, "simple");
          env.put(Context.SECURITY_PRINCIPAL, m_csUserId);
          env.put(Context.SECURITY_CREDENTIALS, m_csPassword);  
          if(m_ldapUtil != null)
          {
            DirContext dirContext = m_ldapUtil.getDirContext(env);
            if(dirContext != null)
            {
                m_ldapUtil.setOnceDirContext(dirContext);
                Log.logNormal("LDap request " + m_nRequestId + ": dir context correctly set");
                return;
            }
          }   
          nNbTries++;
}
if(m_NbThreadCreated.dec() <= 0)
{
    m_ldapUtil.setOnceDirContext(null);
}
Log.logCritical("LDap request " + m_nRequestId + ": dir context NOT correctly set");
  }
项目:apache-tomcat-7.0.73-with-comment    文件:JNDIRealm.java   
private void restoreEnvironmentParameter(DirContext context,
        String parameterName, Hashtable<?, ?> preservedEnvironment) {
    try {
        context.removeFromEnvironment(parameterName);
        if (preservedEnvironment != null && preservedEnvironment.containsKey(parameterName)) {
            context.addToEnvironment(parameterName,
                    preservedEnvironment.get(parameterName));
        }
    } catch (NamingException e) {
        // Ignore
    }
}
项目:Equella    文件:MemberOfGroupSearch.java   
private void collectAllSubGroupFullNames(Set<String> results, DirContext ctx, Name parent)
{
    final String fullname = parent.toString();
    if( results.add(fullname) )
    {
        for( Name child : ldap.searchAllBases(ctx, getSubgroupsByMemberOfFilter(fullname),
            new FullNameHitsCollector(), true) )
        {
            collectAllSubGroupFullNames(results, ctx, child);
        }
    }
}
项目:lazycat    文件:WebdavServlet.java   
/**
 * Determines the methods normally allowed for the resource.
 *
 */
private StringBuilder determineMethodsAllowed(DirContext dirContext, HttpServletRequest req) {

    StringBuilder methodsAllowed = new StringBuilder();
    boolean exists = true;
    Object object = null;
    try {
        String path = getRelativePath(req);

        object = dirContext.lookup(path);
    } catch (NamingException e) {
        exists = false;
    }

    if (!exists) {
        methodsAllowed.append("OPTIONS, MKCOL, PUT, LOCK");
        return methodsAllowed;
    }

    methodsAllowed.append("OPTIONS, GET, HEAD, POST, DELETE");
    // Trace - assume disabled unless we can prove otherwise
    if (req instanceof RequestFacade && ((RequestFacade) req).getAllowTrace()) {
        methodsAllowed.append(", TRACE");
    }
    methodsAllowed.append(", PROPPATCH, COPY, MOVE, LOCK, UNLOCK");

    if (listings) {
        methodsAllowed.append(", PROPFIND");
    }

    if (!(object instanceof DirContext)) {
        methodsAllowed.append(", PUT");
    }

    return methodsAllowed;
}
项目:lazycat    文件:ProxyDirContext.java   
/**
 * Retrieves the named object as a cache entry, without any exception.
 * 
 * @param name
 *            the name of the object to look up
 * @return the cache entry bound to name
 */
public CacheEntry lookupCache(String name) {
    CacheEntry entry = cacheLookup(name);
    if (entry == null) {
        entry = new CacheEntry();
        entry.name = name;
        try {
            Object object = dirContext.lookup(parseName(name));
            if (object instanceof InputStream) {
                entry.resource = new Resource((InputStream) object);
            } else if (object instanceof DirContext) {
                entry.context = (DirContext) object;
            } else if (object instanceof Resource) {
                entry.resource = (Resource) object;
            } else {
                entry.resource = new Resource(
                        new ByteArrayInputStream(object.toString().getBytes(Charset.defaultCharset())));
            }
            Attributes attributes = dirContext.getAttributes(parseName(name));
            if (!(attributes instanceof ResourceAttributes)) {
                attributes = new ResourceAttributes(attributes);
            }
            entry.attributes = (ResourceAttributes) attributes;
        } catch (NamingException e) {
            entry.exists = false;
        }
    }
    return entry;
}
项目:lams    文件:JNDIRealm.java   
/**
 * Use the distinguished name to locate the directory
 * entry for the user with the specified username and
 * return a User object; otherwise return <code>null</code>.
 *
 * @param context The directory context
 * @param username The username
 * @param attrIds String[]containing names of attributes to
 * @param dn Distinguished name of the user
 * retrieve.
 *
 * @exception NamingException if a directory server error occurs
 */
protected User getUserByPattern(DirContext context,
                                String username,
                                String[] attrIds,
                                String dn)
    throws NamingException {

    // Get required attributes from user entry
    Attributes attrs = null;
    try {
        attrs = context.getAttributes(dn, attrIds);
    } catch (NameNotFoundException e) {
        return (null);
    }
    if (attrs == null)
        return (null);

    // Retrieve value of userPassword
    String password = null;
    if (userPassword != null)
        password = getAttributeValue(userPassword, attrs);

    // Retrieve values of userRoleName attribute
    ArrayList<String> roles = null;
    if (userRoleName != null)
        roles = addAttributeValues(userRoleName, attrs, roles);

    return new User(username, dn, password, roles);
}
项目:Equella    文件:DirectoryGroupSearch.java   
@Override
public List<UserBean> getUsersInGroup(DirContext ctx, String query, String groupID, boolean recurse)
{
    if( groupID.length() == 0 )
    {
        return Collections.emptyList();
    }

    Name groupName = getFullGroupName(ctx, groupID);
    return ldap.search(ctx, groupName, ldap.getUserSearchFilter(query), new UserBeanHitsCollector(), recurse);
}
项目:apache-tomcat-7.0.73-with-comment    文件:StandardContext.java   
/**
 * Add a URL for a JAR that contains static resources in a
 * META-INF/resources directory that should be included in the static
 * resources for this context.
 */
public void addResourcesDirContext(DirContext altDirContext) {
    if (webappResources instanceof BaseDirContext) {
        ((BaseDirContext) webappResources).addAltDirContext(altDirContext);
    } else {
        log.error(sm.getString("standardContext.noResourceJar", altDirContext,
                getName()));
    }
}
项目:tomcat7    文件:TestStandardContextResources.java   
@Test
public void testResourceCaching() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-3.0-fragments");
    // app dir is relative to server home
    StandardContext ctx = (StandardContext) tomcat.addWebapp(
            null, "/test", appDir.getAbsolutePath());
    ctx.setCachingAllowed(false);

    tomcat.start();

    DirContext resources = ctx.getResources();

    Assert.assertTrue(resources instanceof ProxyDirContext);

    ProxyDirContext proxyResources = (ProxyDirContext) resources;

    // Caching should be disabled
    Assert.assertNull(proxyResources.getCache());

    ctx.stop();
    ctx.start();

    // Caching should still be disabled
    Assert.assertNull(proxyResources.getCache());
}
项目:joai-project    文件:LdapClient.java   
/**
 * <b>Deprecated:</b> Low level method: renames an entry in the LDAP database,
 * using the specified dn/pswd for authorization.
 *
 * @param host     the URI of the LDAP server.
 * @param authDn   the authorized dn (distinguished name) of the caller
 * @param password the password associated with authDn
 * @param oldDn the old dn.
 * @param newDn the new dn.
 */

public void renameEntryDn(
    String authDn,
    String password,
    String oldDn,
    String newDn)
throws LdapException
{
    chkstg( "old dn", oldDn);
    chkstg( "new dn", newDn);

    DirContext dirctx = getDirContext( authDn, password);
    try { dirctx.rename( oldDn, newDn); }
    catch( NamingException nexc) {
        if (bugs >= 1) {
            prtln("renameEntryDn: nexc: " + nexc);
            nexc.printStackTrace();
            prtln();
            prtln("authDn: \"" + authDn + "\"");
            prtln("password: \"" + password + "\"");
            prtln("oldDn: \"" + oldDn + "\"");
            prtln("newDn: \"" + newDn + "\"");
            prtln();
        }
        throw new LdapException("renameEntryDn: exception", nexc);
    }
}
项目:Equella    文件:LDAPServiceImpl.java   
@Override
public GroupBean getParentGroupForGroup(final LDAP ldap, final String groupID)
{

    return ldap.doAsAdmin(new InContext<GroupBean>()
    {
        @Override
        public GroupBean execute(DirContext ctx) throws NamingException
        {
            return ldap.getGroupSearch().getParentGroupForGroup(ctx, groupID);
        }
    });
}
项目:tomcat7    文件:ContainerBase.java   
/**
  * Return the resources DirContext object with which this Container is
  * associated.  If there is no associated resources object, return the
  * resources associated with our parent Container (if any); otherwise
  * return <code>null</code>.
 */
@Override
public DirContext getResources() {
    if (resources != null)
        return (resources);
    if (parent != null)
        return (parent.getResources());
    return (null);

}
项目:lazycat    文件:ApplicationContext.java   
/**
 * Return a Set containing the resource paths of resources member of the
 * specified collection. Each path will be a String starting with a "/"
 * character. The returned set is immutable.
 *
 * @param path
 *            Collection path
 */
@Override
public Set<String> getResourcePaths(String path) {

    // Validate the path argument
    if (path == null) {
        return null;
    }
    if (!path.startsWith("/")) {
        throw new IllegalArgumentException(sm.getString("applicationContext.resourcePaths.iae", path));
    }

    String normalizedPath;
    if (File.separatorChar == '\\') {
        // On Windows '\\' is a separator so in case a Windows style
        // separator has managed to make it into the path, replace it.
        normalizedPath = RequestUtil.normalize(path, true);
    } else {
        // On UNIX and similar systems, '\\' is a valid file name so do not
        // convert it to '/'
        normalizedPath = RequestUtil.normalize(path, false);
    }
    if (normalizedPath == null)
        return (null);

    DirContext resources = context.getResources();
    if (resources != null) {
        return (getResourcePathsInternal(resources, normalizedPath));
    }
    return (null);

}
项目:lazycat    文件:ApplicationContext.java   
/**
 * Internal implementation of getResourcesPath() logic.
 *
 * @param resources
 *            Directory context to search
 * @param path
 *            Collection path
 */
private Set<String> getResourcePathsInternal(DirContext resources, String path) {

    ResourceSet<String> set = new ResourceSet<String>();
    try {
        listCollectionPaths(set, resources, path);
    } catch (NamingException e) {
        return (null);
    }
    set.setLocked(true);
    return (set);

}
项目:tomcat7    文件:DirContextURLStreamHandler.java   
/**
 * Get the bound context.
 */
public static DirContext get() {

    DirContext result = null;

    Thread currentThread = Thread.currentThread();
    ClassLoader currentCL = currentThread.getContextClassLoader();

    // Checking CL binding
    result = clBindings.get(currentCL);
    if (result != null)
        return result;

    // Checking thread biding
    result = threadBindings.get(currentThread);

    // Checking parent CL binding
    currentCL = currentCL.getParent();
    while (currentCL != null) {
        result = clBindings.get(currentCL);
        if (result != null)
            return result;
        currentCL = currentCL.getParent();
    }

    if (result == null)
        throw new IllegalStateException("Illegal class loader binding");

    return result;

}
项目:apache-tomcat-7.0.73-with-comment    文件:ProxyDirContext.java   
/**
 * Retrieves the named object as a cache entry, without any exception.
 * 
 * @param name the name of the object to look up
 * @return the cache entry bound to name
 */
public CacheEntry lookupCache(String name) {
    CacheEntry entry = cacheLookup(name);
    if (entry == null) {
        entry = new CacheEntry();
        entry.name = name;
        try {
            Object object = dirContext.lookup(parseName(name));
            if (object instanceof InputStream) {
                entry.resource = new Resource((InputStream) object);
            } else if (object instanceof DirContext) {
                entry.context = (DirContext) object;
            } else if (object instanceof Resource) {
                entry.resource = (Resource) object;
            } else {
                entry.resource = new Resource(new ByteArrayInputStream
                    (object.toString().getBytes(Charset.defaultCharset())));
            }
            Attributes attributes = dirContext.getAttributes(parseName(name));
            if (!(attributes instanceof ResourceAttributes)) {
                attributes = new ResourceAttributes(attributes);
            }
            entry.attributes = (ResourceAttributes) attributes;
        } catch (NamingException e) {
            entry.exists = false;
        }
    }
    return entry;
}
项目:lams    文件:ApplicationContext.java   
/**
 * Internal implementation of getResourcesPath() logic.
 *
 * @param resources Directory context to search
 * @param path Collection path
 */
private Set getResourcePathsInternal(DirContext resources, String path) {

    ResourceSet set = new ResourceSet();
    try {
        listCollectionPaths(set, resources, path);
    } catch (NamingException e) {
        return (null);
    }
    set.setLocked(true);
    return (set);

}