Example usage for javax.naming.directory Attribute size

List of usage examples for javax.naming.directory Attribute size

Introduction

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

Prototype

int size();

Source Link

Document

Retrieves the number of values in this attribute.

Usage

From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java

private void getGroups(UserGroupSink sink) throws Throwable {
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
    long highestdeltaSyncGroupTime = deltaSyncGroupTime;
    try {/*from   w  ww  .jav  a2 s. c  o m*/
        createLdapContext();
        int total;
        // Activate paged results
        if (pagedResultsEnabled) {
            ldapContext.setRequestControls(
                    new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) });
        }
        extendedGroupSearchFilter = "(objectclass=" + groupObjectClass + ")";
        if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) {
            String customFilter = groupSearchFilter.trim();
            if (!customFilter.startsWith("(")) {
                customFilter = "(" + customFilter + ")";
            }
            extendedGroupSearchFilter = extendedGroupSearchFilter + customFilter;
        }

        extendedAllGroupsSearchFilter = "(&" + extendedGroupSearchFilter + "(|(uSNChanged>="
                + deltaSyncGroupTime + ")(modifyTimestamp>=" + deltaSyncGroupTimeStamp + "Z)))";

        LOG.info("extendedAllGroupsSearchFilter = " + extendedAllGroupsSearchFilter);
        for (int ou = 0; ou < groupSearchBase.length; ou++) {
            byte[] cookie = null;
            int counter = 0;
            try {
                int paged = 0;
                do {
                    groupSearchResultEnum = ldapContext.search(groupSearchBase[ou],
                            extendedAllGroupsSearchFilter, groupSearchControls);
                    while (groupSearchResultEnum.hasMore()) {
                        final SearchResult groupEntry = groupSearchResultEnum.next();
                        if (groupEntry == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("groupEntry null, skipping sync for the entry");
                            }
                            continue;
                        }
                        counter++;
                        Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute);
                        if (groupNameAttr == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info(groupNameAttribute + " empty for entry "
                                        + groupEntry.getNameInNamespace() + ", skipping sync");
                            }
                            continue;
                        }
                        String gName = (String) groupNameAttr.get();
                        String transformGroupName = groupNameTransform(gName);
                        // If group based search is enabled, then
                        // update the group name to ranger admin
                        // check for group members and populate userInfo object with user's full name and group mapping
                        if (groupSearchFirstEnabled) {
                            LOG.debug("Update Ranger admin with " + transformGroupName);
                            sink.addOrUpdateGroup(transformGroupName);
                        }
                        Attribute timeStampAttr = groupEntry.getAttributes().get("uSNChanged");
                        if (timeStampAttr != null) {
                            String uSNChangedVal = (String) timeStampAttr.get();
                            long currentDeltaSyncTime = Long.parseLong(uSNChangedVal);
                            if (currentDeltaSyncTime > highestdeltaSyncGroupTime) {
                                highestdeltaSyncGroupTime = currentDeltaSyncTime;
                            }
                        } else {
                            timeStampAttr = groupEntry.getAttributes().get("modifytimestamp");
                            if (timeStampAttr != null) {
                                String timeStampVal = (String) timeStampAttr.get();
                                Date parseDate = dateFormat.parse(timeStampVal);
                                long currentDeltaSyncTime = parseDate.getTime();
                                LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = "
                                        + currentDeltaSyncTime);
                                if (currentDeltaSyncTime > highestdeltaSyncGroupTime) {
                                    highestdeltaSyncGroupTime = currentDeltaSyncTime;
                                    deltaSyncGroupTimeStamp = timeStampVal;
                                }
                            }
                        }
                        Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName);
                        int userCount = 0;
                        if (groupMemberAttr == null || groupMemberAttr.size() <= 0) {
                            LOG.info("No members available for " + gName);
                            continue;
                        }

                        NamingEnumeration<?> userEnum = groupMemberAttr.getAll();
                        while (userEnum.hasMore()) {
                            String originalUserFullName = (String) userEnum.next();
                            if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) {
                                continue;
                            }
                            userCount++;
                            String userName = getShortUserName(originalUserFullName);
                            originalUserFullName = originalUserFullName.toLowerCase();
                            if (groupSearchFirstEnabled && !userSearchEnabled) {
                                String transformUserName = userNameTransform(userName);
                                try {
                                    sink.addOrUpdateUser(transformUserName);
                                } catch (Throwable t) {
                                    LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage()
                                            + ", for user: " + transformUserName);
                                }
                                userNameMap.put(originalUserFullName, transformUserName);
                            }
                            //System.out.println("Adding " + userNameMap.get(originalUserFullName) + " and fullname = " + originalUserFullName + " to " + gName);
                            if (userNameMap.get(originalUserFullName) != null) {
                                groupUserTable.put(gName, originalUserFullName,
                                        userNameMap.get(originalUserFullName));
                            } else {
                                groupUserTable.put(gName, originalUserFullName, originalUserFullName);
                            }
                            groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName);
                        }
                        LOG.info("No. of members in the group " + gName + " = " + userCount);
                    }
                    // Examine the paged results control response
                    Control[] controls = ldapContext.getResponseControls();
                    if (controls != null) {
                        for (int i = 0; i < controls.length; i++) {
                            if (controls[i] instanceof PagedResultsResponseControl) {
                                PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                                total = prrc.getResultSize();
                                if (total != 0) {
                                    LOG.debug("END-OF-PAGE total : " + total);
                                } else {
                                    LOG.debug("END-OF-PAGE total : unknown");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOG.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    if (pagedResultsEnabled) {
                        LOG.debug(String.format("Fetched paged results round: %s", ++paged));
                        ldapContext.setRequestControls(new Control[] {
                                new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) });
                    }
                } while (cookie != null);
                LOG.info("LdapDeltaUserGroupBuilder.getGroups() completed with group count: " + counter);
            } catch (Exception t) {
                LOG.error("LdapDeltaUserGroupBuilder.getGroups() failed with exception: " + t);
                LOG.info("LdapDeltaUserGroupBuilder.getGroups() group count: " + counter);
            }
        }

    } finally {
        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
        closeLdapContext();
    }

    if (groupHierarchyLevels > 0) {
        LOG.debug("deltaSyncGroupTime = " + deltaSyncGroupTime);
        if (deltaSyncGroupTime > 0) {
            LOG.info(
                    "LdapDeltaUserGroupBuilder.getGroups(): Going through group hierarchy for nested group evaluation for deltasync");
            goUpGroupHierarchyLdap(groupNameMap.keySet(), groupHierarchyLevels - 1);
        }
    }

    if (deltaSyncGroupTime < highestdeltaSyncGroupTime) {
        // Incrementing highestdeltaSyncGroupTime (for AD) in order to avoid search record repetition for next sync cycle.
        deltaSyncGroupTime = highestdeltaSyncGroupTime + 1;
        // Incrementing the highest timestamp value (for OpenLdap) with 1min in order to avoid search record repetition for next sync cycle.
        deltaSyncGroupTimeStamp = dateFormat.format(new Date(highestdeltaSyncGroupTime + 60000l));
    }
}

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

