简体   繁体   中英

Update the information active directory data using the java JNDI ?

I want to use the java JNDI to update/insert the user information which available or not-available in the Active directory. I have created an application which allow Active Directory user to get their information and I am able to extract the data from the active directory but I don't have any idea how to save the data in active directory using jndi Java which user want to update.

ctx.modifyAttributes(unique_name,iteam); 

using this method you can update the record in the active directory. name is the denoting the combination of searchbase and search filter which make the data unique in ldap active directory.

ModificationItem[] iteam = new ModificationItem[number_of_attribute_you_want_to_update];

iteam is the array of changes which you are going to do.

Attribute name = new BasicAttribute("displayName",userDetail.getName());
// replacing the value
    item[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, name);

setting the value

done ----- working example given below package com.ma.util;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Properties;
import java.util.logging.Logger;
import javax.naming.directory.*;
 import javax.naming.AuthenticationException; 
 import javax.naming.AuthenticationNotSupportedException;
 import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapContext;
import javax.security.auth.login.AppConfigurationEntry;
import javax.xml.transform.ErrorListener;

import com.ma.model.AppUserToAD;
import com.ma.model.Non_GAppUserFromAD;
import com.ma.properties.Params;

public class ActiveDirectoryConnectionWpToAd {

// connect the application with the active directory

public DirContext superUserContext;
public LdapContext ctx;
public static DirContext UserContext;

public ActiveDirectoryConnectionWpToAd() {
    // initialization parameters
    UserContext = getConnect();
}

public DirContext getConnect() {

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

    env.put(Context.PROVIDER_URL, <ipaddress:port>);
    env.put(Context.SECURITY_PRINCIPAL, <ldap user>);
    env.put(Context.SECURITY_CREDENTIALS, <ldap password>);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");

    env.put("java.naming.ldap.attributes.binary", "objectSID objectGUID");
    try {
        superUserContext = new InitialDirContext(env);

        System.out.println("connected");
        System.out.println(superUserContext.getEnvironment().toString());

    } catch (AuthenticationNotSupportedException ex) {
        System.out.println("The authentication is not supported by the server");
    } catch (AuthenticationException ex) {
        System.out.println("incorrect password or username");
    } catch (NamingException ex) {
        System.out.println("error when trying to create the context" + ex);
    }
    return superUserContext;

}

   // this method setUserInfo
   public void setUserInfo(DirContext ctx, String searchBase,
        String searchFilter) throws NamingException {

    SearchResult sourceResult = null;
    // Create the search controls
    SearchControls searchCtls = new SearchControls();

    // Specify the attributes to return
    searchCtls.setReturningAttributes("cn,sn,objectGUID,telephoneNumber");
    System.out.println("Specify the attributes to return ");

    // Specify the search scope
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    System.out.println(" Specify the search scope ");
    NamingEnumeration<SearchResult> answer = ctx.search(searchBase,
            searchFilter, searchCtls);

    System.out.println(answer);

    sourceResult = (SearchResult) answer.next();
    Attributes attrs = sourceResult.getAttributes();
    System.out.println("name : " + attrs.get("cn").get());

    if (answer.hasMore()) {
        sourceResult = (SearchResult) answer.next();

        Attributes attrs1 = sourceResult.getAttributes();
        System.out.println("name : " + attrs1.get("cn").get());
        // System.out.println("name 2 : "+attrs2.get("cn").get());
        System.out.println("telephoneNumber : "
                + attrs1.get("telephoneNumber").get());
    }
    // updating the record
    Attribute attribute = new BasicAttribute("telephoneNumber",
            "8285427147");
    // array of modified iteams
    ModificationItem[] item = new ModificationItem[1];
    // replacing the value
    item[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute);
    // changing the value of the attribute
    ctx.modifyAttributes(
            "CN=<somevalue> ,OU= <somevalue> Contacts,DC=<somevalue>,DC=<some value>",
            item);

    System.out.println("telephoneNumber : "+    attrs.get("telephoneNumber").get());

}

// convert the attribute data into the string
    public String convertDataIntoString(Attributes attrs, String name) {
    String output = "";
    if (attrs.get(name) != null) {
        try {
            output = (String) attrs.get(name).get();
        } catch (Exception e) {
            System.out.println("Exception In : " + attrs.get("cn"));
            e.toString();
        }

    } else {
        output = "";
    }
    return output;

}

// convert the objectGUID into the byteString
public static String getObjectGUIDString(Attributes attrs)
        throws NamingException {

    byte[] GUID = (byte[]) attrs.get("objectGUID").get();
    // String strGUID = "";
    String byteGUID = "";

    // Convert the GUID into string using the byte format
    for (int c = 0; c < GUID.length; c++) {
        byteGUID = byteGUID + "\\\\" + AddLeadingZero((int) GUID[c] & 0xFF);
    }

    // specify the LDAP search filter
    // This is the binary format of the objectGUID
    // Note that I've escaped the '\' character
    /*
     * String searchFilter ="(objectGUID=\\67\\8a\\44\\7c\\3b\\92\\ee\\48\\b2\\1a\\34\\51\\f2\\f7\\58\\ca)";
     */

    return byteGUID;
}

static String AddLeadingZero(int k) {
    return (k < 0xF) ? "0" + Integer.toHexString(k) : Integer
            .toHexString(k);
}


// this method setUserInfo

    public void setUserInfo(String searchBase,String searchFilter, Non_GAppUserFromAD userDetail) throws NamingException {
    SearchResult sourceResult = null;
    NamingEnumeration<SearchResult> answer=null ;
    // Create the search controls
    SearchControls searchCtls = new SearchControls();
    if (userDetail == null) {
        return;
    } else {

        // Specify the attributes to return
        searchCtls.setReturningAttributes(Params.RETURNED_ATTRIBUTES);
        System.out.println("Specify the attributes to return ");

        // Specify the search scope
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        System.out.println(" Specify the search scope ");
    //  NamingEnumeration<SearchResult> answer = ctx.search(searchBase,searchFilter, searchCtls);

        System.out.println("Search Filter : "+ searchFilter);
         answer = UserContext.search(searchBase,searchFilter, searchCtls);

        System.out.println("-------------------------"+answer);

        sourceResult = (SearchResult) answer.next();
        Attributes attrs = sourceResult.getAttributes();
        System.out.println("name : " + attrs.get("cn").get());


    // updating the record

        userDetail.getName();
        userDetail.getSurName();
        userDetail.getUserId();

    System.out.println( userDetail.toString());

        //assign the value to the attribute  fields 

        Attribute name = new BasicAttribute("displayName",userDetail.getName());
        Attribute surName = new BasicAttribute("sn",userDetail.getSurName());





        // array of modified iteams

        ModificationItem[] item = new ModificationItem[10];
        // replacing the value

        item[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,name);
        item[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,surName);



        // changing the value of the attribute
        String cnValue = attrs.get("CN").toString();
    String cnValueRp = cnValue.replace(':', '=');

        try {

            UserContext.modifyAttributes(cnValueRp+","+searchBase, item);

        } catch (NamingException e) {
            e.printStackTrace();
        }



       }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM