javax.naming.directory.Attributes Java Examples

The following examples show how to use javax.naming.directory.Attributes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LDAPLoginModule.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if Collection of naming Attributes contain defined required properties for OLAT * Configuration: LDAP Required Map = olatextconfig.xml (property=reqAttrs)
 * 
 * @param attributes
 *            Collection of LDAP Naming Attribute
 * @return null If all required Attributes are found, otherwise String[] of missing Attributes
 */
public static String[] checkReqAttr(final Attributes attrs) {
    final Map<String, String> reqAttrMap = getReqAttrs();
    final String[] missingAttr = new String[reqAttrMap.size()];
    int y = 0;
    for (String attKey : reqAttrMap.keySet()) {
        attKey = attKey.trim();
        if (attrs.get(attKey) == null) {
            missingAttr[y++] = attKey;
        }
    }
    if (y == 0) {
        return null;
    } else {
        return missingAttr;
    }
}
 
Example #2
Source File: LdapService.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
   public void updateLDAPUser(User user, Attributes attrs) {
HashMap<String, String> map = getLDAPUserAttributes(attrs);
user.setLogin(map.get("login"));
user.setFirstName(map.get("fname"));
user.setLastName(map.get("lname"));
user.setEmail(map.get("email"));
user.setAddressLine1(map.get("address1"));
user.setAddressLine2(map.get("address2"));
user.setAddressLine3(map.get("address3"));
user.setCity(map.get("city"));
user.setState(map.get("state"));
user.setPostcode(map.get("postcode"));
user.setCountry(map.get("country"));
user.setDayPhone(map.get("dayphone"));
user.setEveningPhone(map.get("eveningphone"));
user.setFax(map.get("fax"));
user.setMobilePhone(map.get("mobile"));
user.setLocale(getLocale(map.get("locale")));
user.setDisabledFlag(getDisabledBoolean(attrs));
service.saveUser(user);
   }
 
Example #3
Source File: UserGroupAttributesMapper.java    From geofence with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object mapFromAttributes(Attributes attrs) throws NamingException
{
    UserGroup group = new UserGroup();

    String id = getAttribute(attrs, "id");
    if(StringUtils.isBlank(id)) {
        LOGGER.warn("Empty id for UserGroup");
        if(LOGGER.isDebugEnabled()) {
            for(Object oa: Collections.list(attrs.getAll())) {
                Attribute a = (Attribute)oa;
                LOGGER.debug("---> " + a);
            }
        }
    }
    group.setExtId(id);
    group.setName(getAttribute(attrs, "groupname"));
    group.setEnabled(true);

    return group;
}
 
Example #4
Source File: NamingManager.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static Context getURLContext(
        String scheme, Hashtable<?,?> environment)
        throws NamingException {
    return new DnsContext("", null, new Hashtable<String,String>()) {
        public Attributes getAttributes(String name, String[] attrIds)
                throws NamingException {
            return new BasicAttributes() {
                public Attribute get(String attrID) {
                    BasicAttribute ba  = new BasicAttribute(attrID);
                    ba.add("1 1 99 b.com.");
                    ba.add("0 0 88 a.com.");    // 2nd has higher priority
                    return ba;
                }
            };
        }
    };
}
 
Example #5
Source File: ContextSourceAndHibernateTransactionManagerNamespaceITest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdate() {
	String dn = "cn=Some Person,ou=company1,ou=Sweden";
	OrgPerson person = (OrgPerson) this.hibernateTemplate.load(OrgPerson.class, new Integer(1));
	person.setLastname("Updated Person");
	person.setDescription("Updated description");

	dummyDao.update(person);

	log.debug("Verifying result");
	Object ldapResult = ldapTemplate.lookup(dn, new AttributesMapper() {
		public Object mapFromAttributes(Attributes attributes) throws NamingException {
			assertThat(attributes.get("sn").get()).isEqualTo("Updated Person");
			assertThat(attributes.get("description").get()).isEqualTo("Updated description");
			return new Object();
		}
	});

	OrgPerson updatedPerson = (OrgPerson) this.hibernateTemplate.load(OrgPerson.class, new Integer(1));
	assertThat(updatedPerson.getLastname()).isEqualTo("Updated Person");
	assertThat(updatedPerson.getDescription()).isEqualTo("Updated description");
	assertThat(ldapResult).isNotNull();
}
 