private void writeSearchResult(final SearchResult sr, final XMLBuffer xmlb) throws NamingException {
    final Attributes attrs = sr.getAttributes();
    final int size = attrs.size();
    final ArrayList<Attribute> sortedAttrs = new ArrayList<>(size);

    xmlb.openTag("searchresult"); // $NON-NLS-1$
    xmlb.tag("dn", sr.getName()); // $NON-NLS-1$
    xmlb.tag("returnedattr", Integer.toString(size)); // $NON-NLS-1$
    xmlb.openTag("attributes"); // $NON-NLS-1$

    try {// w ww .  j a  v  a  2  s  . com
        for (NamingEnumeration<? extends Attribute> en = attrs.getAll(); en.hasMore();) {
            final Attribute attr = en.next();
            sortedAttrs.add(attr);
        }
        sortAttributes(sortedAttrs);
        for (final Attribute attr : sortedAttrs) {
            StringBuilder sb = new StringBuilder();
            if (attr.size() == 1) {
                sb.append(getWriteValue(attr.get()));
            } else {
                final ArrayList<String> sortedVals = new ArrayList<>(attr.size());
                boolean first = true;

                for (NamingEnumeration<?> ven = attr.getAll(); ven.hasMore();) {
                    final Object value = getWriteValue(ven.next());
                    sortedVals.add(value.toString());
                }

                Collections.sort(sortedVals);

                for (final String value : sortedVals) {
                    if (first) {
                        first = false;
                    } else {
                        sb.append(", "); // $NON-NLS-1$
                    }
                    sb.append(value);
                }
            }
            xmlb.tag(attr.getID(), sb);
        }
    } finally {
        xmlb.closeTag("attributes"); // $NON-NLS-1$
        xmlb.closeTag("searchresult"); // $NON-NLS-1$
    }
}

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

