Example usage for javax.naming.directory DirContext bind

List of usage examples for javax.naming.directory DirContext bind

Introduction

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

Prototype

public void bind(String name, Object obj, Attributes attrs) throws NamingException;

Source Link

Document

Binds a name to an object, along with associated attributes.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Attributes attrs = new BasicAttributes(true);
    Attribute objclass = new BasicAttribute("objectclass");
    objclass.add("top");
    objclass.add("extensible");
    attrs.put(objclass);//from   www . ja  v a 2  s.  c  o  m

    Object obj = "yourObject";
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "yourURL");

    DirContext ctx = new InitialDirContext(env);

    ctx.bind("cn=Sample", obj, attrs);
}

From source file:SerObjWithCodebase.java

public static void main(String[] args) {

    if (args.length != 1) {
        System.err.println("usage: java SerObjWithCodebase <codebase URL>");
        System.exit(-1);/*from w ww. ja va 2s .  c om*/
    }

    String codebase = args[0];

    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {
        // Create the initial context
        DirContext ctx = new InitialDirContext(env);

        // Create object to be bound
        Flower f = new Flower("rose", "pink");

        // Perform bind and specify codebase
        ctx.bind("cn=Flower", f, new BasicAttributes("javaCodebase", codebase));

        // Check that it is bound
        Flower f2 = (Flower) ctx.lookup("cn=Flower");
        System.out.println(f2);

        // Close the context when we're done
        ctx.close();
    } catch (NamingException e) {
        System.out.println("Operation failed: " + e);
    }
}

From source file:com.ktds.ldap.populator.LdapTestUtils.java

