Java 类javax.naming.ldap.LdapContext 实例源码

项目:g3server    文件:LdapGroupProvider.java   
public Group getGroup(String groupName) throws GroupNotFoundException {
    LdapContext ctx = null;
    try {
        String groupDN = manager.findGroupDN(groupName);
        // Load record.
        ctx = manager.getContext(manager.getGroupsBaseDN(groupName));
        Attributes attrs = ctx.getAttributes(groupDN, standardAttributes);

        return processGroup(ctx, attrs);
    }
    catch (Exception e) {
        Log.error(e.getMessage(), e);
        throw new GroupNotFoundException("Group with name " + groupName + " not found.", e);
    }
    finally {
        try {
            if (ctx != null) {
                ctx.setRequestControls(null);
                ctx.close();
            }
        }
        catch (Exception ignored) {
            // Ignore.
        }
    }
}
项目:neo4j-example-auth-plugins    文件:LdapGroupHasUsersAuthPlugin.java   
@Override
public AuthInfo authenticateAndAuthorize( AuthToken authToken ) throws AuthenticationException
{
    try
    {
        String username = authToken.principal();
        char[] password = authToken.credentials();

        api.log().info( "Log in attempted for user '" + username + "'.");

        LdapContext ctx = authenticate( username, password );

        api.log().info( "User '" + username + "' authenticated." );

        Set<String> roles = authorize( ctx, username );

        api.log().info( "User '" + username + "' authorized roles " + roles );

        return AuthInfo.of( username, roles );
    }
    catch ( NamingException e )
    {
        throw new AuthenticationException( e.getMessage() );
    }
}
项目:rabbitframework    文件:DefaultLdapRealm.java   
/**
 * This implementation opens an LDAP connection using the token's
 * {@link #getLdapPrincipal(org.apache.shiro.authc.AuthenticationToken) discovered principal} and provided
 * {@link AuthenticationToken#getCredentials() credentials}.  If the connection opens successfully, the
 * authentication attempt is immediately considered successful and a new
 * {@link AuthenticationInfo} instance is
 * {@link #createAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken, Object, Object, javax.naming.ldap.LdapContext) created}
 * and returned.  If the connection cannot be opened, either because LDAP authentication failed or some other
 * JNDI problem, an {@link NamingException} will be thrown.
 *
 * @param token              the submitted authentication token that triggered the authentication attempt.
 * @param ldapContextFactory factory used to retrieve LDAP connections.
 * @return an {@link AuthenticationInfo} instance representing the authenticated user's information.
 * @throws NamingException if any LDAP errors occur.
 */
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token,
                                                        LdapContextFactory ldapContextFactory)
        throws NamingException {

    Object principal = token.getPrincipal();
    Object credentials = token.getCredentials();

    log.debug("Authenticating user '{}' through LDAP", principal);

    principal = getLdapPrincipal(token);

    LdapContext ctx = null;
    try {
        ctx = ldapContextFactory.getLdapContext(principal, credentials);
        //context was opened successfully, which means their credentials were valid.  Return the AuthenticationInfo:
        return createAuthenticationInfo(token, principal, credentials, ctx);
    } finally {
        LdapUtils.closeContext(ctx);
    }
}
项目:Camel    文件:LdapProducer.java   
private boolean prepareNextPage(LdapContext ldapContext) throws Exception {
    Control[] responseControls = ldapContext.getResponseControls();

    byte[] cookie = null;
    if (responseControls != null) {
        for (Control responseControl : responseControls) {
            if (responseControl instanceof PagedResultsResponseControl) {
                PagedResultsResponseControl prrc = (PagedResultsResponseControl) responseControl;
                cookie = prrc.getCookie();
            }
        }
    }

    if (cookie == null) {
        return false;
    } else {
        ldapContext.setRequestControls(new Control[]{new PagedResultsControl(pageSize, cookie, Control.CRITICAL)});
        return true;
    }
}
项目:directory-ldap-api    文件:TriggerUtils.java   
/**
 * Create the Trigger execution subentry
 * 
 * @param apCtx The administration point context
 * @param subentryCN The CN used by the suentry
 * @param subtreeSpec The subtree specification
 * @param prescriptiveTriggerSpec The prescriptive trigger specification
 * @throws NamingException If the operation failed
 */
public static void createTriggerExecutionSubentry(
    LdapContext apCtx,
    String subentryCN,
    String subtreeSpec,
    String prescriptiveTriggerSpec ) throws NamingException
{
    Attributes subentry = new BasicAttributes( SchemaConstants.CN_AT, subentryCN, true );
    Attribute objectClass = new BasicAttribute( SchemaConstants.OBJECT_CLASS_AT );
    subentry.put( objectClass );
    objectClass.add( SchemaConstants.TOP_OC );
    objectClass.add( SchemaConstants.SUBENTRY_OC );
    objectClass.add( SchemaConstants.TRIGGER_EXECUTION_SUBENTRY_OC );
    subentry.put( SchemaConstants.SUBTREE_SPECIFICATION_AT, subtreeSpec );
    subentry.put( SchemaConstants.PRESCRIPTIVE_TRIGGER_SPECIFICATION_AT, prescriptiveTriggerSpec );
    apCtx.createSubcontext( "cn=" + subentryCN, subentry );
}
项目:centraldogma    文件:SearchFirstActiveDirectoryRealm.java   
/**
 * Builds an {@link AuthenticationInfo} object by querying the active directory LDAP context for the
 * specified username.
 */