Example #6
Source File: LdapCertificateRepo.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected List<X509CRL> getCRLsFromLdap(String tmpRootDN, String tmpFilter, String tmpAttrName) {
    try {
        List<X509CRL> crls = new ArrayList<>();
        NamingEnumeration<SearchResult> answer = ldapSearch.searchSubTree(tmpRootDN, tmpFilter);
        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute attribute = attrs.get(tmpAttrName);
            if (attribute != null) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509CRL crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(
                        (byte[]) attribute.get()));
                crls.add(crl);
            }
        }
        return crls;
    } catch (CertificateException | NamingException | CRLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example #7
Source File: LdapResult.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
boolean compareToSearchResult(String name) {
    boolean successful = false;

    switch (status) {
        case LdapClient.LDAP_COMPARE_TRUE:
            status = LdapClient.LDAP_SUCCESS;
            entries = new Vector<>(1,1);
            Attributes attrs = new BasicAttributes(LdapClient.caseIgnore);
            LdapEntry entry = new LdapEntry( name, attrs );
            entries.addElement(entry);
            successful = true;
            break;

        case LdapClient.LDAP_COMPARE_FALSE:
            status = LdapClient.LDAP_SUCCESS;
            entries = new Vector<>(0);
            successful = true;
            break;

        default:
            successful = false;
            break;
    }

    return successful;
}
 
Example #8
Source File: LdapManager.java    From fess with Apache License 2.0 6 votes vote down vote up
protected List<Object> getAttributeValueList(final List<SearchResult> result, final String name) {
    try {
        for (final SearchResult srcrslt : result) {
            final Attributes attrs = srcrslt.getAttributes();

            final Attribute attr = attrs.get(name);
            if (attr == null) {
                continue;
            }

            final List<Object> attrList = new ArrayList<>();
            for (int i = 0; i < attr.size(); i++) {
                final Object attrValue = attr.get(i);
                if (attrValue != null) {
                    attrList.add(attrValue);
                }
            }
            return attrList;
        }
        return Collections.emptyList();
    } catch (final NamingException e) {
        throw new LdapOperationException("Failed to parse attribute values for " + name, e);
    }
}
 
Example #9
Source File: LdapUserDao.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
public LdapUser findByUsername(final Object username, final String... organizationalUnits)
{
  return (LdapUser) new LdapTemplate(ldapConnector) {
    @Override
    protected Object call() throws NameNotFoundException, Exception
    {
      NamingEnumeration< ? > results = null;
      final SearchControls controls = new SearchControls();
      controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
      final String searchBase = getSearchBase(organizationalUnits);
      results = ctx.search(searchBase, "(&(objectClass=" + getObjectClass() + ")(uid=" + username + "))", controls);
      if (results.hasMore() == false) {
        return null;
      }
      final SearchResult searchResult = (SearchResult) results.next();
      final String dn = searchResult.getName();
      final Attributes attributes = searchResult.getAttributes();
      if (results.hasMore() == true) {
        log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + username);
      }
      return mapToObject(dn, searchBase, attributes);
    }
  }.excecute();
}
 
Example #10
Source File: ContextSourceAndHibernateTransactionManagerNamespaceITest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testModifyAttributes() {
	String dn = "cn=Some Person,ou=company1,ou=Sweden";
	// Perform test
	dummyDao.modifyAttributes(dn, "Updated lastname", "Updated description");

	// Verify result - check that the operation was not rolled back
	Object result = ldapTemplate.lookup(dn, new AttributesMapper() {
		public Object mapFromAttributes(Attributes attributes) throws NamingException {
			assertThat(attributes.get("sn").get()).isEqualTo("Updated lastname");
			assertThat(attributes.get("description").get()).isEqualTo("Updated description");
			return new Object();
		}
	});

	assertThat(result).isNotNull();
}
 