/**
 * returns true if the attribute is empty. It is empty if a == null, size ==
 * 0 or get() == null or an exception if thrown when accessing the get
 * method/*  ww w  .  j  a  v a  2  s.co m*/
 */
private boolean isEmptyAttribute(Attribute a) {
    try {
        return (a == null || a.size() == 0 || a.get() == null);
    } catch (NamingException e) {
        return true;
    }
}

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

public Object getObjectAttribute(String name) {
    Attribute oneAttr = originalAttrs.get(name);
    if (oneAttr == null || oneAttr.size() == 0) { // LDAP-215
        return null;
    }//from   w  ww.  j a v a 2s. c  o  m
    try {
        return oneAttr.get();
    } catch (NamingException e) {
        throw LdapUtils.convertLdapException(e);
    }
}

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

/**
 * @see java.lang.Object#toString()//from  w ww  .j  a v a  2  s .  c  om
 */
public String toString() {
    StringBuffer buf = new StringBuffer();
    buf.append(getClass().getName());
    buf.append(":");
    if (dn != null) {
        buf.append(" dn=" + dn);
    }
    buf.append(" {");

    try {
        for (NamingEnumeration i = originalAttrs.getAll(); i.hasMore();) {
            Attribute attribute = (Attribute) i.next();
            if (attribute.size() == 1) {
                buf.append(attribute.getID());
                buf.append('=');
                buf.append(attribute.get());
            } else {
                for (int j = 0; j < attribute.size(); j++) {
                    if (j > 0) {
                        buf.append(", ");
                    }
                    buf.append(attribute.getID());
                    buf.append('[');
                    buf.append(j);
                    buf.append("]=");
                    buf.append(attribute.get(j));
                }
            }

            if (i.hasMore()) {
                buf.append(", ");
            }
        }
    } catch (NamingException e) {
        log.warn("Error in toString()");
    }
    buf.append('}');

    return buf.toString();
}

From source file:no.feide.moria.directory.backend.JNDIBackend.java

/**
 * Retrieves a list of attributes from an element.
 * @param ldap/*from   w w w.ja va2 s  .c o  m*/
 *            A prepared LDAP context. Cannot be <code>null</code>.
 * @param rdn
 *            The relative DN (to the DN in the LDAP context
 *            <code>ldap</code>). Cannot be <code>null</code>.
 * @param attributes
 *            The requested attribute's names. Also indirectly referenced
 *            attributes on the form
 *            <code>someReferenceAttribute:someIndirectAttribute</code>,
 *            where the DN in the reference attribute
 *            <code>someReferenceAttribute</code> is followed to look up
 *            <code>someIndirectAttribute</code> from another element.
 * @return The requested attributes (<code>String</code> names and
 *         <code>String[]</code> values), if they did exist in the
 *         external backend. Otherwise returns those attributes that could
 *         actually be read, this may be an empty <code>HashMap</code>.
 *         Returns an empty <code>HashMap</code> if
 *         <code>attributes</code> is <code>null</code> or an empty
 *         array. Note that attribute values are mapped to
 *         <code>String</code> using ISO-8859-1.
 * @throws BackendException
 *             If unable to read the attributes from the backend.
 * @throws NullPointerException
 *             If <code>ldap</code> or <code>rdn</code> is
 *             <code>null</code>.
 * @see javax.naming.directory.InitialDirContext#getAttributes(java.lang.String,
 *      java.lang.String[])
 */