@Override
protected AuthenticationInfo queryForAuthenticationInfo(
        AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {

    final UsernamePasswordToken upToken = ensureUsernamePasswordToken(token);
    final String userDn = findUserDn(ldapContextFactory, upToken.getUsername());

    LdapContext ctx = null;
    try {
        // Binds using the username and password provided by the user.
        ctx = ldapContextFactory.getLdapContext(userDn, upToken.getPassword());
    } finally {
        LdapUtils.closeContext(ctx);
    }
    return buildAuthenticationInfo(upToken.getUsername(), upToken.getPassword());
}
项目:uavstack    文件:GUISSOLdapClient.java   
private void clearLdapContext(String action) {

        try {
            loggerInfo("LDAPContext", "清空", "开始", action);

            if (ldapContexts.containsKey(action)) {
                LdapContext context = ldapContexts.get(action);
                context.close();
                context = null;
                ldapContexts.remove(action);
            }

            loggerInfo("LDAPContext", "清空", "完成", action);
        }
        catch (Exception e) {
            loggerError("LDAPContext清空", action, e);
        }

    }
项目:helium    文件:PersonesPluginLdap.java   
private LdapContext getContext() throws Exception {
    Hashtable<String, String> envDC = new Hashtable<String, String>();
    envDC.put(
            Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
    envDC.put(
            Context.PROVIDER_URL,
            GlobalProperties.getInstance().getProperty("app.persones.plugin.ldap.url"));
    envDC.put(
            Context.SECURITY_AUTHENTICATION,
            "simple");
    envDC.put(
            Context.SECURITY_PRINCIPAL,
            GlobalProperties.getInstance().getProperty("app.persones.plugin.ldap.principal"));
    envDC.put(
            Context.SECURITY_CREDENTIALS,
            GlobalProperties.getInstance().getProperty("app.persones.plugin.ldap.credentials"));
    return new InitialLdapContext(envDC, null);
}
项目:cosmic    文件:LdapManagerImpl.java   
@Override
public LdapConfigurationResponse addConfiguration(final String hostname, final int port) throws InvalidParameterValueException {
    LdapConfigurationVO configuration = _ldapConfigurationDao.findByHostname(hostname);
    if (configuration == null) {
        LdapContext context = null;
        try {
            final String providerUrl = "ldap://" + hostname + ":" + port;
            context = _ldapContextFactory.createBindContext(providerUrl);
            configuration = new LdapConfigurationVO(hostname, port);
            _ldapConfigurationDao.persist(configuration);
            s_logger.info("Added new ldap server with hostname: " + hostname);
            return new LdapConfigurationResponse(hostname, port);
        } catch (NamingException | IOException e) {
            s_logger.debug("NamingException while doing an LDAP bind", e);
            throw new InvalidParameterValueException("Unable to bind to the given LDAP server");
        } finally {
            closeContext(context);
        }
    } else {
        throw new InvalidParameterValueException("Duplicate configuration");
    }
}
项目:cosmic    文件:ADLdapUserManagerImpl.java   
@Override
public List<LdapUser> getUsersInGroup(final String groupName, final LdapContext context) throws NamingException {
    if (StringUtils.isBlank(groupName)) {
        throw new IllegalArgumentException("ldap group name cannot be blank");
    }

    final String basedn = _ldapConfiguration.getBaseDn();
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException("ldap basedn is not configured");
    }

    final SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    final NamingEnumeration<SearchResult> results = context.search(basedn, generateADGroupSearchFilter(groupName), searchControls);
    final List<LdapUser> users = new ArrayList<>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result));
    }
    return users;
}
项目:cosmic    文件:OpenLdapUserManagerImpl.java   
public LdapUser searchUser(final String basedn, final String searchString, final LdapContext context) throws NamingException, IOException {
    final SearchControls searchControls = new SearchControls();

    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    final NamingEnumeration<SearchResult> results = context.search(basedn, searchString, searchControls);
    final List<LdapUser> users = new ArrayList<>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result));
    }

    if (users.size() == 1) {
        return users.get(0);
    } else {
        throw new NamingException("No user found for basedn " + basedn + " and searchString " + searchString);
    }
}
项目:rabbitframework    文件:ActiveDirectoryRealm.java   
/**
 * Builds an {@link org.apache.shiro.authz.AuthorizationInfo} object by querying the active directory LDAP context for the
 * groups that a user is a member of.  The groups are then translated to role names by using the
 * configured {@link #groupRolesMap}.
 * <p/>
 * This implementation expects the <tt>principal</tt> argument to be a String username.
 * <p/>
 * Subclasses can override this method to determine authorization data (roles, permissions, etc) in a more
 * complex way.  Note that this default implementation does not support permissions, only roles.
 *
 * @param principals         the principal of the Subject whose account is being retrieved.
 * @param ldapContextFactory the factory used to create LDAP connections.
 * @return the AuthorizationInfo for the given Subject principal.
 * @throws NamingException if an error occurs when searching the LDAP server.
 */