Example #11
Source File: ScoreCommand.java    From AntiVPN with MIT License 6 votes vote down vote up
private static Set<String> collectRecords(String dns) {
    if (ConfigUtil.getDebugOrFalse()) {
        logger.info("Collecting A records for " + dns);
    }
    Set<String> retVal = new HashSet<>();
    try {
        InitialDirContext context = new InitialDirContext();
        Attributes attributes = context.getAttributes("dns:/" + dns, new String[] { "A" });
        NamingEnumeration<?> attributeEnum = attributes.get("A").getAll();
        while (attributeEnum.hasMore()) {
            retVal.add(attributeEnum.next().toString());
        }
    } catch (NamingException ex) {
        logger.error(ex.getMessage(), ex);
    }
    if (ConfigUtil.getDebugOrFalse()) {
        logger.info("Got " + retVal.size() + " record(s) for " + dns);
    }
    return retVal;
}
 
Example #12
Source File: LdapUtil.java    From zstack with Apache License 2.0 6 votes vote down vote up
public boolean validateDnExist(LdapTemplateContextSource ldapTemplateContextSource, String fullDn){
    try {
        String dn = fullDn.replace("," + ldapTemplateContextSource.getLdapContextSource().getBaseLdapPathAsString(), "");
        Object result = ldapTemplateContextSource.getLdapTemplate().lookup(dn, new AbstractContextMapper<Object>() {
            @Override
            protected Object doMapFromContext(DirContextOperations ctx) {
                Attributes group = ctx.getAttributes();
                return group;
            }
        });
        return result != null;
    }catch (Exception e){
        logger.warn(String.format("validateDnExist[%s] fail", fullDn), e);
        return false;
    }
}
 
Example #13
Source File: DirectoryManager.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private static Object createObjectFromFactories(Object obj, Name name,
        Context nameCtx, Hashtable<?,?> environment, Attributes attrs)
    throws Exception {

    FactoryEnumeration factories = ResourceManager.getFactories(
        Context.OBJECT_FACTORIES, environment, nameCtx);

    if (factories == null)
        return null;

    ObjectFactory factory;
    Object answer = null;
    // Try each factory until one succeeds
    while (answer == null && factories.hasMore()) {
        factory = (ObjectFactory)factories.next();
        if (factory instanceof DirObjectFactory) {
            answer = ((DirObjectFactory)factory).
                getObjectInstance(obj, name, nameCtx, environment, attrs);
        } else {
            answer =
                factory.getObjectInstance(obj, name, nameCtx, environment);
        }
    }
    return answer;
}
 
Example #14
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAttributesSortedStringSetExists() throws Exception {
	final Attributes attrs = new BasicAttributes();
	Attribute multi = new BasicAttribute("abc");
	multi.add("123");
	multi.add("234");
	attrs.put(multi);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(attrs, null);
		}
	}
	tested = new TestableDirContextAdapter();
	SortedSet s = tested.getAttributeSortedStringSet("abc");
	assertThat(s).isNotNull();
	assertThat(s).hasSize(2);
	Iterator it = s.iterator();
	assertThat(it.next()).isEqualTo("123");
	assertThat(it.next()).isEqualTo("234");
}
 
Example #15
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testChangeMultiAttribute_RemoveValue() throws Exception {
	final Attributes fixtureAttrs = new BasicAttributes();
	Attribute multi = new BasicAttribute("abc");
	multi.add("123");
	multi.add("qwe");
	fixtureAttrs.put(multi);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(fixtureAttrs, null);
			setUpdateMode(true);
		}
	}
	tested = new TestableDirContextAdapter();
	assertThat(tested.isUpdateMode()).isTrue();
	tested.setAttributeValues("abc", new String[] { "123" });

	ModificationItem[] modificationItems = tested.getModificationItems();
	assertThat(modificationItems.length).isEqualTo(1);
    assertThat(modificationItems[0].getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
	assertThat(modificationItems[0].getAttribute().get()).isEqualTo("qwe");
}
 