private HashMap<String, String[]> getAttributes(final InitialLdapContext ldap, final String rdn,
        final String[] attributes) throws BackendException {

    // Sanity checks.
    if (ldap == null)
        throw new NullPointerException("LDAP context cannot be NULL");
    if (rdn == null)
        throw new NullPointerException("RDN cannot be NULL");
    if ((attributes == null) || (attributes.length == 0))
        return new HashMap<String, String[]>();

    // Used to remember attributes to be read through references later on.
    Hashtable<String, Vector> attributeReferences = new Hashtable<String, Vector>();

    // Strip down request, resolving references and removing duplicates.
    Vector<String> strippedAttributeRequest = new Vector<String>();
    for (int i = 0; i < attributes.length; i++) {
        int indexOfSplitCharacter = attributes[i]
                .indexOf(DirectoryManagerBackend.ATTRIBUTE_REFERENCE_SEPARATOR);
        if (indexOfSplitCharacter == -1) {

            // A regular attribute request.
            if (!strippedAttributeRequest.contains(attributes[i]))
                strippedAttributeRequest.add(attributes[i]);

        } else {

            // A referenced attribute request.
            final String referencingAttribute = attributes[i].substring(0, indexOfSplitCharacter);
            if (!strippedAttributeRequest.contains(referencingAttribute))
                strippedAttributeRequest.add(referencingAttribute);

            // Add to list of attributes to be read through each reference.
            if (!attributeReferences.containsKey(referencingAttribute)) {

                // Add new reference.
                Vector<String> referencedAttribute = new Vector<String>();
                referencedAttribute.add(attributes[i].substring(indexOfSplitCharacter + 1));
                attributeReferences.put(referencingAttribute, referencedAttribute);

            } else {

                // Update existing reference.
                Vector<String> referencedAttribute = attributeReferences.get(referencingAttribute);
                if (!referencedAttribute.contains(attributes[i].substring(indexOfSplitCharacter + 1)))
                    referencedAttribute.add(attributes[i].substring(indexOfSplitCharacter + 1));

            }

        }

    }

    // The context provider URL and DN, for later logging.
    String url = "unknown backend";
    String dn = "unknown dn";

    // Get the attributes from an already initialized LDAP connection.
    Attributes rawAttributes = null;
    try {

        // Remember the URL and bind DN, for later logging.
        final Hashtable environment = ldap.getEnvironment();
        url = (String) environment.get(Context.PROVIDER_URL);
        dn = (String) environment.get(Context.SECURITY_PRINCIPAL);

        // Get the attributes.
        rawAttributes = ldap.getAttributes(rdn, strippedAttributeRequest.toArray(new String[] {}));

    } catch (NameNotFoundException e) {

        // Successful authentication but missing user element; no attributes
        // returned and the event is logged.
        log.logWarn("No LDAP element found (DN was '" + dn + "')", mySessionTicket);
        rawAttributes = new BasicAttributes();

    } catch (NamingException e) {
        String a = new String();
        for (int i = 0; i < attributes.length; i++)
            a = a + attributes[i] + ", ";
        throw new BackendException("Unable to read attribute(s) '" + a.substring(0, a.length() - 2) + "' from '"
                + rdn + "' on '" + url + "'", e);
    }

    // Translate retrieved attributes from Attributes to HashMap.
    HashMap<String, String[]> convertedAttributes = new HashMap<String, String[]>();
    for (int i = 0; i < attributes.length; i++) {

        // Did we get any attribute back at all?
        final String requestedAttribute = attributes[i];
        Attribute rawAttribute = rawAttributes.get(requestedAttribute);
        if (rawAttribute == null) {

            // Attribute was not returned.
            log.logDebug("Requested attribute '" + requestedAttribute + "' not found on '" + url + "'",
                    mySessionTicket);

        } else {

            // Map the attribute values to String[].
            ArrayList<String> convertedAttributeValues = new ArrayList<String>(rawAttribute.size());
            for (int j = 0; j < rawAttribute.size(); j++) {
                try {

                    // We either have a String or a byte[].
                    String convertedAttributeValue = null;
                    try {

                        // Encode String.
                        convertedAttributeValue = new String(((String) rawAttribute.get(j)).getBytes(),
                                DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET);
                    } catch (ClassCastException e) {

                        // Encode byte[] to String.
                        convertedAttributeValue = new String(Base64.encodeBase64((byte[]) rawAttribute.get(j)),
                                DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET);

                    }
                    convertedAttributeValues.add(convertedAttributeValue);

                } catch (NamingException e) {
                    throw new BackendException("Unable to read attribute value of '" + rawAttribute.getID()
                            + "' from '" + url + "'", e);
                } catch (UnsupportedEncodingException e) {
                    throw new BackendException(
                            "Unable to use " + DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET + " encoding",
                            e);
                }
            }
            convertedAttributes.put(requestedAttribute, convertedAttributeValues.toArray(new String[] {}));

        }

    }

    // Follow references to look up any indirectly referenced attributes.
    Enumeration<String> keys = attributeReferences.keys();
    while (keys.hasMoreElements()) {

        // Do we have a reference? 
        final String referencingAttribute = keys.nextElement();
        final String[] referencingValues = convertedAttributes.get(referencingAttribute);
        if (referencingValues == null) {

            // No reference was found in this attribute.
            log.logDebug("Found no DN references in attribute '" + referencingAttribute + "'", mySessionTicket);

        } else {

            // One (or more) references was found in this attribute.
            if (referencingValues.length > 1)
                log.logDebug("Found " + referencingValues.length + " DN references in attribute '"
                        + referencingAttribute + "'; ignoring all but first", mySessionTicket);
            log.logDebug("Following reference '" + referencingValues[0] + "' found in '" + referencingAttribute
                    + "' to look up attribute(s) '" + attributeReferences.get(referencingAttribute).toString(),
                    mySessionTicket);
            String providerURL = null; // To be used later.
            try {

                // Follow the reference.
                providerURL = (String) ldap.getEnvironment().get(Context.PROVIDER_URL);
                providerURL = providerURL.substring(0, providerURL.lastIndexOf("/") + 1) + referencingValues[0];
                ldap.addToEnvironment(Context.PROVIDER_URL, providerURL);

            } catch (NamingException e) {
                throw new BackendException("Unable to update provider URL in LDAP environment", e);
            }

            // Add any referenced attributes returned.
            HashMap additionalAttributes = getAttributes(ldap, providerURL,
                    (String[]) attributeReferences.get(referencingAttribute).toArray(new String[] {}));
            Iterator i = additionalAttributes.keySet().iterator();
            while (i.hasNext()) {
                String attributeName = (String) i.next();
                convertedAttributes.put(referencingAttribute
                        + DirectoryManagerBackend.ATTRIBUTE_REFERENCE_SEPARATOR + attributeName,
                        (String[]) additionalAttributes.get(attributeName));
            }

        }

    }

    return convertedAttributes;

}

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