protected AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals, LdapContextFactory ldapContextFactory) throws NamingException {

    String username = (String) getAvailablePrincipal(principals);

    // Perform context search
    LdapContext ldapContext = ldapContextFactory.getSystemLdapContext();

    Set<String> roleNames;

    try {
        roleNames = getRoleNamesForUser(username, ldapContext);
    } finally {
        LdapUtils.closeContext(ldapContext);
    }

    return buildAuthorizationInfo(roleNames);
}
项目:Camel    文件:LdapProducer.java   
public void process(Exchange exchange) throws Exception {
    String filter = exchange.getIn().getBody(String.class);
    DirContext dirContext = getDirContext();

    try {
        // could throw NamingException
        List<SearchResult> data;
        if (pageSize == null) {
            data = simpleSearch(dirContext, filter);
        } else {
            if (!(dirContext instanceof LdapContext)) {
                throw new IllegalArgumentException("When using attribute 'pageSize' for a ldap endpoint, you must provide a LdapContext (subclass of DirContext)");
            }
            data = pagedSearch((LdapContext) dirContext, filter);
        }
        exchange.getOut().setBody(data);
        exchange.getOut().setHeaders(exchange.getIn().getHeaders());
        exchange.getOut().setAttachments(exchange.getIn().getAttachments());
    } finally {
        if (dirContext != null) {
            dirContext.close();
        }
    }
}
项目:Camel    文件:LdapProducer.java   
private List<SearchResult> pagedSearch(LdapContext ldapContext, String searchFilter) throws Exception {
    List<SearchResult> data = new ArrayList<SearchResult>();

    log.trace("Using paged ldap search, pageSize={}", pageSize);

    Control[] requestControls = new Control[]{new PagedResultsControl(pageSize, Control.CRITICAL)};
    ldapContext.setRequestControls(requestControls);
    do {
        List<SearchResult> pageResult = simpleSearch(ldapContext, searchFilter);
        data.addAll(pageResult);
        log.trace("Page returned {} entries", pageResult.size());
    } while (prepareNextPage(ldapContext));

    if (log.isDebugEnabled()) {
        log.debug("Found a total of {} entries for ldap filter {}", data.size(), searchFilter);
    }

    return data;
}
项目:ldapchai    文件:JNDIProviderImpl.java   
@LdapOperation
@ModifyOperation
public final void deleteEntry( final String entryDN )
        throws ChaiUnavailableException, ChaiOperationException
{
    activityPreCheck();
    getInputValidator().deleteEntry( entryDN );

    final LdapContext ldapConnection = getLdapConnection();
    try
    {
        ldapConnection.destroySubcontext( addJndiEscape( entryDN ) );
    }
    catch ( NamingException e )
    {
        convertNamingException( e );
    }
}
项目:ldapchai    文件:JNDIProviderImpl.java   
private LdapContext getLdapConnection()
        throws ChaiUnavailableException
{
    try
    {
        if ( socketFactory != null )
        {
            ThreadLocalSocketFactory.set( socketFactory );
        }
        return jndiConnection.newInstance( null );
    }
    catch ( NamingException e )
    {
        final String errorMsg = "error creating new jndiConnection instance: " + e.getMessage();
        throw new ChaiUnavailableException( errorMsg, ChaiError.CHAI_INTERNAL_ERROR );
    }
}
项目:OEPv2    文件:ManagerLdap.java   
public void changePassord(ServiceContext serviceContext, User user, String password) throws Exception{
    long companyId = serviceContext.getCompanyId();
    Properties userMappings = getUserMappings(serviceContext.getCompanyId());
    Binding binding = getUser(companyId, user.getScreenName());
    System.out.println("bingging " + binding);
    System.out.println("Pass " + user.getPassword());
    String name = StringPool.BLANK;
    StringBuilder sb = new StringBuilder();
    LdapContext ctx = getContext(serviceContext.getCompanyId());
       sb = new StringBuilder();
    sb.append(userMappings.getProperty("screenName"));
    sb.append(StringPool.EQUAL);
    sb.append(user.getScreenName());
    sb.append(StringPool.COMMA);
    sb.append(getUsersDN(companyId));
    name = sb.toString();
    Modifications mods = Modifications.getInstance();  

    mods.addItem(userMappings.getProperty(UserConverterKeys.PASSWORD),password);
    ModificationItem[] modItems = mods.getItems();
    if (binding != null) {
        ctx.modifyAttributes(name, modItems);
    }

}
项目:OEPv2    文件:EmployeeExportToLdap.java   
public void updateLdapZimbra(LdapContext ctx ,User user,String name, Employee emp) throws NamingException{
    Modifications mods = Modifications.getInstance();
       for (int i = 0; i < 5;i++){
         mods.addItem(zimbraProperty[i][0],zimbraProperty[i][1]);
       }
       mods.addItem("zimbramaildeliveryaddress",user.getEmailAddress());

      // mods.addItem("company",user.getEmailAddress());
     //  mods.addItem("street",user.getEmailAddress());
      //.addItem("company",user.getEmailAddress());
      // mods.addItem("company",user.getEmailAddress());
    //System.out.println("My  " + mods);
       ModificationItem[] modItems = mods.getItems();
       ctx.modifyAttributes(name, modItems);
       //= getContext(serviceContext.getCompanyId());

}
项目:zeppelin    文件:LdapGroupRealm.java   
public Set<String> getRoleNamesForUser(String username,
                                       LdapContext ldapContext,
                                       String userDnTemplate) throws NamingException {
  try {
    Set<String> roleNames = new LinkedHashSet<>();

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String searchFilter = "(&(objectClass=groupOfNames)(member=" + userDnTemplate + "))";
    Object[] searchArguments = new Object[]{username};

    NamingEnumeration<?> answer = ldapContext.search(
        String.valueOf(ldapContext.getEnvironment().get("ldap.searchBase")),
        searchFilter,
        searchArguments,
        searchCtls);

    while (answer.hasMoreElements()) {
      SearchResult sr = (SearchResult) answer.next();
      Attributes attrs = sr.getAttributes();
      if (attrs != null) {
        NamingEnumeration<?> ae = attrs.getAll();
        while (ae.hasMore()) {
          Attribute attr = (Attribute) ae.next();
          if (attr.getID().equals("cn")) {
            roleNames.add((String) attr.get());
          }
        }
      }
    }
    return roleNames;

  } catch (Exception e) {
    LOG.error("Error", e);
  }

  return new HashSet<>();
}
项目:zeppelin    文件:ActiveDirectoryGroupRealm.java   
/**
 * Builds an {@link AuthenticationInfo} object by querying the active directory LDAP context for
 * the specified username.  This method binds to the LDAP server using the provided username
 * and password - which if successful, indicates that the password is correct.
 * <p/>
 * This method can be overridden by subclasses to query the LDAP server in a more complex way.
 *
 * @param token              the authentication token provided by the user.
 * @param ldapContextFactory the factory used to build connections to the LDAP server.
 * @return an {@link AuthenticationInfo} instance containing information retrieved from LDAP.
 * @throws NamingException if any LDAP errors occur during the search.
 */