Example #16
Source File: DirectoryManager.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static Object createObjectFromFactories(Object obj, Name name,
        Context nameCtx, Hashtable<?,?> environment, Attributes attrs)
    throws Exception {

    FactoryEnumeration factories = ResourceManager.getFactories(
        Context.OBJECT_FACTORIES, environment, nameCtx);

    if (factories == null)
        return null;

    ObjectFactory factory;
    Object answer = null;
    // Try each factory until one succeeds
    while (answer == null && factories.hasMore()) {
        factory = (ObjectFactory)factories.next();
        if (factory instanceof DirObjectFactory) {
            answer = ((DirObjectFactory)factory).
                getObjectInstance(obj, name, nameCtx, environment, attrs);
        } else {
            answer =
                factory.getObjectInstance(obj, name, nameCtx, environment);
        }
    }
    return answer;
}
 
Example #17
Source File: ContextSourceTransactionManagerNamespaceIntegrationTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnbindWithException() {
	String dn = "cn=Some Person,ou=company1,ou=Sweden";
	try {
		// Perform test
		dummyDao.unbindWithException(dn, "Some Person");
		fail("DummyException expected");
	}
	catch (DummyException expected) {
		assertThat(true).isTrue();
	}

	// Verify result - check that the operation was properly rolled back
	Object ldapResult = ldapTemplate.lookup(dn, new AttributesMapper() {
		public Object mapFromAttributes(Attributes attributes) throws NamingException {
			// Just verify that the entry still exists.
			return new Object();
		}
	});

	assertThat(ldapResult).isNotNull();
}
 
Example #18
Source File: ScoreCommand.java    From AntiVPN with MIT License 6 votes vote down vote up
private static Set<String> collectRecords(String dns) {
    if (ConfigUtil.getDebugOrFalse()) {
        logger.info("Collecting A records for " + dns);
    }
    Set<String> retVal = new HashSet<>();
    try {
        InitialDirContext context = new InitialDirContext();
        Attributes attributes = context.getAttributes("dns:/" + dns, new String[] { "A" });
        NamingEnumeration<?> attributeEnum = attributes.get("A").getAll();
        while (attributeEnum.hasMore()) {
            retVal.add(attributeEnum.next().toString());
        }
    } catch (NamingException ex) {
        logger.error(ex.getMessage(), ex);
    }
    if (ConfigUtil.getDebugOrFalse()) {
        logger.info("Got " + retVal.size() + " record(s) for " + dns);
    }
    return retVal;
}
 
Example #19
Source File: JNDIProviderImpl.java    From ldapchai with GNU Lesser General Public License v2.1 5 votes vote down vote up
@LdapOperation
@ModifyOperation
public final void createEntry( final String entryDN, final Set<String> baseObjectClasses, final Map<String, String> stringAttributes )
        throws ChaiOperationException, ChaiUnavailableException
{
    activityPreCheck();
    getInputValidator().createEntry( entryDN, baseObjectClasses, stringAttributes );

    final Attributes attrs = new BasicAttributes();

    //Put in the base object class an attribute
    final BasicAttribute objectClassAttr = new BasicAttribute( ChaiConstant.ATTR_LDAP_OBJECTCLASS );
    for ( final String loopClass : baseObjectClasses )
    {
        objectClassAttr.add( loopClass );
    }
    attrs.put( objectClassAttr );

    //Add each of the attributes required.
    for ( final Map.Entry<String, String> entry : stringAttributes.entrySet() )
    {
        attrs.put( entry.getKey(), entry.getValue() );
    }

    // Create the object.
    final DirContext ldapConnection = getLdapConnection();
    try
    {
        ldapConnection.createSubcontext( addJndiEscape( entryDN ), attrs );
    }
    catch ( NamingException e )
    {
        convertNamingException( e );
    }
}
 
Example #20
Source File: ProxyDirContext.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the named object as a cache entry, without any exception.
 * 
 * @param name the name of the object to look up
 * @return the cache entry bound to name
 */
