Example usage for javax.naming.directory BasicAttribute BasicAttribute

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

Introduction

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

Prototype

public BasicAttribute(String id) 

Source Link

Document

Constructs a new instance of an unordered attribute with no value.

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 ww w .j  a v  a  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:com.surevine.ldap2alfresco.ProfileFieldTextConverter.java

/**
 * Encode some attributes as Attributes.
 * @param json The JSON object to convert
 * @param attributes Collection of attributes to insert into
 *//* w  ww.j  av a2s. c  om*/
public void toAttributes(final Attributes attributes, final JSONObject json) {

    BasicAttribute attr = new BasicAttribute(attributeLabel);

    try {
        if (allowMultiples) {
            JSONArray jsonValues = json.getJSONArray(jsonLabel);

            for (int x = 0; x < jsonValues.length(); x++) {
                String jsonValue = jsonValues.getString(x);

                if (jsonValue != null && jsonValue.length() > 0) {
                    attr.add(jsonValue);
                }
            }
        } else {
            String jsonValue = json.getString(jsonLabel);

            if (jsonValue != null && jsonValue.length() > 0) {
                attr.add(jsonValue);
            }
        }
    } catch (JSONException e) {
        logException(Level.ERROR, e);
        return;
    }

    attributes.put(attr);
}

From source file:org.apache.archiva.redback.rest.services.LdapGroupMappingServiceTest.java

@Override
public void startServer() throws Exception {
    super.startServer();

    groupSuffix = apacheDs.addSimplePartition("test", new String[] { "archiva", "apache", "org" }).getSuffix();

    log.info("groupSuffix: {}", groupSuffix);

    suffix = "ou=People,dc=archiva,dc=apache,dc=org";

    log.info("DN Suffix: {}", suffix);

    apacheDs.startServer();//from ww w .  j  a v  a2s.  co m

    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("organizationalUnit");

    Attributes attributes = new BasicAttributes(true);
    attributes.put(objectClass);
    attributes.put("organizationalUnitName", "foo");

    apacheDs.getAdminContext().createSubcontext(suffix, attributes);

    createGroups();
}

From source file:de.sub.goobi.helper.ldap.LdapUser.java

/**
 * configure LdapUser with Userdetails.//from www. j av a2s . c  o m
 *
 * @param inUser
 *            User object
 * @param inPassword
 *            String
 * @param inUidNumber
 *            String
 */
public void configure(User inUser, String inPassword, String inUidNumber)
        throws NamingException, NoSuchAlgorithmException {
    MD4 digester = new MD4();
    if (!ConfigCore.getBooleanParameter("ldap_readonly", false)) {

        this.type = inUser.getLogin();
        LdapGroup lp = inUser.getLdapGroup();
        if (lp.getObjectClasses() == null) {
            throw new NamingException("no objectclass defined");
        }

        /* ObjectClasses */
        Attribute oc = new BasicAttribute("objectclass");
        StringTokenizer tokenizer = new StringTokenizer(lp.getObjectClasses(), ",");
        while (tokenizer.hasMoreTokens()) {
            oc.add(tokenizer.nextToken());
        }
        this.myAttrs.put(oc);

        this.myAttrs.put("uid", ReplaceVariables(lp.getUid(), inUser, inUidNumber));
        this.myAttrs.put("cn", ReplaceVariables(lp.getUid(), inUser, inUidNumber));
        this.myAttrs.put("displayName", ReplaceVariables(lp.getDisplayName(), inUser, inUidNumber));
        this.myAttrs.put("description", ReplaceVariables(lp.getDescription(), inUser, inUidNumber));
        this.myAttrs.put("gecos", ReplaceVariables(lp.getGecos(), inUser, inUidNumber));
        this.myAttrs.put("loginShell", ReplaceVariables(lp.getLoginShell(), inUser, inUidNumber));
        this.myAttrs.put("sn", ReplaceVariables(lp.getSn(), inUser, inUidNumber));
        this.myAttrs.put("homeDirectory", ReplaceVariables(lp.getHomeDirectory(), inUser, inUidNumber));

        this.myAttrs.put("sambaAcctFlags", ReplaceVariables(lp.getSambaAcctFlags(), inUser, inUidNumber));
        this.myAttrs.put("sambaLogonScript", ReplaceVariables(lp.getSambaLogonScript(), inUser, inUidNumber));
        this.myAttrs.put("sambaPrimaryGroupSID",
                ReplaceVariables(lp.getSambaPrimaryGroupSID(), inUser, inUidNumber));
        this.myAttrs.put("sambaSID", ReplaceVariables(lp.getSambaSID(), inUser, inUidNumber));

        this.myAttrs.put("sambaPwdMustChange",
                ReplaceVariables(lp.getSambaPwdMustChange(), inUser, inUidNumber));
        this.myAttrs.put("sambaPasswordHistory",
                ReplaceVariables(lp.getSambaPasswordHistory(), inUser, inUidNumber));
        this.myAttrs.put("sambaLogonHours", ReplaceVariables(lp.getSambaLogonHours(), inUser, inUidNumber));
        this.myAttrs.put("sambaKickoffTime", ReplaceVariables(lp.getSambaKickoffTime(), inUser, inUidNumber));
        this.myAttrs.put("sambaPwdLastSet", String.valueOf(System.currentTimeMillis() / 1000l));

        this.myAttrs.put("uidNumber", inUidNumber);
        this.myAttrs.put("gidNumber", ReplaceVariables(lp.getGidNumber(), inUser, inUidNumber));

        /*
         * Samba passwords
         */
        /* LanMgr */
        try {
            this.myAttrs.put("sambaLMPassword", toHexString(lmHash(inPassword)));
        } catch (Exception e) {
            logger.error(e);
        }
        /* NTLM */
        try {
            byte hmm[] = digester.digest(inPassword.getBytes("UnicodeLittleUnmarked"));
            this.myAttrs.put("sambaNTPassword", toHexString(hmm));
        } catch (UnsupportedEncodingException e) {
            logger.error(e);
        }

        /*
         * Encryption of password und Base64-Enconding
         */

        MessageDigest md = MessageDigest.getInstance(ConfigCore.getParameter("ldap_encryption", "SHA"));
        md.update(inPassword.getBytes(StandardCharsets.UTF_8));
        String digestBase64 = new String(Base64.encodeBase64(md.digest()), StandardCharsets.UTF_8);
        this.myAttrs.put("userPassword",
                "{" + ConfigCore.getParameter("ldap_encryption", "SHA") + "}" + digestBase64);
    }
}