protected AuthenticationInfo queryForAuthenticationInfo(
    AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {

  UsernamePasswordToken upToken = (UsernamePasswordToken) token;

  // Binds using the username and password provided by the user.
  LdapContext ctx = null;
  try {
    String userPrincipalName = upToken.getUsername();
    if (!isValidPrincipalName(userPrincipalName)) {
      return null;
    }
    if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) {
      userPrincipalName = upToken.getUsername() + this.principalSuffix;
    }
    ctx = ldapContextFactory.getLdapContext(
        userPrincipalName, upToken.getPassword());
  } finally {
    LdapUtils.closeContext(ctx);
  }

  return buildAuthenticationInfo(upToken.getUsername(), upToken.getPassword());
}
项目:zeppelin    文件:ActiveDirectoryGroupRealm.java   
/**
 * Builds an {@link org.apache.shiro.authz.AuthorizationInfo} object by querying the active
 * directory LDAP context for the groups that a user is a member of.  The groups are then
 * translated to role names by using the configured {@link #groupRolesMap}.
 * <p/>
 * This implementation expects the <tt>principal</tt> argument to be a String username.
 * <p/>
 * Subclasses can override this method to determine authorization data (roles, permissions, etc)
 * in a more complex way.  Note that this default implementation does not support permissions,
 * only roles.
 *
 * @param principals         the principal of the Subject whose account is being retrieved.
 * @param ldapContextFactory the factory used to create LDAP connections.
 * @return the AuthorizationInfo for the given Subject principal.
 * @throws NamingException if an error occurs when searching the LDAP server.
 */
protected AuthorizationInfo queryForAuthorizationInfo(
    PrincipalCollection principals,
    LdapContextFactory ldapContextFactory) throws NamingException {

  String username = (String) getAvailablePrincipal(principals);

  // Perform context search
  LdapContext ldapContext = ldapContextFactory.getSystemLdapContext();

  Set<String> roleNames;

  try {
    roleNames = getRoleNamesForUser(username, ldapContext);
  } finally {
    LdapUtils.closeContext(ldapContext);
  }

  return buildAuthorizationInfo(roleNames);
}
项目:zeppelin    文件:LdapRealm.java   
private Set<String> getRoles(PrincipalCollection principals, 
      final LdapContextFactory ldapContextFactory)
    throws NamingException {
  final String username = (String) getAvailablePrincipal(principals);

  LdapContext systemLdapCtx = null;
  try {
    systemLdapCtx = ldapContextFactory.getSystemLdapContext();
    return rolesFor(principals, username, systemLdapCtx,
      ldapContextFactory, SecurityUtils.getSubject().getSession());
  } catch (AuthenticationException ae) {
    ae.printStackTrace();
    return Collections.emptySet();
  } finally {
    LdapUtils.closeContext(systemLdapCtx);
  }
}
项目:cukes    文件:EntityService.java   
public void deleteEntityByDn(String dn) {
    try {
        LdapContext context = connectionService.getContext();
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration<SearchResult> children = context.search(dn, "(objectclass=*)", searchControls);
        TreeSet<String> dnsToDelete = new TreeSet<>(new DnComparator(true));
        while (children.hasMoreElements()) {
            SearchResult childResult = children.nextElement();
            String childDn = childResult.getNameInNamespace();
            dnsToDelete.add(childDn);
        }
        for (String s : dnsToDelete) {
            context.destroySubcontext(s);
        }
    } catch (NamingException e) {
        throw new CukesRuntimeException("Cannot delete entity by dn " + dn, e);
    } finally {
        connectionService.close();
    }
}
项目:cukes    文件:EntityService.java   
public List<Attributes> searchByFilter(String dn, String filter){
    try {
        LdapContext context = connectionService.getContext();
        NamingEnumeration<SearchResult> searchResults = context.search(dn, filter, new SearchControls());
        List<Attributes> attributesList = new ArrayList<>();
        while (searchResults.hasMore()) {
            SearchResult searchResult = searchResults.next();
            attributesList.add(searchResult.getAttributes());
        }
        return attributesList;
    } catch (NamingException ex) {
        throw new CukesRuntimeException(ex);
    } finally {
        connectionService.close();
    }
}
项目:teiid    文件:LDAPDirectSearchQueryExecution.java   
@Override
public void execute() throws TranslatorException {
    IQueryToLdapSearchParser parser = new IQueryToLdapSearchParser(this.executionFactory);
    LDAPSearchDetails details = parser.buildRequest(query);
    // Create and configure the new search context.
    LdapContext context =  createSearchContext(details.getContextName());

    // build search controls
    SearchControls controls = new SearchControls();
    controls.setSearchScope(details.getSearchScope());
    controls.setTimeLimit(details.getTimeLimit());
    controls.setCountLimit(details.getCountLimit());
    controls.setReturningAttributes(details.getAttributes());

    this.delegate = new LDAPQueryExecution(context, details, controls, this.executionFactory, this.executionContext);
    this.delegate.execute();        
}
项目:teiid    文件:TestLDAPDirectQueryExecution.java   
@Test public void testSearch() throws Exception {
    String input = "exec native('search;context-name=corporate;filter=(objectClass=*);count-limit=5;timeout=6;search-scope=ONELEVEL_SCOPE;attributes=uid,cn')"; 

    TranslationUtility util = FakeTranslationFactory.getInstance().getExampleTranslationUtility();
    Command command = util.parseCommand(input);
    ExecutionContext ec = Mockito.mock(ExecutionContext.class);
    RuntimeMetadata rm = Mockito.mock(RuntimeMetadata.class);
    LdapContext connection = Mockito.mock(LdapContext.class);
    LdapContext ctx = Mockito.mock(LdapContext.class);
    Mockito.stub(connection.lookup("corporate")).toReturn(ctx);

    LDAPDirectSearchQueryExecution execution = (LDAPDirectSearchQueryExecution)TRANSLATOR.createExecution(command, ec, rm, connection);
    execution.execute();
    LDAPSearchDetails details = execution.getDelegate().getSearchDetails();

    assertEquals("corporate", details.getContextName());
    assertEquals("(objectClass=*)", details.getContextFilter());
    assertEquals(5, details.getCountLimit());
    assertEquals(6, details.getTimeLimit());
    assertEquals(1, details.getSearchScope());
    assertEquals(2, details.getElementList().size());
    assertEquals("uid", details.getElementList().get(0).getName());
    assertEquals("cn", details.getElementList().get(1).getName());
}
项目:teiid    文件:TestLDAPDirectQueryExecution.java   
@Test public void testSearchDefaultsAndEscaping() throws Exception {
    String input = "exec native('search;context-name=corporate;filter=(;;)')"; 

    TranslationUtility util = FakeTranslationFactory.getInstance().getExampleTranslationUtility();
    Command command = util.parseCommand(input);
    ExecutionContext ec = Mockito.mock(ExecutionContext.class);
    RuntimeMetadata rm = Mockito.mock(RuntimeMetadata.class);
    LdapContext connection = Mockito.mock(LdapContext.class);
    LdapContext ctx = Mockito.mock(LdapContext.class);
    Mockito.stub(connection.lookup("corporate")).toReturn(ctx);

    LDAPDirectSearchQueryExecution execution = (LDAPDirectSearchQueryExecution)TRANSLATOR.createExecution(command, ec, rm, connection);
    execution.execute();
    LDAPSearchDetails details = execution.getDelegate().getSearchDetails();

    assertEquals("corporate", details.getContextName());
    assertEquals("(;)", details.getContextFilter());
    assertEquals(-1, details.getCountLimit());
    assertEquals(0, details.getTimeLimit());
    assertEquals(1, details.getSearchScope());
    assertEquals(0, details.getElementList().size());
}
项目:teiid    文件:TestLDAPDirectQueryExecution.java   
@Test public void testDelete() throws Exception {
      String input = "exec native('delete;uid=doe,ou=people,o=teiid.org')"; 

      TranslationUtility util = FakeTranslationFactory.getInstance().getExampleTranslationUtility();
      Command command = util.parseCommand(input);
      ExecutionContext ec = Mockito.mock(ExecutionContext.class);
      RuntimeMetadata rm = Mockito.mock(RuntimeMetadata.class);
      LdapContext connection = Mockito.mock(LdapContext.class);
      LdapContext ctx = Mockito.mock(LdapContext.class);
      Mockito.stub(connection.lookup("")).toReturn(ctx);

      LDAPDirectCreateUpdateDeleteQueryExecution execution = (LDAPDirectCreateUpdateDeleteQueryExecution)TRANSLATOR.createExecution(command, ec, rm, connection);
execution.execute();

Mockito.verify(ctx, Mockito.times(1)).destroySubcontext("uid=doe,ou=people,o=teiid.org");
  }