public CacheEntry lookupCache(String name) {
    CacheEntry entry = cacheLookup(name);
    if (entry == null) {
        entry = new CacheEntry();
        entry.name = name;
        try {
            Object object = dirContext.lookup(parseName(name));
            if (object instanceof InputStream) {
                entry.resource = new Resource((InputStream) object);
            } else if (object instanceof DirContext) {
                entry.context = (DirContext) object;
            } else if (object instanceof Resource) {
                entry.resource = (Resource) object;
            } else {
                entry.resource = new Resource(new ByteArrayInputStream
                    (object.toString().getBytes(Charset.defaultCharset())));
            }
            Attributes attributes = dirContext.getAttributes(parseName(name));
            if (!(attributes instanceof ResourceAttributes)) {
                attributes = new ResourceAttributes(attributes);
            }
            entry.attributes = (ResourceAttributes) attributes;
        } catch (NamingException e) {
            entry.exists = false;
        }
    }
    return entry;
}
 
Example #21
Source File: LDAPDataDao.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
private String getValueFromAttribute(Attributes attrs, String attrName){
	javax.naming.directory.Attribute attr = attrs.get(attrName);
	if( attr == null ) {
		return null;
	}
	String attrString = attr.toString();
    return attrString.substring(attrString.indexOf(":") + 1);
}
 
Example #22
Source File: ContinuationDirContext.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(Name name,
                            Attributes matchingAttributes,
                            String[] attributesToReturn)
throws NamingException  {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().search(res.getName(), matchingAttributes,
                                     attributesToReturn);
}
 
Example #23
Source File: ContinuationDirContext.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            Attributes matchingAttributes,
                            String[] attributesToReturn)
throws NamingException  {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(),
                                     matchingAttributes,
                                     attributesToReturn);
}
 
Example #24
Source File: ContinuationDirContext.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            Attributes matchingAttributes,
                            String[] attributesToReturn)
throws NamingException  {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(),
                                     matchingAttributes,
                                     attributesToReturn);
}
 
Example #25
Source File: ContinuationDirContext.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            Attributes matchingAttributes)
throws NamingException  {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(),
                                     matchingAttributes);
}
 
Example #26
Source File: ApacheDSRootDseServlet.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException {
    try {
        resp.setContentType("text/plain");
        PrintWriter out = resp.getWriter();

        out.println("*** ApacheDS RootDSE ***\n");

        DirContext ctx = new InitialDirContext(this.createEnv());

        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(new String[] { "*", "+" });
        ctls.setSearchScope(SearchControls.OBJECT_SCOPE);

        NamingEnumeration<SearchResult> result = ctx.search("", "(objectClass=*)", ctls);
        if (result.hasMore()) {
            SearchResult entry = result.next();
            Attributes as = entry.getAttributes();

            NamingEnumeration<String> ids = as.getIDs();
            while (ids.hasMore()) {
                String id = ids.next();
                Attribute attr = as.get(id);
                for (int i = 0; i < attr.size(); ++i) {
                    out.println(id + ": " + attr.get(i));
                }
            }
        }
        ctx.close();

        out.flush();
    } catch (Exception e) {
        throw new ServletException(e);
    }
}
 
Example #27
Source File: LdapUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static String getAttributeValue(final Attributes attributes, final String attributeName) throws NamingException {
    final Attribute attribute = attributes.get(attributeName);
    if (attribute != null) {
        final Object value = attribute.get();
        return String.valueOf(value);
    }
    return null;
}
 
Example #28
Source File: ContinuationDirContext.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(Name name,
                            Attributes matchingAttributes,
                            String[] attributesToReturn)
throws NamingException  {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().search(res.getName(), matchingAttributes,
                                     attributesToReturn);
}
 
Example #29
Source File: ContinuationDirContext.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            Attributes matchingAttributes)
throws NamingException  {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(),
                                     matchingAttributes);
}
 
Example #30
Source File: LdapManager.java    From fess with Apache License 2.0 5 votes vote down vote up
protected void insert(final String entryDN, final Attributes entry, final Supplier<Hashtable<String, String>> envSupplier) {
    try (DirContextHolder holder = getDirContext(envSupplier)) {
        logger.debug("Inserting {}", entryDN);
        holder.get().createSubcontext(entryDN, entry);
    } catch (final NamingException e) {
        throw new LdapOperationException("Failed to add " + entryDN, e);
    }
}