private static void loadLdif(DirContext context, Name rootNode, Resource ldifFile) {
    try {// w w  w .  j ava  2s.c o m
        LdapName baseDn = (LdapName) context.getEnvironment()
                .get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY);

        LdifParser parser = new LdifParser(ldifFile);
        parser.open();
        while (parser.hasMoreRecords()) {
            LdapAttributes record = parser.getRecord();

            LdapName dn = record.getName();

            if (baseDn != null) {
                dn = LdapUtils.removeFirst(dn, baseDn);
            }

            if (!rootNode.isEmpty()) {
                dn = LdapUtils.prepend(dn, rootNode);
            }
            context.bind(dn, null, record);
        }
    } catch (Exception e) {
        throw new UncategorizedLdapException("Failed to populate LDIF", e);
    }
}

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "domain.create", required = { "domain", "userName", "password", "rootDn", "rootDnPassword" })
@RequiresRoles("SUPERUSER")
public HashMap<String, Object> createDomain(OperationContext opContext)
        throws NamingException, NoSuchAlgorithmException, UnsupportedEncodingException {

    String domain = (String) opContext.getParams().get("domain");
    String userName = (String) opContext.getParams().get("userName");
    String password = (String) opContext.getParams().get("password");
    String rootDn = (String) opContext.getParams().get("rootDn");
    String rootDnPassword = (String) opContext.getParams().get("rootDnPassword");

    DirContext dirContext = contextSource.getContext(rootDn, rootDnPassword);

    DirContextAdapter userRoot = (DirContextAdapter) dirContext
            .lookup("ds-cfg-backend-id=userRoot,cn=Backends,cn=config");

    DomainDn domainDn = nameHelper.newDomainDnFromDomain(domain);

    //Declaring backend
    userRoot.addAttributeValue("ds-cfg-base-dn", domainDn.toString());
    dirContext.modifyAttributes(userRoot.getNameInNamespace(), userRoot.getModificationItems());

    //Creating backend
    DirContextAdapter adapter = new DirContextAdapter();
    adapter.setAttributeValues("objectclass", new String[] { "top", "domain" });
    adapter.setAttributeValue("dc", domain.split("\\.")[0]);
    dirContext.bind(domainDn.toString(), adapter, null);

    //Creating group node
    DirContextAdapter groupNode = new DirContextAdapter();
    groupNode.setAttributeValue("objectclass", "organizationalUnit");
    dirContext.bind(domainDn.getGroupNodeDn(), groupNode);

    //creating user node
    DirContextAdapter userNode = new DirContextAdapter();
    userNode.setAttributeValue("objectclass", "organizationalUnit");
    dirContext.bind(domainDn.getUserNodeDn(), userNode);

    //creating user
    DirContextAdapter userAccount = new DirContextAdapter();
    userAccount.setAttributeValues("objectclass", ldapConfiguration.getUserObjectClassList().toArray());
    userAccount.setAttributeValue("sn", userName);
    userAccount.setAttributeValue("cn", userName);
    UserDn userDn = nameHelper.newUserDn(userName, domainDn);
    userAccount.setAttributeValue("userPassword", password);
    dirContext.bind(userDn, userAccount);

    //creating admin group
    DirContextAdapter adminGroup = new DirContextAdapter();
    adminGroup.setAttributeValues("objectclass", ldapConfiguration.getGroupObjectClassList().toArray());
    adminGroup.setAttributeValue("uniqueMember", userDn.toString());
    GroupDn groupDn = nameHelper.newGroupDn("administrator", domainDn);
    dirContext.bind(groupDn, adminGroup);

    HashMap<String, Object> response = new HashMap<String, Object>();
    response.put("success", true);

    return response;
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationCreate(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        String result = null;//from w  w  w.  j  av a  2 s  .  c o  m
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Create attribute: " + a.getID());
            NamingEnumeration values;
            try {
                values = a.getAll();
            } catch (NamingException e1) {
                storeLdapException(e1, prc);
                throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1);
            }
            while (values.hasMoreElements()) {
                Attributes partialAttrs = new BasicAttributes();
                Attribute singleValuedAttribute;
                String id = a.getID();
                Object value = values.nextElement();
                if (log.isDebugEnabled()) {
                    if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) {
                        log.debug("Create value: ***");
                    } else {
                        log.debug("Create value: " + value);
                    }
                }
                if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) {
                    singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value));
                } else {
                    singleValuedAttribute = new BasicAttribute(id, value);
                }
                partialAttrs.put(singleValuedAttribute);
                DirContext dirContext = null;
                try {
                    dirContext = getDirContext(paramValueMap);
                    dirContext.modifyAttributes(entryName, DirContext.ADD_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   20 LDAP_TYPE_OR_VALUE_EXISTS Indicates that the attribute value specified in a modify or add operation already exists as a value for that attribute.
                    // Sun:
                    //   [LDAP: error code 20 - Attribute Or Value Exists]
                    if (e.getMessage().startsWith("[LDAP: error code 20 - ")) {
                        if (log.isDebugEnabled())
                            log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                        result = DEFAULT_RESULT_CREATE_OK;
                    } else {
                        storeLdapException(e, prc);
                        throw new SenderException(
                                "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]",
                                e);
                    }
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        if (result != null) {
            return result;
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            if (unicodePwd) {
                Enumeration enumeration = attrs.getIDs();
                while (enumeration.hasMoreElements()) {
                    String id = (String) enumeration.nextElement();
                    if ("unicodePwd".equalsIgnoreCase(id)) {
                        Attribute attr = attrs.get(id);
                        for (int i = 0; i < attr.size(); i++) {
                            attr.set(i, encodeUnicodePwd(attr.get(i)));
                        }
                    }
                }
            }
            dirContext = getDirContext(paramValueMap);
            dirContext.bind(entryName, null, attrs);
            return DEFAULT_RESULT;
        } catch (NamingException e) {
            // if (log.isDebugEnabled()) log.debug("Exception in operation [" + getOperation()+ "] entryName ["+entryName+"]", e);
            if (log.isDebugEnabled())
                log.debug("Exception in operation [" + getOperation() + "] entryName [" + entryName + "]: "
                        + e.getMessage());
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   68 LDAP_ALREADY_EXISTS Indicates that the add operation attempted to add an entry that already exists, or that the modify operation attempted to rename an entry to the name of an entry that already exists.
            // Sun:
            //   [LDAP: error code 68 - Entry Already Exists]
            if (e.getMessage().startsWith("[LDAP: error code 68 - ")) {
                return DEFAULT_RESULT_CREATE_OK;
            } else {
                storeLdapException(e, prc);
                throw new SenderException(e);
            }
        } finally {
            closeDirContext(dirContext);
        }
    }

}