项目:teiid    文件:TestLDAPDirectQueryExecution.java   
@Test public void testUpdate() throws Exception {
      String input = "exec native('update;uid=doe,ou=people,o=teiid.org;attributes=one,two,three', 'one', 2, 3.0)"; 

      TranslationUtility util = FakeTranslationFactory.getInstance().getExampleTranslationUtility();
      Command command = util.parseCommand(input);
      ExecutionContext ec = Mockito.mock(ExecutionContext.class);
      RuntimeMetadata rm = Mockito.mock(RuntimeMetadata.class);
      LdapContext connection = Mockito.mock(LdapContext.class);
      LdapContext ctx = Mockito.mock(LdapContext.class);
      Mockito.stub(connection.lookup("")).toReturn(ctx);

      LDAPDirectCreateUpdateDeleteQueryExecution execution = (LDAPDirectCreateUpdateDeleteQueryExecution)TRANSLATOR.createExecution(command, ec, rm, connection);
execution.execute();

ArgumentCaptor<String> nameArgument = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<ModificationItem[]> modificationItemArgument = ArgumentCaptor.forClass(ModificationItem[].class);
Mockito.verify(ctx).modifyAttributes(nameArgument.capture(),modificationItemArgument.capture());

assertEquals("uid=doe,ou=people,o=teiid.org", nameArgument.getValue());
assertEquals("one", modificationItemArgument.getValue()[0].getAttribute().getID());
assertEquals("one", modificationItemArgument.getValue()[0].getAttribute().get());
assertEquals("two", modificationItemArgument.getValue()[1].getAttribute().getID());
assertEquals("2", modificationItemArgument.getValue()[1].getAttribute().get());
assertEquals("three", modificationItemArgument.getValue()[2].getAttribute().getID());
assertEquals("3.0", modificationItemArgument.getValue()[2].getAttribute().get());
  }
项目:teiid    文件:TestLDAPDirectQueryExecution.java   
@Test public void testCreate() throws Exception {
      String input = "exec native('create;uid=doe,ou=people,o=teiid.org;attributes=one,two,three', 'one', 2, 3.0)"; 

      TranslationUtility util = FakeTranslationFactory.getInstance().getExampleTranslationUtility();
      Command command = util.parseCommand(input);
      ExecutionContext ec = Mockito.mock(ExecutionContext.class);
      RuntimeMetadata rm = Mockito.mock(RuntimeMetadata.class);
      LdapContext connection = Mockito.mock(LdapContext.class);
      LdapContext ctx = Mockito.mock(LdapContext.class);
      Mockito.stub(connection.lookup("")).toReturn(ctx);

      LDAPDirectCreateUpdateDeleteQueryExecution execution = (LDAPDirectCreateUpdateDeleteQueryExecution)TRANSLATOR.createExecution(command, ec, rm, connection);
execution.execute();

ArgumentCaptor<String> nameArgument = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<BasicAttributes> createItemArgument = ArgumentCaptor.forClass(BasicAttributes.class);
Mockito.verify(ctx).createSubcontext(nameArgument.capture(), createItemArgument.capture());

assertEquals("uid=doe,ou=people,o=teiid.org", nameArgument.getValue());
assertEquals("one", createItemArgument.getValue().get("one").getID());
assertEquals("one", createItemArgument.getValue().get("one").get());
assertEquals("two", createItemArgument.getValue().get("two").getID());
assertEquals("2", createItemArgument.getValue().get("two").get());
assertEquals("three", createItemArgument.getValue().get("three").getID());
assertEquals("3.0", createItemArgument.getValue().get("three").get());
  }
