ldapservice.java

来自「jetspeed源代码」· Java 代码 · 共 1,485 行 · 第 1/3 页

JAVA
1,485
字号
            {
                logger.debug("LDAP Service: Transfer Tree failed", e);
                return false;
            }
        }

        checkAndCloseContext(ctx);
        return true;
    }

    /**
     * Update Atribute Function
     *
     * Update an attribute for given <code>LDAPURL</code>.
     *
     * @param url object to update.
     * @param at atrribute to update.
     * @return boolean true if success else false.
     */
    public boolean updateAttribute(LDAPURL url, Attribute at)
    {
        try
        {
            ModificationItem mods[] = new ModificationItem[1];
            mods[0] = new ModificationItem(2, at);
            return modifyAttribute(url, mods);
        }
        catch(NamingException e)
        {
            logger.debug("LDAP Service: Failed to update '" + at.getID() + "' attribute for " + url.getUrl(), e);
        }
        return false;
    }

    /**
     * Update Atributes Function
     *
     * Update attributes for given <code>LDAPURL</code>.
     *
     * @param url object to update.
     * @param at atrributes to update.
     * @return boolean true if success else false.
     */
    public boolean updateEntry(LDAPURL url, Attributes at)
    {
        DirContext ctx = connect(url);
        if(ctx == null) return false;

        try
        {
            ctx.modifyAttributes(url.getDN(), 2, at);
			checkAndCloseContext(ctx);
        }
        catch(ReferralException e)
        {
            LDAPURL myurl = getReferralUrl(e);
            return updateEntry(myurl, at);
        }
        catch(NamingException e)
        {
            logger.error("LDAP Service: Failed to update entry " + url.getDN(), e);
            return false;
        }
        return true;
    }
 
    /**
     * Update Entry Function
     *
     * Update attributes for given <code>LDAPURL</code>.
     *
     * @param url object to update.
     * @param ats atrributes to update.
     * @param replace replace if exist.
     * @return boolean true if success else false.
     */
    public boolean updateEntry(LDAPURL url, Attributes ats, boolean replace)
    {
        return replace ? synchEntry(url, ats) : addEntry(url, ats);
    }

    /**
     * Search Function
     *
     * Search objects for given Base DN and filter.
     *
     * @param ctx directory context.
     * @param dn Base search DN.
     * @param filter Search filter.
     * @param attribs attributes to receive.
     * @param type search scope 1 Subscope, else 0.
     * @exception NamingException
     * @return NamingEnumeration Results.
     */
    public NamingEnumeration search(DirContext ctx, String dn, String filter, String attribs[], int type)
        throws NamingException
    {
		return search(ctx, dn, filter, attribs, type, true);
    }

    /**
     * Search Function
     *
     * Search objects for given Base DN and filter.
     *
     * @param ctx directory context.
     * @param dn Base search DN.
     * @param filter Search filter.
     * @param attribs attributes to receive.
     * @param type search scope 2 Subscope, else 1.
     * @param setLimits enable limits.
     * @exception NamingException
     * @return NamingEnumeration Results.
     */
    private NamingEnumeration search(DirContext ctx, String dn, String filter, String attribs[], int type, boolean setLimits)
        throws NamingException
    {
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(type);
        constraints.setReturningAttributes(attribs);
        if(setLimits)
        {
            constraints.setCountLimit(limit);
            constraints.setTimeLimit(timeout);
        }
        NamingEnumeration results = ctx.search(dn, filter, constraints);
        return results;
    }

    /**
     * Search Function
     *
     * Search objects for given BaseURL and filter.
     *
     * @param url Base URL .
     * @param filter Search filter.
     * @param attribs attributes to receive.
     * @param subTreeScope true subtree else false.
     * @return Vector Results.
     */
    public Vector search(LDAPURL url, String filter, String attribs[], boolean subTreeScope)
    {
    	/*
		System.out.println("===== LDAPService: search");
		System.out.println("===== LDAPService: " + url);
		System.out.println("===== LDAPService: " + filter);
		System.out.println("===== LDAPService: " + attribs);
		System.out.println("===== LDAPService: " + subTreeScope);
		*/
		
        Vector results = new Vector();
        String attrs[] = new String[attribs.length + 1];
        attrs[0] = "objectclass";
        System.arraycopy(attribs, 0, attrs, 1, attribs.length);
        int scope = subTreeScope ? 2 : 1;
        subSearch(url, filter, attrs, scope, results);

        return results;
    }

    /**
     * Search Function
     *
     * Search objects for given BaseURL and filter.
     *
     * @param url Base URL .
     * @param filter Search filter.
     * @param attribs attributes to receive.
     * @param scope true subtree else false.
     * @param rs Result
     * @return boolean true if success else false.
     */
    private boolean subSearch(LDAPURL url, String filter, String attribs[], int scope, Vector rs)
    {
        DirContext ctx = connect(url);
        if(ctx == null) return false;
        
        String entryDN = null;
        Attributes at = null;
        Attribute a = null;
        LDAPURL myurl = null;
        int subscope = 0;
        String baseDN = url.getDN();

        boolean moreReferrals = true;
        while(moreReferrals)
		{
		    try
            {
                Vector vl;
                for(NamingEnumeration results = search(ctx, baseDN, filter, attribs, scope); results.hasMore(); rs.addElement(vl))
                {
                    SearchResult si = (SearchResult)results.next();
                    vl = new Vector(attribs.length);
                    entryDN = getFixedDN(si.getName(), baseDN);
                    myurl = new LDAPURL(url.getHost(), url.getPort(), entryDN);
                    vl.addElement(myurl);
                    at = si.getAttributes();
                    for(int i = 1; i < attribs.length; i++)
                    {
                        a = at.get(attribs[i]);
                        if(a == null)
                        {
                            vl.addElement("N/A");
                        } else
                        {
                            Object v = a.get();
                            if(v instanceof byte[])
                                vl.addElement(v);
                            else
                                vl.addElement(a.get().toString());
                        }
                    }
                }
                moreReferrals = false;
            }

            catch(ReferralException e)
            {
                myurl = getReferralUrl(e);
                subscope = scope != 1 ? scope : 0;
                boolean error = subSearch(myurl, filter, attribs, subscope, rs);
                if(!error) return error;
                
                moreReferrals = e.skipReferral();
                try
                {
                   	// Close old context
                   	checkAndCloseContext(ctx);
                    ctx = (DirContext)e.getReferralContext();
                }
                catch(NamingException _ex) { }
            }
            catch(NamingException e)
            {
                logger.debug("LDAP Service: Search failed", e);
                return false;
            }
        }
        
       	checkAndCloseContext(ctx);
        return true;
    }

    /**
     * Get value Function
     *
     * Return value for attribute value pair.
     *
     * @param attrvalue input.
     * @return String Value.
     */
    public String removeAttrName(String attrvalue)
    {
        StringTokenizer token = new StringTokenizer(attrvalue,"=");
        if (token.countTokens()==2)
        {
        	token.nextToken();
        	return token.nextToken();
        }
        else
        {
            return attrvalue;
        }
    }
 
    /**
     * Return full DN Function
     *
     * Add Base DN to given DN.
     *
     * @param rdn full DN.
     * @param base Base DN.
     * @return String DN.
     */
    private String getFixedDN(String rdn, String base)
    {
        return getDN(fixName(rdn), base);
    }

    /**
     * Return Name Function
     *
     * Return name for given DN.
     *
     * @param dn DN.
     * @return String Name.
     */
    public String getName(String dn)
    {
        try
        {
            Name nm = parser.parse(dn);
            return nm.get(nm.size() - 1).toString();
        }
        catch(NamingException _ex)
        {
            return null;
        }
    }

    /**
     * Fix Name Function
     *
     * Fix chars .
     *
     * @param name Name to fix.
     * @return String Fixed name.
     */
    private String fixName(String name)
    {
        if(name.length() > 0 && name.charAt(0) == '"')
        {
            int size = name.length() - 1;
            StringBuffer buf = new StringBuffer();
            for(int i = 1; i < size; i++)
            {
                if(name.charAt(i) == '/')
                    buf.append("\\");
                buf.append(name.charAt(i));
            }

            return buf.toString();
        }
        else
        {
            return name;
        }
    }

    /**
     * Return full DN Function
     *
     * Add Base DN to given DN.
     *
     * @param rdn DN.
     * @param base Base DN.
     * @return String full DN.
     */
    private String getDN(String rdn, String base)
    {
        if(rdn.length() == 0)
            return base;
        if(base.length() == 0)
            return rdn;
        else
            return rdn + ", " + base;
    }

    /**
     * Return Name Function
     *
     * Add Base DN to given DN.
     *
     * @param dn full DN.
     * @return Name Name for given DN.
     */
    public Name parse(String dn)
    {
        try
        {
            return parser.parse(dn);
        }
        catch(NamingException _ex)
        {
            return null;
        }
    }

    /**
     * Get Referral URL Function
     *
     * Return <code>LDAPURL</code> extracted from exception.
     *
     * @param e Exception to extract.
     * @return LDAPURL referrral URL.
     */
    public LDAPURL getReferralUrl(ReferralException e)
    {
        String url = (String)e.getReferralInfo();
        try
        {
            return new LDAPURL(url);
        }
        catch(Exception ex)
        {
            logger.debug("Invalid url: " + ex.getMessage() + " " + url);
        }
        return null;
    }

    ///////////////////////////////////////////////////////////////////////////
    // Service Init
    ///////////////////////////////////////////////////////////////////////////

    /**
     * This is the early initialization method called by the
     * Turbine <code>Service</code> framework
     * @param conf The <code>ServletConfig</code>
     * @exception InitializationException if the service fails to initialize
     */
    public void init( ServletConfig conf ) throws InitializationException
    {
        connections = new Hashtable();
        connector = null;
        parser = null;
        env = new Properties();
        ResourceService serviceConf = ((TurbineServices)TurbineServices.getInstance())
                                                     .getResources(SERVICE_NAME);
        this.host = serviceConf.getString("host");
        this.port = serviceConf.getInt("port",DEFAULT_PORT);
        this.sslport = serviceConf.getInt("sslport",DEFAULT_SSLPORT);
        this.limit = serviceConf.getInt("limit",DEFAULT_LIMIT);
        this.timeout = serviceConf.getInt("timeout",DEFAULT_TIMEOUT);
        this.version = serviceConf.getInt("version",DEFAULT_VERSION);
        this.listFilter = repair(serviceConf.getString("listfilter","(objectclass=*)"));
        this.basedn = repair(serviceConf.getString("basedn"));
        this.managerdn = repair(serviceConf.getString("managerdn"));
        this.password = serviceConf.getString("password");
        this.attributesList = getList(serviceConf.getString("attributeslist")," ");
        this.showOpAttributes = serviceConf.getBoolean("showopattributes",false);
        this.anonymousBind = serviceConf.getBoolean("anonymousbind",false);
        this.securityAuthentication = serviceConf.getString("securityauthentication","simple");
        this.securityProtocol = serviceConf.getString("securityprotocol");
        this.socketFactory = serviceConf.getString("socketfactory");
        this.useCachedDirContexts = serviceConf.getBoolean("contextcache", false);

        this.jndiprovider = serviceConf.getString("jndiprovider",DEFAULT_CTX);
        this.saslclientpckgs = serviceConf.getString("saslclientpckgs");
        mainConnect(new LDAPURL(host,port,basedn));
        setInit(true);
    }

    /**
     * This is the late initialization method called by the
     * Turbine <code>Service</code> framework
     * @param conf The <code>ServletConfig</code>
     * @exception InitializationException if the service fails to initialize
     */
    public void init() throws InitializationException
    {
        while( !getInit() )
        {
            //Not yet...
            try
            {
                Thread.sleep( 500 );
            }
            catch (InterruptedException ie )
            {
                logger.error( ie );
            }
        }
    }

    /**
     * Repair Given Parameter Function
     *
     * Repair String read from config.
     *
     * @param value String to repair.
     * @return String Repaired String.
     */
    private String repair(String value)
    {
        value = value.replace('/', '=');
        value = value.replace('%', ',');
        return value;
    }

    /**
     * Tokenizer Wrapper Function
     *
     * Tokenize given string with given parameter.
     *
     * @param value String to repair.
     * @param separator separator
     * @return String Result.
     */
    private String[] getList(String value, String separator)
    {
        if(value == null) return null;

        StringTokenizer tokens = new StringTokenizer(value, separator);
        String at[] = new String[tokens.countTokens()];

        for(int i = 0; tokens.hasMoreTokens(); i++)
		{
            at[i] = tokens.nextToken();
        }

        return at;
    }

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?