From source file:org.geoserver.security.ldap.LDAPTestUtils.java

private static void loadLdif(DirContext context, Resource ldifFile) throws IOException {
    try {//from  w w  w.  j ava  2 s  .  co m
        DistinguishedName baseDn = (DistinguishedName) context.getEnvironment()
                .get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY);

        LdifParser parser = new LdifParser(ldifFile);
        parser.open();
        while (parser.hasMoreRecords()) {
            LdapAttributes record = parser.getRecord();

            DistinguishedName dn = record.getDN();
            if (baseDn != null) {
                dn.removeFirst(baseDn);
            }
            context.bind(dn, null, record);
        }
    } catch (NamingException e) {
        throw new RuntimeException("Failed to populate LDIF", e);
    }
}

From source file:org.projectforge.business.ldap.LdapDao.java

/**
 * @param ctx/*w w  w  .j a v a  2s . c  o m*/
 * @param ouBase If organizational units are given by the given obj then this parameter will be ignored, otherwise
 *          this is the ou where the new object will be inserted.
 * @param obj
 * @param args
 * @throws NamingException
 */
public void create(final DirContext ctx, final String ouBase, final T obj, final Object... args)
        throws NamingException {
    final String dn = buildDn(ouBase, obj);
    log.info("Create " + getObjectClass() + ": " + dn + ": " + getLogInfo(obj));
    final Attributes attrs = new BasicAttributes();
    final List<ModificationItem> modificationItems = getModificationItems(new ArrayList<ModificationItem>(),
            obj);
    modificationItems.add(createModificationItem(DirContext.ADD_ATTRIBUTE, "objectClass", getObjectClass()));
    final String[] additionalObjectClasses = getAdditionalObjectClasses(obj);
    if (additionalObjectClasses != null) {
        for (final String objectClass : additionalObjectClasses) {
            modificationItems.add(createModificationItem(DirContext.ADD_ATTRIBUTE, "objectClass", objectClass));
        }
    }
    for (final ModificationItem modItem : modificationItems) {
        final Attribute attr = modItem.getAttribute();
        LdapUtils.putAttribute(attrs, attr.getID(), (String) attr.get());
    }
    LdapUtils.putAttribute(attrs, "cn", LdapUtils.escapeCommonName(obj.getCommonName()));
    onBeforeBind(dn, attrs, args);
    ctx.bind(dn, null, attrs);
}

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

public void bind(final Name dn, final Object obj, final Attributes attributes) {

    executeReadWrite(new ContextExecutor() {
        public Object executeWithContext(DirContext ctx) throws javax.naming.NamingException {
            ctx.bind(dn, obj, attributes);
            return null;
        }// w  w w  . jav a 2s . c  o  m
    });
}

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

public void bind(final String dn, final Object obj, final Attributes attributes) {

    executeReadWrite(new ContextExecutor() {
        public Object executeWithContext(DirContext ctx) throws javax.naming.NamingException {
            ctx.bind(dn, obj, attributes);
            return null;
        }/*from ww w .  j av  a2  s  .  co  m*/
    });
}

From source file:org.springframework.ldap.demo.dao.PersonDaoImpl.java

public void create(Person person) {
    DirContext ctx = createAuthenticatedContext();
    String dn = buildDn(person);/*from  w w  w  . j  ava2 s  . co  m*/
    try {
        Attributes attrs = getAttributesToBind(person);
        ctx.bind(dn, null, attrs);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }
}