项目:teiid    文件:TestIQueryToLdapSearchParser.java   
@Test public void testUpdateNull() throws Exception {
      String sql = "update LdapModel.People set userid = 1, name = null where dn = 'x'"; //$NON-NLS-1$

      QueryMetadataInterface metadata = exampleLdap();

      Update query = (Update)getCommand(sql, metadata);

      LDAPExecutionFactory config = new LDAPExecutionFactory();

      LdapContext context = Mockito.mock(LdapContext.class);

      Mockito.stub(context.lookup("")).toReturn(context);

LDAPUpdateExecution lue = new LDAPUpdateExecution(query, context);

      lue.execute();
      ArgumentCaptor<ModificationItem[]> captor = ArgumentCaptor.forClass(ModificationItem[].class);
      Mockito.verify(context).modifyAttributes(ArgumentCaptor.forClass(String.class).capture(), captor.capture());
      ModificationItem[] modifications = captor.getValue();
      assertEquals(2, modifications.length);
      assertEquals("uid: 1", modifications[0].getAttribute().toString());
      assertEquals("cn: null", modifications[1].getAttribute().toString());
  }
项目:teiid    文件:TestIQueryToLdapSearchParser.java   
@Test public void testUpdateArray() throws Exception {
      String sql = "update LdapModel.People set userid = 1, vals = ('a','b') where dn = 'x'"; //$NON-NLS-1$

      QueryMetadataInterface metadata = exampleLdap();

      Update query = (Update)getCommand(sql, metadata);

      LDAPExecutionFactory config = new LDAPExecutionFactory();

      LdapContext context = Mockito.mock(LdapContext.class);

      Mockito.stub(context.lookup("")).toReturn(context);

LDAPUpdateExecution lue = new LDAPUpdateExecution(query, context);

      lue.execute();
      ArgumentCaptor<ModificationItem[]> captor = ArgumentCaptor.forClass(ModificationItem[].class);
      Mockito.verify(context).modifyAttributes(ArgumentCaptor.forClass(String.class).capture(), captor.capture());
      ModificationItem[] modifications = captor.getValue();
      assertEquals(2, modifications.length);
      assertEquals("uid: 1", modifications[0].getAttribute().toString());
      assertEquals("vals: a, b", modifications[1].getAttribute().toString());
  }
