Example usage for javax.naming.directory BasicAttributes BasicAttributes

List of usage examples for javax.naming.directory BasicAttributes BasicAttributes

Introduction

In this page you can find the example usage for javax.naming.directory BasicAttributes BasicAttributes.

Prototype

public BasicAttributes(boolean ignoreCase) 

Source Link

Document

Constructs a new instance of Attributes.

Usage

From source file:org.apache.ftpserver.usermanager.LdapUserManager.java

/**
 * Save user.//  w  w  w  .j  ava2 s  .c  om
 */
public synchronized void save(User user) throws FtpException {
    try {
        String name = user.getName();
        String dn = getDN(name);
        BaseUser newUser = new BaseUser(user);

        // if password is not available, 
        // do not change the existing password
        User existUser = getUserByName(name);
        if ((existUser != null) && (newUser.getPassword() == null)) {
            newUser.setPassword(existUser.getPassword());
        }

        // set attributes
        Attributes attrs = new BasicAttributes(true);
        attrs.put(new BasicAttribute(CN, name));
        attrs.put(new BasicAttribute(CLASS_NAME, BaseUser.class.getName()));

        // bind object
        m_log.info("Rebinding user " + dn);
        m_adminContext.rebind(dn, newUser, attrs);
    } catch (NamingException ex) {
        m_log.error("LdapUserManager.save()", ex);
        throw new FtpException("LdapUserManager.save()", ex);
    }
}

From source file:org.springframework.ldap.core.DirContextAdapter.java

/**
 * Sets the update mode. The update mode should be <code>false</code> for a
 * new entry and <code>true</code> for an existing entry that is being
 * updated.//from ww w .  j  av a2 s  .  co m
 * 
 * @param mode Update mode.
 */
public void setUpdateMode(boolean mode) {
    this.updateMode = mode;
    if (updateMode) {
        updatedAttrs = new BasicAttributes(true);
    }
}

From source file:org.apache.hadoop.hdfsproxy.LdapIpDirFilter.java

/**
 * check if client's ip is listed in the Ldap Roles if yes, return true and
 * update ldapent. if not, return false/* ww w. j a  va2  s.  com*/
 * */
@SuppressWarnings("unchecked")
private boolean getLdapRoleEntryFromUserIp(String userIp, LdapRoleEntry ldapent) throws NamingException {
    String ipMember = hdfsIpSchemaStrPrefix + userIp;
    Attributes matchAttrs = new BasicAttributes(true);
    matchAttrs.put(new BasicAttribute(hdfsIpSchemaStr, ipMember));
    matchAttrs.put(new BasicAttribute(hdfsUidSchemaStr));
    matchAttrs.put(new BasicAttribute(hdfsPathSchemaStr));

    String[] attrIDs = { hdfsUidSchemaStr, hdfsPathSchemaStr };

    NamingEnumeration<SearchResult> results = lctx.search(baseName, matchAttrs, attrIDs);
    if (results.hasMore()) {
        String userId = null;
        ArrayList<Path> paths = new ArrayList<Path>();
        SearchResult sr = results.next();
        Attributes attrs = sr.getAttributes();
        for (NamingEnumeration ne = attrs.getAll(); ne.hasMore();) {
            Attribute attr = (Attribute) ne.next();
            if (hdfsUidSchemaStr.equalsIgnoreCase(attr.getID())) {
                userId = (String) attr.get();
            } else if (hdfsPathSchemaStr.equalsIgnoreCase(attr.getID())) {
                for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
                    String pathStr = (String) e.next();
                    paths.add(new Path(pathStr));
                }
            }
        }
        ldapent.init(userId, paths);
        if (LOG.isDebugEnabled())
            LOG.debug(ldapent);
        return true;
    }
    LOG.info("Ip address " + userIp + " is not authorized to access the proxy server");
    return false;
}

From source file:CreateJavaSchema.java

