Example usage for javax.naming.directory Attributes put

List of usage examples for javax.naming.directory Attributes put

Introduction

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

Prototype

Attribute put(Attribute attr);

Source Link

Document

Adds a new attribute to the attribute set.

Usage

From source file:org.wso2.carbon.connector.ldap.UpdateEntry.java

@Override
public void connect(MessageContext messageContext) throws ConnectException {
    String attributesString = (String) getParameter(messageContext, LDAPConstants.ATTRIBUTES);
    String dn = (String) getParameter(messageContext, LDAPConstants.DN);
    String mode = (String) getParameter(messageContext, LDAPConstants.MODE);

    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace ns = factory.createOMNamespace(LDAPConstants.CONNECTOR_NAMESPACE, LDAPConstants.NAMESPACE);
    OMElement result = factory.createOMElement(LDAPConstants.RESULT, ns);
    OMElement message = factory.createOMElement(LDAPConstants.MESSAGE, ns);

    try {//from  w  w w. j a  va 2 s .  co  m
        DirContext context = LDAPUtils.getDirectoryContext(messageContext);

        Attributes entry = new BasicAttributes();
        if (StringUtils.isNotEmpty(attributesString)) {
            JSONObject object = new JSONObject(attributesString);
            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                String val = object.getString(key);
                Attribute newAttr = new BasicAttribute(key);
                newAttr.add(val);
                entry.put(newAttr);
            }
        }

        try {
            if (mode.equals(LDAPConstants.REPLACE)) {
                context.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, entry);
            } else if (mode.equals(LDAPConstants.ADD)) {
                context.modifyAttributes(dn, DirContext.ADD_ATTRIBUTE, entry);
            } else if (mode.equals(LDAPConstants.REMOVE)) {
                context.modifyAttributes(dn, DirContext.REMOVE_ATTRIBUTE, entry);
            }
            message.setText(LDAPConstants.SUCCESS);
            result.addChild(message);
            LDAPUtils.preparePayload(messageContext, result);
        } catch (NamingException e) { // LDAP Errors are catched
            LDAPUtils.handleErrorResponse(messageContext, LDAPConstants.ErrorConstants.UPDATE_ENTRY_ERROR, e);
            throw new SynapseException(e);
        }
    } catch (NamingException e) { //Authentication failures are catched
        LDAPUtils.handleErrorResponse(messageContext, LDAPConstants.ErrorConstants.INVALID_LDAP_CREDENTIALS, e);
        throw new SynapseException(e);
    } catch (JSONException e) {
        handleException("Error while passing the JSON object", e, messageContext);
    }
}

From source file:org.easy.ldap.AdminServiceImpl.java

@Override
public void addTenant(String tenantId) {
    try {/*from  w w w .  j av a  2s. co m*/
        //Add org node.
        Attributes attributes = new BasicAttributes();

        attributes.put(NamingFactory.getOrgObjectClasses());
        attributes.put(new BasicAttribute(RdnType.O.toString(), tenantId));

        LdapName domainDn = namingFactory.getDomainDn();
        Rdn tenantRdn = namingFactory.createTenantRdn(tenantId);

        ldapDao.createSubContext(domainDn, tenantRdn, attributes);

        //add roles node under org
        attributes = new BasicAttributes();
        attributes.put(NamingFactory.getRolesObjectClasses());
        attributes.put(new BasicAttribute(RdnType.OU.toString(),
                environment.getProperty(PropertyNames.ROLES_RDN_VALUE)));

        LdapName tenantDn = namingFactory.createTenantDn(tenantId);
        Rdn rolesRdn = namingFactory.createRolesRdn();

        ldapDao.createSubContext(tenantDn, rolesRdn, attributes);

        //create users node
        attributes = new BasicAttributes();
        attributes.put(NamingFactory.getUsersObjectClasses());
        attributes.put(new BasicAttribute(RdnType.OU.toString(),
                environment.getProperty(PropertyNames.USERS_RDN_VALUE)));

        Rdn peopleRdn = namingFactory.createPeopleRdn();

        ldapDao.createSubContext(tenantDn, peopleRdn, attributes);

    } catch (RuntimeException e) {
        log.error(e);
        throw new java.lang.RuntimeException(e);
    }

}

From source file:hsa.awp.common.naming.DirectoryTest.java

/**
 * Properties that must be set.//from w  ww  .j a va2s.c om
 *
 * @throws Exception If something went wrong with Attributes
 */

@Test
public void testGetUserProperties() throws Exception {

    for (Attributes curAttrs : adapter.getUsers().values()) {
        Properties curProps = directory.getUserProperties((String) curAttrs.get("uid").get());
        // here we have to fix the semester field - ldap has a field like
        // 0079$8 but directory maps to 8
        // TODO refactor ldap abstraction to externalize field processing
        String curSemesterString = (String) curAttrs.get("term").get();
        curAttrs.put(new BasicAttribute("term", curSemesterString.split("\\$")[1]));
        assertTrue(isEqual(curAttrs, curProps));
    }
}

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

/**
 * Test case for <a href="http://issues.apache.org/jira/browse/DIREVE-284" where users in
 * mixed case partitions were not able to authenticate properly.  This test case creates
 * a new partition under dc=aPache,dc=org, it then creates the example user in the JIRA
 * issue and attempts to authenticate as that user.
 *
 * @throws Exception if the user cannot authenticate or test fails
 *///from   ww w . j av a 2s  . co m