项目:olat    文件:LDAPLoginManagerImpl.java   
private byte[] getCookie(final LdapContext ctx) throws NamingException, IOException {
    byte[] cookie = null;
    // Examine the paged results control response
    final Control[] controls = ctx.getResponseControls();
    if (controls != null) {
        for (int i = 0; i < controls.length; i++) {
            if (controls[i] instanceof PagedResultsResponseControl) {
                final PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                cookie = prrc.getCookie();
            }
        }
    }
    // Re-activate paged results
    ctx.setRequestControls(new Control[] { new PagedResultsControl(PAGE_SIZE, cookie, Control.CRITICAL) });
    return cookie;
}
项目:olat    文件:LDAPLoginManagerImpl.java   
private byte[] getCookie(final LdapContext ctx) throws NamingException, IOException {
    byte[] cookie = null;
    // Examine the paged results control response
    final Control[] controls = ctx.getResponseControls();
    if (controls != null) {
        for (int i = 0; i < controls.length; i++) {
            if (controls[i] instanceof PagedResultsResponseControl) {
                final PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                cookie = prrc.getCookie();
            }
        }
    }
    // Re-activate paged results
    ctx.setRequestControls(new Control[] { new PagedResultsControl(PAGE_SIZE, cookie, Control.CRITICAL) });
    return cookie;
}
项目:glowroot    文件:LdapAuthentication.java   
@Instrumentation.TraceEntry(message = "get ldap user DN for username: {{1}}", timer = "ldap")
private static @Nullable String getUserDn(LdapContext ldapContext, String username,
        LdapConfig ldapConfig) throws NamingException {
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration<?> namingEnum = ldapContext.search(ldapConfig.userBaseDn(),
            ldapConfig.userSearchFilter(), new String[] {username}, searchCtls);
    try {
        if (!namingEnum.hasMore()) {
            return null;
        }
        SearchResult result = (SearchResult) checkNotNull(namingEnum.next());
        String userDn = result.getNameInNamespace();
        if (namingEnum.hasMore()) {
            throw new IllegalStateException("More than matching user: " + username);
        }
        return userDn;
    } finally {
        namingEnum.close();
    }
}
项目:glowroot    文件:LdapAuthentication.java   
@Instrumentation.TraceEntry(message = "get ldap group DNs for user DN: {{1}}", timer = "ldap")
private static Set<String> getGroupDnsForUserDn(LdapContext ldapContext, String userDn,
        LdapConfig ldapConfig) throws NamingException {
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration<?> namingEnum = ldapContext.search(ldapConfig.groupBaseDn(),
            ldapConfig.groupSearchFilter(), new String[] {userDn}, searchCtls);
    try {
        Set<String> ldapGroups = Sets.newHashSet();
        while (namingEnum.hasMore()) {
            SearchResult result = (SearchResult) checkNotNull(namingEnum.next());
            ldapGroups.add(result.getNameInNamespace());
        }
        return ldapGroups;
    } finally {
        namingEnum.close();
    }
}
项目:cn1    文件:LdapContextImpl.java   
public ExtendedResponse extendedOperation(ExtendedRequest request)
        throws NamingException {
    ExtendedOp op = new ExtendedOp(request);
    try {
        doBasicOperation(op);
    } catch (ReferralException e) {
        if (isFollowReferral(e)) {
            LdapContext referralContext = (LdapContext) getReferralContext(e);
            return referralContext.extendedOperation(request);
        }
        throw e;
    }
    ExtendedResponse response = op.getExtendedResponse();
    // set existing underlying socket to startTls extended response
    if (response instanceof StartTlsResponseImpl) {
        ((StartTlsResponseImpl) response).setSocket(client.getSocket());
    }
    return response;
}
项目:cn1    文件:ldapURLContextTest.java   
public void testGetRootURLContext2() throws Exception {
    Hashtable<Object, Object> initialEnv = new Hashtable<Object, Object>();
    initialEnv.put(Context.REFERRAL, "throw");
    initialEnv.put("test.getRootURLContext", "test");

    MockLdapURLContext context = new MockLdapURLContext(initialEnv);

    Hashtable<Object, Object> env = new Hashtable<Object, Object>();
    env.put(Context.REFERRAL, "ignore");
    env.put("test.getRootURLContext", "GetRootURLContext");

    server.setResponseSeq(new LdapMessage[] { new LdapMessage(
            LdapASN1Constant.OP_BIND_RESPONSE, new BindResponse(), null) });

    ResolveResult result = context.getRootURLContext(server.getURL(), env);

    assertEquals("", result.getRemainingName().toString());
    assertTrue(result.getResolvedObj() instanceof LdapContextImpl);

    LdapContext newContext = (LdapContext) result.getResolvedObj();
    Hashtable<Object, Object> newEnv = (Hashtable<Object, Object>) newContext
            .getEnvironment();

    assertEquals("ignore", newEnv.get(Context.REFERRAL));
    assertEquals("GetRootURLContext", newEnv.get("test.getRootURLContext"));
}
项目:cn1    文件:ldapURLContextTest.java   
public void testGetRootURLContext3() throws Exception {
    Hashtable<Object, Object> initialEnv = new Hashtable<Object, Object>();
    initialEnv.put(Context.REFERRAL, "throw");
    initialEnv.put("test.getRootURLContext", "test");

    MockLdapURLContext context = new MockLdapURLContext(initialEnv);

    server.setResponseSeq(new LdapMessage[] { new LdapMessage(
            LdapASN1Constant.OP_BIND_RESPONSE, new BindResponse(), null) });

    ResolveResult result = context.getRootURLContext(server.getURL(), null);

    assertEquals("", result.getRemainingName().toString());
    assertTrue(result.getResolvedObj() instanceof LdapContextImpl);

    LdapContext newContext = (LdapContext) result.getResolvedObj();
    Hashtable<Object, Object> newEnv = (Hashtable<Object, Object>) newContext
            .getEnvironment();

    assertEquals("throw", newEnv.get(Context.REFERRAL));
    assertEquals("test", newEnv.get("test.getRootURLContext"));
}
项目:cn1    文件:LdapContextServerMockedTest.java   
public void testConnectControls2() throws Exception {
    // set connect controls by property "java.naming.ldap.control.connect"
    env.put("java.naming.ldap.control.connect",
            new Control[] { new SortControl("", Control.NONCRITICAL) });

    server.setResponseSeq(new LdapMessage[] { new LdapMessage(
            LdapASN1Constant.OP_BIND_RESPONSE, new BindResponse(), null) });

    InitialDirContext initialDirContext = new InitialDirContext(env);

    server.setResponseSeq(new LdapMessage[] { new LdapMessage(
            LdapASN1Constant.OP_SEARCH_RESULT_DONE,
            new EncodableLdapResult(), null) });
    LdapContext context = (LdapContext) initialDirContext.lookup("");

    Control[] controls = context.getConnectControls();
    assertNotNull(controls);
    assertEquals(1, controls.length);
    Control c = controls[0];
    assertTrue(c instanceof SortControl);
    assertEquals(Control.NONCRITICAL, c.isCritical());
}