From source file:org.springframework.ldap.support.LdapUtilsTest.java

@Test
public void testIterateAttributeValues() {
    String expectedAttributeName = "someAttribute";

    BasicAttribute expectedAttribute = new BasicAttribute(expectedAttributeName);
    expectedAttribute.add("value1");
    expectedAttribute.add("value2");

    LdapUtils.iterateAttributeValues(expectedAttribute, handlerMock);

    verify(handlerMock).handleAttributeValue(expectedAttributeName, "value1", 0);
    verify(handlerMock).handleAttributeValue(expectedAttributeName, "value2", 1);
}

From source file:com.surevine.ldap2alfresco.ProfileFieldTelephoneConverter.java

/**
 * Encode some attributes as Attributes.
 * @param json The JSON object to convert
 * @param attributes Collection of attributes to insert into
 */// ww w . j a va 2 s  . c  o m
public void toAttributes(final Attributes attributes, final JSONObject json) {

    BasicAttribute attr = new BasicAttribute(attributeLabel);

    try {
        if (allowMultiples) {
            JSONArray jsonNumbers = json.getJSONArray(jsonLabel);

            for (int x = 0; x < jsonNumbers.length(); x++) {
                JSONObject jsonNumber = jsonNumbers.getJSONObject(x);
                String number = encodePhoneNumber(jsonNumber);

                if (number != null && number.length() > 0) {
                    attr.add(number);
                }
            }
        } else {
            JSONObject jsonNumber = json.getJSONObject(jsonLabel);
            String number = encodePhoneNumber(jsonNumber);

            if (number != null && number.length() > 0) {
                attr.add(number);
            }
        }
    } catch (JSONException e) {
        logException(Level.ERROR, e);
        return;
    }

    attributes.put(attr);
}

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  2 s .  co 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:com.swdouglass.joid.store.DirectoryStoreImpl.java

public DirectoryStoreImpl() {
    try {/*  ww  w. j  a  v a 2  s.com*/
        // Set up environment for creating the initial context
        initialCtx = DirectoryUtil.getInitialDirContext();

        this.setOuOpenID(OU.concat(DirectoryUtil.getProperty(OU_OPENID_PROP, OU_OPENID_PROP_DEFAULT)));
        this.setOuAssociation(
                OU.concat(DirectoryUtil.getProperty(OU_ASSOCIATION_PROP, OU_ASSOCIATION_PROP_DEFAULT)));
        this.setOuNonce(OU.concat(DirectoryUtil.getProperty(OU_NONCE_PROP, OU_NONCE_PROP_DEFAULT)));

        //try to create parent contexes
        Attributes attrs = new BasicAttributes(true); // case-ignore
        Attribute objclass = new BasicAttribute("objectclass");
        objclass.add("top");
        objclass.add("organizationalUnit");
        attrs.put(objclass);
        DirContext baseCtx = initialCtx.createSubcontext(ouOpenID, attrs);
        baseCtx.createSubcontext(ouAssociation, attrs);
        baseCtx.createSubcontext(ouNonce, attrs);

    } catch (NameAlreadyBoundException ex) {
        //ignore
    } catch (Exception ex) {
        log.warn(ex);
        ex.printStackTrace();
    }
}