protected void updateAttributes(DirContext attrRoot, String[] attrIDs) throws NamingException {

    /* Get rid of old attr IDs */
    for (int i = 0; i < attrIDs.length; i++) {
        attrRoot.destroySubcontext(attrIDs[i]);
    }/*w  w  w.  j av  a2 s  .c  om*/

    // javaSerializedData
    Attributes attrs = new BasicAttributes(true); // ignore case
    attrs.put("NUMERICOID", "1.3.6.1.4.1.42.2.27.4.1.8");
    attrs.put("NAME", "javaSerializedData");
    attrs.put("DESC", "Serialized form of a Java object");
    if (netscape41bug) {
        // DS 4.1 doesn't like Octet String
        attrs.put("SYNTAX", "1.3.6.1.4.1.1466.115.121.1.5");
    } else {
        attrs.put("SYNTAX", "1.3.6.1.4.1.1466.115.121.1.40");
    }

    attrs.put("SINGLE-VALUE", "true");
    attrRoot.createSubcontext("javaSerializedData", attrs);
    System.out.println("Created javaSerializedData attribute");

    // javaCodebase
    attrs = new BasicAttributes(true);
    attrs.put("NUMERICOID", "1.3.6.1.4.1.42.2.27.4.1.7");
    attrs.put("NAME", "javaCodebase");
    attrs.put("DESC", "URL(s) specifying the location of class definition");
    attrs.put("EQUALITY", "caseExactIA5Match");
    attrs.put("SYNTAX", "1.3.6.1.4.1.1466.115.121.1.26");
    attrRoot.createSubcontext("javaCodebase", attrs);
    System.out.println("Created javaCodebase attribute");

    // javaClassName
    attrs = new BasicAttributes(true);
    attrs.put("NUMERICOID", "1.3.6.1.4.1.42.2.27.4.1.6");
    attrs.put("NAME", "javaClassName");
    attrs.put("DESC", "Fully qualified name of distinguished class or interface");
    attrs.put("EQUALITY", "caseExactMatch");
    attrs.put("SYNTAX", "1.3.6.1.4.1.1466.115.121.1.15");
    attrs.put("SINGLE-VALUE", "true");
    attrRoot.createSubcontext("javaClassName", attrs);
    System.out.println("Created javaClassName attribute");

    // javaClassNames
    attrs = new BasicAttributes(true);
    attrs.put("NUMERICOID", "1.3.6.1.4.1.42.2.27.4.1.13");
    attrs.put("NAME", "javaClassNames");
    attrs.put("DESC", "Fully qualified Java class or interface name");
    attrs.put("EQUALITY", "caseExactMatch");
    attrs.put("SYNTAX", "1.3.6.1.4.1.1466.115.121.1.15");
    attrRoot.createSubcontext("javaClassNames", attrs);
    System.out.println("Created javaClassNames attribute");

    // javaFactory
    attrs = new BasicAttributes(true);
    attrs.put("NUMERICOID", "1.3.6.1.4.1.42.2.27.4.1.10");
    attrs.put("NAME", "javaFactory");
    attrs.put("DESC", "Fully qualified Java class name of a JNDI object factory");
    attrs.put("EQUALITY", "caseExactMatch");
    attrs.put("SYNTAX", "1.3.6.1.4.1.1466.115.121.1.15");
    attrs.put("SINGLE-VALUE", "true");
    attrRoot.createSubcontext("javaFactory", attrs);
    System.out.println("Created javaFactory attribute");

    // javaReferenceAddress
    attrs = new BasicAttributes(true);
    attrs.put("NUMERICOID", "1.3.6.1.4.1.42.2.27.4.1.11");
    attrs.put("NAME", "javaReferenceAddress");
    attrs.put("DESC", "Addresses associated with a JNDI Reference");
    attrs.put("EQUALITY", "caseExactMatch");
    attrs.put("SYNTAX", "1.3.6.1.4.1.1466.115.121.1.15");
    attrRoot.createSubcontext("javaReferenceAddress", attrs);
    System.out.println("Created javaReferenceAddress attribute");

    // javaDoc
    attrs = new BasicAttributes(true);
    attrs.put("NUMERICOID", "1.3.6.1.4.1.42.2.27.4.1.12");
    attrs.put("NAME", "javaDoc");
    attrs.put("DESC", "The Java documentation for the class");
    attrs.put("EQUALITY", "caseExactIA5Match");
    attrs.put("SYNTAX", "1.3.6.1.4.1.1466.115.121.1.26");
    attrRoot.createSubcontext("javaDoc", attrs);
    System.out.println("Created javaDoc attribute");
}