public void removeAttributeValue(String name, Object value) {
    if (!updateMode && value != null) {
        Attribute attr = originalAttrs.get(name);
        if (attr != null) {
            attr.remove(value);//from   w  w  w .j a va 2  s.  c om
            if (attr.size() == 0) {
                originalAttrs.remove(name);
            }
        }
    } else if (updateMode) {
        Attribute attr = updatedAttrs.get(name);
        if (attr == null) {
            if (originalAttrs.get(name) != null) {
                attr = (Attribute) originalAttrs.get(name).clone();
                attr.remove(value);
                updatedAttrs.put(attr);
            }
        } else {
            attr.remove(value);
        }
    }
}

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

/**
 * Remove existing statically defined links for the given target id (dynamic references remain unaltered)
 *
 * @see org.nuxeo.ecm.directory.Reference#removeLinksForTarget(String)
 *//* w ww.  j  a v a2 s  .c  o  m*/
@Override
public void removeLinksForTarget(String targetId) throws DirectoryException {
    if (!isStatic()) {
        // nothing to do: dynamic references cannot be updated
        return;
    }
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();
            LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        if (!sourceSession.isReadOnly()) {
            // get the dn of the target that matches targetId
            String targetAttributeValue;

            if (staticAttributeIdIsDn) {
                SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId);
                if (targetLdapEntry == null) {
                    String rdnAttribute = ldapTargetDirectory.getDescriptor().getRdnAttribute();
                    if (!rdnAttribute.equals(targetSession.idAttribute)) {
                        log.warn(String.format(
                                "cannot remove links to missing entry %s in directory %s for reference %s",
                                targetId, ldapTargetDirectory.getName(), this));
                        return;
                    }
                    // the entry might have already been deleted, try to
                    // re-forge it if possible (might not work if scope is
                    // subtree)
                    targetAttributeValue = String.format("%s=%s,%s", rdnAttribute, targetId,
                            ldapTargetDirectory.getDescriptor().getSearchBaseDn());
                } else {
                    targetAttributeValue = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace());
                }
            } else {
                targetAttributeValue = targetId;
            }

            // build a LDAP query to find entries that point to the target
            String searchFilter = String.format("(%s=%s)", attributeId, targetAttributeValue);
            String sourceFilter = ldapSourceDirectory.getBaseFilter();

            if (sourceFilter != null && !"".equals(sourceFilter)) {
                searchFilter = String.format("(&(%s)(%s))", searchFilter, sourceFilter);
            }

            SearchControls scts = new SearchControls();
            scts.setSearchScope(ldapSourceDirectory.getDescriptor().getSearchScope());
            scts.setReturningAttributes(new String[] { attributeId });

            // find all source entries that point to the target key and
            // clean
            // those references
            if (log.isDebugEnabled()) {
                log.debug(String.format(
                        "LDAPReference.removeLinksForTarget(%s): LDAP search baseDn='%s' "
                                + " filter='%s' scope='%s' [%s]",
                        targetId, sourceSession.searchBaseDn, searchFilter, scts.getSearchScope(), this));
            }
            NamingEnumeration<SearchResult> results = sourceSession.dirContext
                    .search(sourceSession.searchBaseDn, searchFilter, scts);
            String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
            Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker);

            try {
                while (results.hasMore()) {
                    SearchResult result = results.next();
                    Attributes attrs = result.getAttributes();
                    Attribute attr = attrs.get(attributeId);
                    try {
                        if (attr.size() == 1) {
                            // the attribute holds the last reference, put
                            // the
                            // empty ref. marker before removing the
                            // attribute
                            // since empty attribute are often not allowed
                            // by
                            // the server schema
                            if (log.isDebugEnabled()) {
                                log.debug(String.format(
                                        "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' "
                                                + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]",
                                        targetId, result.getNameInNamespace(), attrs, this));
                            }
                            sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(),
                                    DirContext.ADD_ATTRIBUTE, emptyAttribute);
                        }
                        // remove the reference to the target key
                        attrs = new BasicAttributes();
                        attr = new BasicAttribute(attributeId);
                        attr.add(targetAttributeValue);
                        attrs.put(attr);
                        if (log.isDebugEnabled()) {
                            log.debug(String.format(
                                    "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' "
                                            + "mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                                    targetId, result.getNameInNamespace(), attrs, this));
                        }
                        sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(),
                                DirContext.REMOVE_ATTRIBUTE, attrs);
                    } catch (SchemaViolationException e) {
                        if (isDynamic()) {
                            // we are editing an entry that has no static
                            // part
                            log.warn(String.format("cannot remove dynamic reference in field %s for target %s",
                                    getFieldName(), targetId));
                        } else {
                            // this is a real schema configuration problem,
                            // wrapup the exception
                            throw new DirectoryException(e);
                        }
                    }
                }
            } finally {
                results.close();
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("removeLinksForTarget failed: " + e.getMessage(), e);
    }
}