From source file:edu.kit.scc.ldap.LdapPosixUserDao.java

/**
 * Inserts a new POSIX user into the LDAP directory.
 * /*from w w w.  ja va2 s.  co  m*/
 * @param posixUser the {@link PosixUser} to insert
 * @return the {@link PosixUser} inserted
 */
public PosixUser insertUser(PosixUser posixUser) {
    if (posixUser.commonName == null || posixUser.gidNumber == null || posixUser.homeDirectory == null
            || posixUser.surName == null || posixUser.uid == null || posixUser.uidNumber == null) {
        log.warn("PosixUser has missing mandatory attributes");
        return null;
    }

    BasicAttribute personBasicAttribute = new BasicAttribute("objectclass");
    personBasicAttribute.add("extensibleObject");
    personBasicAttribute.add("inetOrgPerson");
    personBasicAttribute.add("organizationalPerson");
    personBasicAttribute.add("person");
    personBasicAttribute.add("posixAccount");

    Attributes personAttributes = new BasicAttributes();
    personAttributes.put(personBasicAttribute);
    personAttributes.put("cn", posixUser.getCommonName());
    personAttributes.put("sn", posixUser.getSurName());
    personAttributes.put("uid", posixUser.getUid());
    personAttributes.put("uidNumber", String.valueOf(posixUser.getUidNumber()));
    personAttributes.put("gidNumber", String.valueOf(posixUser.getGidNumber()));
    personAttributes.put("homeDirectory", posixUser.getHomeDirectory());

    if (posixUser.getUniqueIdentifier() != null) {
        personAttributes.put("uniqueIdentifier", posixUser.getUniqueIdentifier());
    }
    if (posixUser.getDescription() != null) {
        personAttributes.put("description", posixUser.getDescription());
    }
    if (posixUser.getGecos() != null) {
        personAttributes.put("gecos", posixUser.getGecos());
    }
    if (posixUser.getLoginShell() != null) {
        personAttributes.put("loginShell", posixUser.getLoginShell());
    }
    if (posixUser.getUserPassword() != null) {
        personAttributes.put("userPassword", posixUser.getUserPassword());
    }
    if (posixUser.getGivenName() != null) {
        personAttributes.put("givenName", posixUser.getGivenName());
    }
    if (posixUser.getMail() != null) {
        personAttributes.put("mail", posixUser.getMail());
    }

    LdapName newUserDn = LdapUtils.emptyLdapName();
    try {
        newUserDn = new LdapName(userBase);
        newUserDn.add("uid=" + posixUser.getUid());
        log.debug("Insert {}", newUserDn.toString());
        ldapTemplate.bind(newUserDn, null, personAttributes);

        return posixUser;
    } catch (InvalidNameException ex) {
        log.error("ERROR {}", ex.toString());
        // ex.printStackTrace();
    } catch (NameAlreadyBoundException ex) {
        log.error("ERROR {}", ex.toString());
    }
    return null;
}

From source file:py.una.pol.karaku.util.LDAPUtil.java

/**
 * Recupera los usuarios de LDAP//  w  ww .  j ava 2  s .  c  om
 * 
 * @return Una lista con los usuarios de LDAP
 */
public List<User> getUsers() {

    List<User> users = new ArrayList<User>();

    try {
        DirContext ctx = createInitialDirContext();

        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute("uid"));

        NamingEnumeration<SearchResult> answer = ctx.search("ou=users", matchAttrs);

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            String uid = sr.getName().substring(4);
            // No se retornan los usuarios especiales
            if (!uid.startsWith(LDAP_SPECIAL_USER_PREFIX) && !ListHelper.contains(EXCLUDED_USERS, uid)) {
                User user = new User();
                user.setUid(uid);
                Attributes atributos = sr.getAttributes();
                String cn = atributos.get("cn").toString().substring(4);
                user.setCn(cn);
                users.add(user);
            }
        }

    } catch (NamingException e) {
        throw new KarakuRuntimeException(e.getMessage(), e);
    }

    return users;

}