From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java

/**
 * Create main context corresponding to tenant.
 *
 * @param rootDN            Root domain name.
 * @param orgName           Organization name
 * @param initialDirContext The directory connection.
 * @throws UserStoreException If an error occurred while creating context.
 *///from   w  ww. j a va 2  s. co  m
protected void createOrganizationalContext(String rootDN, String orgName, DirContext initialDirContext)
        throws UserStoreException {

    DirContext subContext = null;
    DirContext organizationalContext = null;
    try {

        //get the connection context for rootDN
        subContext = (DirContext) initialDirContext.lookup(rootDN);

        Attributes contextAttributes = new BasicAttributes(true);
        //create organizational object class attribute
        Attribute objectClass = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
        objectClass.add(tenantMgtConfig.getTenantStoreProperties()
                .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORGANIZATIONAL_OBJECT_CLASS));
        contextAttributes.put(objectClass);
        //create organizational name attribute
        String organizationalNameAttribute = tenantMgtConfig.getTenantStoreProperties()
                .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORGANIZATIONAL_ATTRIBUTE);
        Attribute organization = new BasicAttribute(organizationalNameAttribute);
        organization.add(orgName);
        contextAttributes.put(organization);
        //construct organization rdn.
        String rdnOfOrganizationalContext = organizationalNameAttribute + "=" + orgName;
        if (logger.isDebugEnabled()) {
            logger.debug("Adding sub context: " + rdnOfOrganizationalContext + " under " + rootDN + " ...");
        }
        //create organization sub context
        organizationalContext = subContext.createSubcontext(rdnOfOrganizationalContext, contextAttributes);
        if (logger.isDebugEnabled()) {
            logger.debug("Sub context: " + rdnOfOrganizationalContext + " was added under " + rootDN
                    + " successfully.");
        }

    } catch (NamingException e) {
        String errorMsg = "Error occurred while adding the organizational unit " + "sub context.";
        if (logger.isDebugEnabled()) {
            logger.debug(errorMsg, e);
        }
        throw new UserStoreException(errorMsg, e);
    } finally {
        closeContext(organizationalContext);
        closeContext(subContext);
    }
}

From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java

private void bindUserObject(DirContext context, User user) throws NamingException {
    Attributes attributes = new BasicAttributes(true);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("inetOrgPerson");
    objectClass.add("person");
    objectClass.add("organizationalperson");
    attributes.put(objectClass);/*  ww w.j av  a 2  s  .c o m*/
    attributes.put("cn", user.getUsername());
    attributes.put("sn", "foo");
    if (StringUtils.isNotEmpty(user.getEmail())) {
        attributes.put("mail", user.getEmail());
    }

    if (userConf.getBoolean(UserConfigurationKeys.LDAP_BIND_AUTHENTICATOR_ALLOW_EMPTY_PASSWORDS, false)
            && StringUtils.isNotEmpty(user.getPassword())) {
        attributes.put("userPassword", passwordEncoder.encodePassword(user.getPassword()));
    }
    attributes.put("givenName", "foo");
    context.createSubcontext("cn=" + user.getUsername() + "," + this.getBaseDn(), attributes);
}

From source file:de.fiz.ddb.aas.auxiliaryoperations.ThreadOrganisationCreate.java