From source file:net.spfbl.core.Core.java

private static boolean isRouteable(String hostame) {
    try {/*from w w  w .ja  va 2s  . c o  m*/
        Attributes attributesA = Server.getAttributesDNS(hostame, new String[] { "A" });
        Attribute attributeA = attributesA.get("A");
        if (attributeA == null) {
            Attributes attributesAAAA = Server.getAttributesDNS(hostame, new String[] { "AAAA" });
            Attribute attributeAAAA = attributesAAAA.get("AAAA");
            if (attributeAAAA != null) {
                for (int i = 0; i < attributeAAAA.size(); i++) {
                    String host6Address = (String) attributeAAAA.get(i);
                    if (SubnetIPv6.isValidIPv6(host6Address)) {
                        try {
                            InetAddress address = InetAddress.getByName(host6Address);
                            if (address.isLinkLocalAddress()) {
                                return false;
                            } else if (address.isLoopbackAddress()) {
                                return false;
                            }
                        } catch (UnknownHostException ex) {
                        }
                    } else {
                        return false;
                    }
                }
            }
        } else {
            for (int i = 0; i < attributeA.size(); i++) {
                String host4Address = (String) attributeA.get(i);
                host4Address = host4Address.trim();
                if (SubnetIPv4.isValidIPv4(host4Address)) {
                    try {
                        InetAddress address = InetAddress.getByName(host4Address);
                        if (address.isLinkLocalAddress()) {
                            return false;
                        } else if (address.isLoopbackAddress()) {
                            return false;
                        }
                    } catch (UnknownHostException ex) {
                    }
                } else {
                    return false;
                }
            }
        }
        return true;
    } catch (NamingException ex) {
        return false;
    }
}

From source file:org.liveSense.auth.ldap.LdapAuthenticationHandler.java

/**
 * Copy LDAP user properties to JCR User properties
 * @param ldapUser/* w ww .j a va  2  s  .c o m*/
 */
private void updateUserAttributes(Session session, LdapUser ldapUser, Authorizable user) {
    // Collecting attribute names
    try {
        for (Iterator e = user.getPropertyNames(); e.hasNext();) {
            user.removeProperty((String) e.next());
        }

        for (NamingEnumeration<? extends Attribute> ae = ldapUser.getAttributes().getAll(); ae.hasMore();) {
            Attribute attr = ae.next();
            log.info("Attribute: " + attr.getID());
            // multi value attribute
            if (attr.size() > 1) {
                Value[] props = new Value[attr.size()];
                int i = 0;
                for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
                    Object o = e.next();
                    if (o instanceof String)
                        props[i] = session.getValueFactory().createValue((String) o);
                    i++;
                }
                user.setProperty(attr.getID(), props);
            } else {
                if (attr.get(0) instanceof String)
                    user.setProperty(attr.getID(), session.getValueFactory().createValue((String) attr.get(0)));
            }
        }
    } catch (Exception e) {
        log.error("Could not update user attributes", e);
    }

}