@Test
public void testUserAuthOnMixedCaseSuffix() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

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

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()) + "/dc=aPache,dc=org");
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    InitialDirContext ctx = new InitialDirContext(env);
    Attributes attrs = ctx.getAttributes("");
    assertTrue(attrs.get("dc").get().equals("aPache"));

    Attributes user = new BasicAttributes("cn", "Kate Bush", true);
    Attribute oc = new BasicAttribute("objectClass");
    oc.add("top");
    oc.add("person");
    oc.add("organizationalPerson");
    oc.add("inetOrgPerson");
    user.put(oc);
    user.put("sn", "Bush");
    user.put("userPassword", "Aerial");
    ctx.createSubcontext("cn=Kate Bush", user);

    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_CREDENTIALS, "Aerial");
    env.put(Context.SECURITY_PRINCIPAL, "cn=Kate Bush,dc=aPache,dc=org");

    InitialDirContext userCtx = new InitialDirContext(env);
    assertNotNull(userCtx);

    ctx.destroySubcontext("cn=Kate Bush");
}

From source file:org.apache.archiva.redback.common.ldap.role.TestLdapRoleMapper.java

private void bindUserObject(DirContext context, String cn, String dn) throws Exception {
    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);
    attributes.put("cn", cn);
    attributes.put("sn", "foo");
    attributes.put("mail", cn + "@apache.org");
    attributes.put("userPassword", passwordEncoder.encodePassword("foo"));
    attributes.put("givenName", "foo");
    context.createSubcontext(dn, attributes);
}

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

@Test
public void testFailureWithUnsupportedControl() throws Exception {
    Control unsupported = new OpaqueControl("1.1.1.1");
    unsupported.setCritical(true);/* w ww. ja  v  a  2s . c om*/

    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

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

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()) + "/ou=system");
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    InitialLdapContext ctx = new InitialLdapContext(env, null);

    Attributes user = new BasicAttributes("cn", "Kate Bush", true);
    Attribute oc = new BasicAttribute("objectClass");
    oc.add("top");
    oc.add("person");
    oc.add("organizationalPerson");
    oc.add("inetOrgPerson");
    user.put(oc);
    user.put("sn", "Bush");
    user.put("userPassword", "Aerial");
    ctx.setRequestControls(JndiUtils.toJndiControls(getLdapServer().getDirectoryService().getLdapCodecService(),
            new Control[] { unsupported }));

    try {
        ctx.createSubcontext("cn=Kate Bush", user);
        fail();
    } catch (OperationNotSupportedException e) {
    }

    unsupported.setCritical(false);
    ctx.setRequestControls(JndiUtils.toJndiControls(getLdapServer().getDirectoryService().getLdapCodecService(),
            new Control[] { unsupported }));

    DirContext kate = ctx.createSubcontext("cn=Kate Bush", user);
    assertNotNull(kate);
    assertTrue(ArrayUtils.isEquals(Asn1StringUtils.getBytesUtf8("Aerial"),
            kate.getAttributes("").get("userPassword").get()));

    ctx.destroySubcontext("cn=Kate Bush");
}

From source file:org.wso2.carbon.connector.integration.test.ldap.LdapConnectorIntegrationTest.java

public void createSampleEntity() throws Exception {

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredentials);

    DirContext ctx = new InitialDirContext(env);
    Attributes entry = new BasicAttributes();
    Attribute obClassAttr = new BasicAttribute("objectClass");
    obClassAttr.add("inetOrgPerson");
    entry.put(obClassAttr);

    Attribute mailAttr = new BasicAttribute("mail");
    mailAttr.add(testUserId + "@wso2.com");
    entry.put(mailAttr);/*from ww w.  j  a  v a2 s  .  c om*/

    Attribute passAttr = new BasicAttribute("userPassword");
    passAttr.add("12345");
    entry.put(passAttr);

    Attribute snAttr = new BasicAttribute("sn");
    snAttr.add("dim");
    entry.put(snAttr);

    Attribute cnAttr = new BasicAttribute("cn");
    cnAttr.add("dim");
    entry.put(cnAttr);

    String dn = "uid=" + testUserId + "," + userBase;

    ctx.createSubcontext(dn, entry);
}

From source file:org.nuxeo.ecm.directory.ldap.MockLdapServer.java

public void createGroup(String cn, String ou, String[] memberDns) {
    Attributes group = new BasicAttributes("cn", cn);
    Attribute members = new BasicAttribute("member");
    Attribute orgUnit = new BasicAttribute("ou", ou);

    for (String memberDn : memberDns) {
        members.add(memberDn);/*from w  w  w . j a  v  a  2s .c  o  m*/
    }

    Attribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("groupOfNames");

    group.put(objectClass);
    group.put(members);
    group.put(orgUnit);

    try {
        serverContext.createSubcontext("cn=" + cn + ",ou=groups", group);
    } catch (NameAlreadyBoundException ignore) {
        // System.out.println(" group " + cn + " already exists.");
    } catch (NamingException ne) {
        log.error("Failed to create group", ne);
    }
}

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);
    attributes.put("cn", user.getUsername());
    attributes.put("sn", "foo");
    if (StringUtils.isNotEmpty(user.getEmail())) {
        attributes.put("mail", user.getEmail());
    }/* www  .j  av a  2  s.  co  m*/

    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);

    // ---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);
        }//from  w  w w . j av  a 2s. c o  m

        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);
            }
        }
    }

}