private void createOrg() throws ExecutionException, IllegalArgumentException, AASUnauthorizedException {
    InitialLdapContext vCtx = null;

    Attributes vOrgAttributes = new BasicAttributes(true);

    BasicAttribute objectClass = new BasicAttribute("objectclass", "top");
    objectClass.add(Constants.ldap_ddbOrg_ObjectClass);
    objectClass.add("organization");

    vOrgAttributes.put(objectClass);/*from w w  w. j a v  a 2s .c o m*/

    // ---All this occurs only if that is not a copy in the export directory
    if (!this.isAddToLicensedOrgs()) {

        // -- When creating the status always set on Pending:
        if (!this.isIngestingOperation()) {
            this._orgObj.setStatus(ConstEnumOrgStatus.pending);
            long vTimeStamp = new Date().getTime();
            this._orgObj.setModified(vTimeStamp);
            this._orgObj.setCreated(vTimeStamp);
        }

        if (this._performer != null) {
            this._orgObj.setModifiedBy(this._performer.getUid());
            this._orgObj.setCreatedBy(this._performer.getUid());
        }

        // -- Is null, if it was isIngestingOperation or isAddToLicensedOrgs 
        //    and therefore does not need to be additionally checked
        if (_submit != null) {
            GeoAdresse vGeoAdresse;
            try {
                vGeoAdresse = _submit.get(50, TimeUnit.SECONDS);
                if (vGeoAdresse.getRequestStatus() == GeoRequestStatus.OK) {
                    this._orgObj.getAddress().setLatitude(vGeoAdresse.getLatitude());
                    this._orgObj.getAddress().setLongitude(vGeoAdresse.getLongitude());
                    this._orgObj.getAddress().setLocationDisplayName(vGeoAdresse.getLocationDisplayName());
                } else {
                    LOG.log(Level.WARNING, "GeoRequestStatus: {0}, (organization id: {1})",
                            new Object[] { vGeoAdresse.getRequestStatus(), this._orgObj.getOIDs() });
                }
            } catch (InterruptedException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._orgObj.getOIDs(), ex);
            } catch (TimeoutException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._orgObj.getOIDs(), ex);
            }
        }
    }

    // -- Conversion of parameters to LDAP attributes:
    this.convertOrganizationToLdapOrgAttrsForCreate(this._orgObj, vOrgAttributes, getPerformer());

    StringBuilder vEntryDN = (this.isAddToLicensedOrgs() ? this.getLicensedOrgsDN(this._orgObj.getOIDs())
            : this.getOrgDN(this._orgObj.getOIDs()));

    try {
        // put arbitrary (Org) Properties as JSON-String into LDAP.
        if (this._orgObj.getProperties() != null && !this._orgObj.getProperties().isEmpty()) {
            vOrgAttributes.put(new BasicAttribute(Constants.ldap_ddbOrg_Properties,
                    serializer.serialize(this._orgObj.getProperties())));
        }

        // finally bind the entry
        vCtx = LDAPConnector.getSingletonInstance().takeCtx();
        ((InitialDirContext) vCtx).bind(vEntryDN.toString(), vCtx, vOrgAttributes);

        // -- Add default privilege(s) so we can assign performer
        //    but only if that is not a copy in the export directory
        if (!this.isAddToLicensedOrgs()) {
            this._orgObj.getPrivilegesSet().add(PrivilegeEnum.ADMIN_ORG);

            // create org-privileges
            for (PrivilegeEnum p : this._orgObj.getPrivilegesSet()) {
                ThreadSinglePrivilegeCreate threadSinglePrivilegeCreate = new ThreadSinglePrivilegeCreate(p,
                        this._orgObj, this._performer);
                threadSinglePrivilegeCreate.call();
            }
            // -- Logging:
            LOG.log(Level.INFO, "One organization with DN: ''{0}'' was created.", new Object[] { vEntryDN });
        } else {
            // -- Logging:
            LOG.log(Level.INFO, "One organization with DN: ''{0}'' was copied to the export directory.",
                    new Object[] { vEntryDN });
        }
    } catch (AssertionError ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw new IllegalArgumentException(ex.getMessage(), ex.getCause());
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NamingException ex) {
        // LDAP: error code 68 - ENTRY_ALREADY_EXISTS: failed for Add
        // Request
        try {
            if (vCtx != null) {
                vCtx.close();
                vCtx = null;
            }
        } catch (NamingException ex1) {
            LOG.log(Level.SEVERE, null, ex1);
        }
        try {
            vCtx = LDAPConnector.getSingletonInstance().getDirContext();
        } catch (NamingException ex1) {
            LOG.log(Level.SEVERE, null, ex1);
        } catch (IllegalAccessException ex1) {
            LOG.log(Level.SEVERE, null, ex1);
        }
        throw new IllegalArgumentException(ex.getMessage());
    } finally {
        if (vCtx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(vCtx);
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, "Exception", ex);
            }
        }
    }

}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public void addServicePrinciple(String serverName, String serverDescription, Object credentials)
        throws DirectoryServerManagerException {

    if (!(credentials instanceof String)) {
        throw new DirectoryServerManagerException("Invalid credentials provided");
    }/*from   w  ww  .j  ava  2  s  . c  om*/

    DirContext dirContext;
    try {
        dirContext = this.connectionSource.getContext();
    } catch (UserStoreException e) {
        throw new DirectoryServerManagerException("An error occurred while retrieving LDAP connection context.",
                e);
    }

    String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    try {

        dirContext = (DirContext) dirContext.lookup(searchBase);

        BasicAttributes basicAttributes = new BasicAttributes(true);

        // Put only service name as uid. i.e. if server name is like ftp/wso2.example.com
        // then add only ftp as uid
        String serverUid = getServiceName(serverName);

        constructBasicAttributes(basicAttributes, serverUid, serverName, credentials, serverDescription,
                LDAPServerManagerConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE);

        dirContext.bind(LDAPServerManagerConstants.LDAP_UID + "=" + serverUid, null, basicAttributes);

    } catch (NamingException e) {
        String message = "Can not access the directory context or user " + "already exists in the system";
        log.error(message, e);
        throw new DirectoryServerManagerException(message, e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }
}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Reproduces the problem with//from w w w.  java 2 s. co m
 * <a href="http://issues.apache.org/jira/browse/DIREVE-239">DIREVE-239</a>.
 *
 * @throws Exception if anything goes wrong
 */
@Test
public void testAdminAccessBug() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous

    final Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    Attributes attributes = new BasicAttributes(true);
    Attribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("organizationalUnit");
    attributes.put(objectClass);
    attributes.put("ou", "blah");
    InitialDirContext ctx = new InitialDirContext(env);
    ctx.createSubcontext("ou=blah,ou=system", attributes);
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.OBJECT_SCOPE);
    controls.setReturningAttributes(new String[] { "+" });
    NamingEnumeration<SearchResult> list = ctx.search("ou=blah,ou=system", "(objectClass=*)", controls);
    SearchResult result = list.next();
    list.close();
    Attribute creatorsName = result.getAttributes().get("creatorsName");
    assertEquals("", creatorsName.get());
    ctx.destroySubcontext("ou=blah,ou=system");
}

From source file:org.exoplatform.services.organization.DummyLDAPServiceImpl.java

private void addNewSchema() throws NamingException {
    DirContext ctx = getLdapContext();
    try {//  www  .jav  a  2  s.  c  om
        Attributes atAttrs = new BasicAttributes(true);
        atAttrs.put("attributeTypes",
                "( 1.2.840.113556.1.4.8 NAME 'userAccountControl' DESC 'Flags that control the behavior of the user account' EQUALITY integerMatch SYNTAX '1.3.6.1.4.1.1466.115.121.1.27' SINGLE-VALUE )");
        ctx.modifyAttributes("cn=schema", DirContext.ADD_ATTRIBUTE, atAttrs);
        Attributes ocAttrs = new BasicAttributes(true);
        ocAttrs.put("objectClasses",
                "( 1.2.840.113556.1.5.9 NAME 'user' SUP inetOrgPerson STRUCTURAL MAY (userAccountControl) )");
        ctx.modifyAttributes("cn=schema", DirContext.ADD_ATTRIBUTE, ocAttrs);
    } finally {
        ctx.close();
    }
}