Java Code Examples for org.apache.directory.api.ldap.model.entry.Entry#get()

The following examples show how to use org.apache.directory.api.ldap.model.entry.Entry#get() . 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: SchemaInterceptor.java    From MyVirtualDirectory with Apache License 2.0 7 votes vote down vote up
/**
 * Checks to see if an attribute is required by as determined from an entry's
 * set of objectClass attribute values.
 *
 * @return true if the objectClass values require the attribute, false otherwise
 * @throws Exception if the attribute is not recognized
 */
private void assertAllAttributesAllowed( Dn dn, Entry entry, Set<String> allowed ) throws LdapException
{
    // Never check the attributes if the extensibleObject objectClass is
    // declared for this entry
    Attribute objectClass = entry.get( OBJECT_CLASS_AT );

    if ( objectClass.contains( SchemaConstants.EXTENSIBLE_OBJECT_OC ) )
    {
        return;
    }

    for ( Attribute attribute : entry )
    {
        String attrOid = attribute.getAttributeType().getOid();

        AttributeType attributeType = attribute.getAttributeType();

        if ( !attributeType.isCollective() && ( attributeType.getUsage() == UsageEnum.USER_APPLICATIONS )
            && !allowed.contains( attrOid ) )
        {
            throw new LdapSchemaViolationException( ResultCodeEnum.OBJECT_CLASS_VIOLATION, I18n.err( I18n.ERR_277,
                attribute.getUpId(), dn.getName() ) );
        }
    }
}
 
Example 2
Source File: LdifAttributesReaderTest.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
@Test
public void testLdifVersionStart() throws LdapLdifException, IOException
{
    String ldif = 
          "cn: app1\n" 
        + "objectClass: top\n" 
        + "objectClass: apApplication\n" 
        + "displayName:   app1   \n"
        + "dependencies:\n" 
        + "envVars:";

    LdifAttributesReader reader = new LdifAttributesReader();
    Entry entry = reader.parseEntry( ldif );

    assertEquals( 1, reader.getVersion() );
    assertNotNull( entry );

    Attribute attr = entry.get( "displayname" );
    assertTrue( attr.contains( "app1" ) );
    reader.close();
}
 
Example 3
Source File: LdifAttributesReaderTest.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Spaces at the end of values should not be included into values.
 * 
 * @throws NamingException
 */
@Test
public void testLdifParserEndSpaces() throws LdapLdifException, IOException
{
    String ldif = 
          "cn: app1\n" 
        + "objectClass: top\n" 
        + "objectClass: apApplication\n" 
        + "displayName:   app1   \n"
        + "dependencies:\n" 
        + "envVars:";

    LdifAttributesReader reader = new LdifAttributesReader();

    Entry entry = reader.parseEntry( ldif );
    assertNotNull( entry );

    Attribute attr = entry.get( "displayname" );
    assertTrue( attr.contains( "app1" ) );
    reader.close();
}
 
Example 4
Source File: LdapPosixTestEnvironment.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void init() throws Exception {
  initializeDirectory();

  // Enable POSIX groups in ApacheDS
  Dn nis = new Dn("cn=nis,ou=schema");
  if (service.getAdminSession().exists(nis)) {
    Entry entry = service.getAdminSession().lookup(nis);
    Attribute nisDisabled = entry.get("m-disabled");
    if (null != nisDisabled && "TRUE".equalsIgnoreCase(nisDisabled.getString())) {
      nisDisabled.remove("TRUE");
      nisDisabled.add("FALSE");
      List<Modification> modifications = new ArrayList<Modification>();
      modifications.add(new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, nisDisabled));
      service.getAdminSession().modify(nis, modifications);
      service.shutdown();
      initializeDirectory(); // Note: This instantiates service again for schema modifications to take effect.
    }
  }

  startServer();

  createGroup("office-berlin");
  createUserUid("daniel", "office-berlin", "Daniel", "Meyer", "[email protected]");

  createGroup("people");
  createUserUid("ruecker", "people", "Bernd", "Ruecker", "[email protected]");
  createUserUid("monster", "people", "Cookie", "Monster", "[email protected]");
  createUserUid("fozzie", "people", "Bear", "Fozzie", "[email protected]");

  createGroup("groups");
  createPosixGroup("1", "posix-group-without-members");
  createPosixGroup("2", "posix-group-with-members", "fozzie", "monster", "ruecker");
}
 
Example 5
Source File: LDAPApi.java    From mamute with Apache License 2.0 5 votes vote down vote up
private byte[] getByteAttribute(Entry entry, String attribute) throws LdapException, InvalidAttributeValueException {
	Attribute value = entry.get(attribute);
	if (value != null) {
		return value.getBytes();
	}
	return null;
}
 
Example 6
Source File: InMemorySchemaPartition.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Partition initialization - loads schema entries from the files on classpath.
 *
 * @see org.apache.directory.server.core.partition.impl.avl.AvlPartition#doInit()
 */
@Override
protected void doInit() throws InvalidNameException, Exception {
   if (initialized) {
      return;
   }

   LOG.debug("Initializing schema partition " + getId());
   suffixDn.apply(schemaManager);
   super.doInit();

   // load schema
   final Map<String, Boolean> resMap = ResourceMap.getResources(Pattern.compile("schema[/\\Q\\\\E]ou=schema.*"));
   for (String resourcePath : new TreeSet<>(resMap.keySet())) {
      if (resourcePath.endsWith(".ldif")) {
         URL resource = DefaultSchemaLdifExtractor.getUniqueResource(resourcePath, "Schema LDIF file");
         LdifEntry ldifEntry;
         try (LdifReader reader = new LdifReader(resource.openStream())) {
            ldifEntry = reader.next();
         }

         Entry entry = new DefaultEntry(schemaManager, ldifEntry.getEntry());
         // add mandatory attributes
         if (entry.get(SchemaConstants.ENTRY_CSN_AT) == null) {
            entry.add(SchemaConstants.ENTRY_CSN_AT, defaultCSNFactory.newInstance().toString());
         }
         if (entry.get(SchemaConstants.ENTRY_UUID_AT) == null) {
            entry.add(SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString());
         }
         AddOperationContext addContext = new AddOperationContext(null, entry);
         super.add(addContext);
      }
   }
}
 
Example 7
Source File: ServerEntryUtils.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a ServerEntry into a BasicAttributes. The Dn is lost
 * during this conversion, as the Attributes object does not store
 * this element.
 *
 * @return An instance of a AttributesImpl() object
 */
public static Attributes toBasicAttributes( Entry entry )
{
    if ( entry == null )
    {
        return null;
    }

    Attributes attributes = new BasicAttributes( true );

    for ( Attribute attribute : entry.getAttributes() )
    {
        AttributeType attributeType = attribute.getAttributeType();
        Attribute attr = entry.get( attributeType );

        // Deal with a special case : an entry without any ObjectClass
        if ( attributeType.getOid().equals( SchemaConstants.OBJECT_CLASS_AT_OID ) && attr.size() == 0 )
        {
            // We don't have any objectClass, just dismiss this element
            continue;
        }

        attributes.put( toBasicAttribute( attr ) );
    }

    return attributes;
}
 
Example 8
Source File: InMemorySchemaPartition.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Partition initialization - loads schema entries from the files on classpath.
 *
 * @see org.apache.directory.server.core.partition.impl.avl.AvlPartition#doInit()
 */
@Override
protected void doInit() throws Exception {
    if (initialized)
        return;

    LOG.debug("Initializing schema partition " + getId());
    suffixDn.apply(schemaManager);
    super.doInit();

    // load schema
    final Map<String, Boolean> resMap = ResourceMap.getResources(Pattern.compile("schema[/\\Q\\\\E]ou=schema.*"));
    for (String resourcePath : new TreeSet<String>(resMap.keySet())) {
        if (resourcePath.endsWith(".ldif")) {
            URL resource = DefaultSchemaLdifExtractor.getUniqueResource(resourcePath, "Schema LDIF file");
            LdifReader reader = new LdifReader(resource.openStream());
            LdifEntry ldifEntry = reader.next();
            reader.close();

            Entry entry = new DefaultEntry(schemaManager, ldifEntry.getEntry());
            // add mandatory attributes
            if (entry.get(SchemaConstants.ENTRY_CSN_AT) == null) {
                entry.add(SchemaConstants.ENTRY_CSN_AT, defaultCSNFactory.newInstance().toString());
            }
            if (entry.get(SchemaConstants.ENTRY_UUID_AT) == null) {
                entry.add(SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString());
            }
            AddOperationContext addContext = new AddOperationContext(null, entry);
            super.add(addContext);
        }
    }
}
 
Example 9
Source File: AttributeUtilsTest.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Test a addModification applied to an entry with the same attribute
 * but with another value 
 */
@Test
public void testApplyAddModificationToEntryWithValues() throws LdapException
{
    Entry entry = new DefaultEntry();
    entry.put( "cn", "apache" );
    assertEquals( 1, entry.size() );

    Attribute attr = new DefaultAttribute( "cn", "test" );
    Modification modification = new DefaultModification( ModificationOperation.ADD_ATTRIBUTE, attr );
    AttributeUtils.applyModification( entry, modification );
    assertNotNull( entry.get( "cn" ) );
    assertEquals( 1, entry.size() );

    Attribute attribute = entry.get( "cn" );

    assertTrue( attribute.size() != 0 );

    Set<String> expectedValues = new HashSet<String>();
    expectedValues.add( "apache" );
    expectedValues.add( "test" );

    for ( Value value : attribute )
    {
        String valueStr = value.getString();

        assertTrue( expectedValues.contains( valueStr ) );

        expectedValues.remove( valueStr );
    }

    assertEquals( 0, expectedValues.size() );
}
 
Example 10
Source File: AttributeUtilsTest.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Test a addModification applied to an entry with the same attribute
 * and the same value 
 */
@Test
public void testApplyAddModificationToEntryWithSameValue() throws LdapException
{
    Entry entry = new DefaultEntry();
    entry.put( "cn", "test", "apache" );
    assertEquals( 1, entry.size() );

    Attribute attr = new DefaultAttribute( "cn", "test" );
    Modification modification = new DefaultModification( ModificationOperation.ADD_ATTRIBUTE, attr );
    AttributeUtils.applyModification( entry, modification );
    assertNotNull( entry.get( "cn" ) );
    assertEquals( 1, entry.size() );

    Attribute cnAttr = entry.get( "cn" );

    assertTrue( cnAttr.size() != 0 );

    Set<String> expectedValues = new HashSet<String>();
    expectedValues.add( "apache" );
    expectedValues.add( "test" );

    for ( Value value : cnAttr )
    {
        String valueStr = value.getString();

        assertTrue( expectedValues.contains( valueStr ) );

        expectedValues.remove( valueStr );
    }

    assertEquals( 0, expectedValues.size() );
}
 
Example 11
Source File: LdifAttributesReaderTest.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
@Test
public void testLdifParserBase64MultiLine() throws LdapLdifException, IOException
{
    String ldif = 
          "#comment\n" 
        + "cn:: RW1tYW51ZWwg\n" 
        + " TMOpY2hhcm55ICA=\n" 
        + "objectClass: top\n"
        + "objectClass: apApplication\n" 
        + "displayName: app1\n" 
        + "serviceType: http\n" 
        + "dependencies:\n"
        + "httpHeaders:\n" 
        + "startupOptions:\n" 
        + "envVars:";

    LdifAttributesReader reader = new LdifAttributesReader();
    Entry entry = reader.parseEntry( ldif );

    assertNotNull( entry );

    Attribute attr = entry.get( "cn" );
    assertTrue( attr.contains( "Emmanuel L\u00e9charny  ".getBytes( StandardCharsets.UTF_8 ) ) );

    attr = entry.get( "objectclass" );
    assertTrue( attr.contains( "top" ) );
    assertTrue( attr.contains( "apApplication" ) );

    attr = entry.get( "displayname" );
    assertTrue( attr.contains( "app1" ) );

    attr = entry.get( "dependencies" );
    assertEquals( "", attr.get().getString() );

    attr = entry.get( "envvars" );
    assertEquals( "", attr.get().getString() );
    reader.close();
}
 
Example 12
Source File: LdapLoginManager.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
private static Attribute getAttr(Properties config, Entry entry, String aliasCode, String defaultAlias) {
	String alias = config.getProperty(aliasCode, "");
	if (Strings.isEmpty(alias)) {
		alias = defaultAlias;
	}
	return Strings.isEmpty(alias) ? null : entry.get(alias);
}
 
Example 13
Source File: LdifAttributesReaderTest.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
@Test
public void testLdifParserMuiltiLineComments() throws LdapLdifException, IOException
{
    String ldif = 
          "#comment\n" 
        + " still a comment\n" 
        + "cn: app1#another comment\n" 
        + "objectClass: top\n"
        + "objectClass: apApplication\n" 
        + "displayName: app1\n" 
        + "serviceType: http\n" 
        + "dependencies:\n"
        + "httpHeaders:\n" 
        + "startupOptions:\n" 
        + "envVars:";

    LdifAttributesReader reader = new LdifAttributesReader();
    Entry entry = reader.parseEntry( ldif );

    assertNotNull( entry );

    Attribute attr = entry.get( "cn" );
    assertTrue( attr.contains( "app1#another comment" ) );

    attr = entry.get( "objectclass" );
    assertTrue( attr.contains( "top" ) );
    assertTrue( attr.contains( "apApplication" ) );

    attr = entry.get( "displayname" );
    assertTrue( attr.contains( "app1" ) );

    attr = entry.get( "dependencies" );
    assertEquals( "", attr.get().getString() );

    attr = entry.get( "envvars" );
    assertEquals( "", attr.get().getString() );
    reader.close();
}
 
Example 14
Source File: InMemorySchemaPartition.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Partition initialization - loads schema entries from the files on classpath.
 *
 * @see org.apache.directory.server.core.partition.impl.avl.AvlPartition#doInit()
 */
@Override
protected void doInit() throws Exception {
    if (initialized)
        return;

    LOG.debug("Initializing schema partition " + getId());
    suffixDn.apply(schemaManager);
    super.doInit();

    // load schema
    final Map<String, Boolean> resMap = ResourceMap.getResources(Pattern.compile("schema[/\\Q\\\\E]ou=schema.*"));
    for (String resourcePath : new TreeSet<String>(resMap.keySet())) {
        if (resourcePath.endsWith(".ldif")) {
            URL resource = DefaultSchemaLdifExtractor.getUniqueResource(resourcePath, "Schema LDIF file");
            LdifReader reader = new LdifReader(resource.openStream());
            LdifEntry ldifEntry = reader.next();
            reader.close();

            Entry entry = new DefaultEntry(schemaManager, ldifEntry.getEntry());
            // add mandatory attributes
            if (entry.get(SchemaConstants.ENTRY_CSN_AT) == null) {
                entry.add(SchemaConstants.ENTRY_CSN_AT, defaultCSNFactory.newInstance().toString());
            }
            if (entry.get(SchemaConstants.ENTRY_UUID_AT) == null) {
                entry.add(SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString());
            }
            AddOperationContext addContext = new AddOperationContext(null, entry);
            super.add(addContext);
        }
    }
}
 
Example 15
Source File: SearchResultEntryTest.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * Test the decoding of a SearchResultEntry
 */
@Test
public void testDecodeSearchResultEntry2AttrsSuccess() throws DecoderException, EncoderException, LdapException
{
    ByteBuffer stream = ByteBuffer.allocate( 0x7b );

    stream.put( new byte[]
        {
            0x30, 0x79,                     // LDAPMessage ::=SEQUENCE {
              0x02, 0x01, 0x01,             // messageID MessageID
              0x64, 0x74,                   // CHOICE { ..., searchResEntry SearchResultEntry,
                                            // ...
                                            // SearchResultEntry ::= [APPLICATION 4] SEQUENCE {
                                            // objectName LDAPDN,
                0x04, 0x1b,
                  'o', 'u', '=', 'c', 'o', 'n', 't', 'a', 'c', 't', 's', ',',
                  'd', 'c', '=', 'i', 'k', 't', 'e', 'k', ',', 'd', 'c', '=', 'c', 'o', 'm',
                                            // attributes PartialAttributeList }
                                            // PartialAttributeList ::= SEQUENCE OF SEQUENCE {
                0x30, 0x55,
                  0x30, 0x28,
                    0x04, 0x0b,             // type AttributeDescription,
                      'o', 'b', 'j', 'e', 'c', 't', 'c', 'l', 'a', 's', 's',
                    0x31, 0x19,             // vals SET OF AttributeValue }
                      0x04, 0x03,           // AttributeValue ::= OCTET STRING
                        't', 'o', 'p',
                      0x04, 0x12,           // AttributeValue ::= OCTET STRING
                        'o', 'r', 'g', 'a', 'n', 'i', 'z', 'a', 't', 'i', 'o', 'n', 'a', 'l', 'U', 'n', 'i', 't',
                  0x30, 0x29,
                    0x04, 0x0c,             // type AttributeDescription,
                      'o', 'b', 'j', 'e', 'c', 't', 'c', 'l', 'a', 's', 's', '2',
                    0x31, 0x19,             // vals SET OF AttributeValue }
                      0x04, 0x03,           // AttributeValue ::= OCTET STRING
                        't', 'o', 'p',
                      0x04, 0x12,           // AttributeValue ::= OCTET STRING
                        'o', 'r', 'g', 'a', 'n', 'i', 'z', 'a', 't', 'i', 'o', 'n', 'a', 'l', 'U', 'n', 'i', 't'
        } );

    stream.flip();

    // Allocate a BindRequest Container
    LdapMessageContainer<SearchResultEntry> ldapMessageContainer =
        new LdapMessageContainer<>( codec );

    Asn1Decoder.decode( stream, ldapMessageContainer );

    SearchResultEntry searchResultEntry = ldapMessageContainer.getMessage();

    assertEquals( 1, searchResultEntry.getMessageId() );
    assertEquals( "ou=contacts,dc=iktek,dc=com", searchResultEntry.getObjectName().toString() );

    Entry entry = searchResultEntry.getEntry();

    assertEquals( 2, entry.size() );

    String[] expectedAttributes = new String[]
        { "objectClass", "objectClass2" };

    for ( int i = 0; i < expectedAttributes.length; i++ )
    {
        Attribute attribute = entry.get( expectedAttributes[i] );

        assertEquals(
            Strings.toLowerCaseAscii( expectedAttributes[i] ),
            Strings.toLowerCaseAscii( attribute.getUpId() ) );

        assertTrue( attribute.contains( "top" ) );
        assertTrue( attribute.contains( "organizationalUnit" ) );
    }

    // Check encode reverse
    Asn1Buffer buffer = new Asn1Buffer();

    ByteBuffer result = LdapEncoder.encodeMessage( buffer, codec, searchResultEntry );

    // We can't compare the encodings, the order of the attributes has
    // changed
    LdapMessageContainer<SearchResultEntry> ldapMessageContainer2 =
        new LdapMessageContainer<>( codec );

    Asn1Decoder.decode( result, ldapMessageContainer2 );

    assertEquals( searchResultEntry.getEntry(), ldapMessageContainer2.getMessage().getEntry() );
    assertEquals( searchResultEntry.getObjectName(), ldapMessageContainer2.getMessage().getObjectName() );
}
 
Example 16
Source File: SchemaEntityFactory.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public LdapComparator<?> getLdapComparator( SchemaManager schemaManager, Entry entry, Registries targetRegistries,
    String schemaName ) throws LdapException
{
    checkEntry( entry, SchemaConstants.COMPARATOR );

    // The Comparator OID
    String oid = getOid( entry, SchemaConstants.COMPARATOR, schemaManager.isStrict() );

    // Get the schema
    if ( !schemaManager.isSchemaLoaded( schemaName ) )
    {
        // The schema is not loaded. We can't create the requested Comparator
        String msg = I18n.err( I18n.ERR_16022_CANNOT_ADD_CMP, entry.getDn().getName(), schemaName );
        
        if ( LOG.isWarnEnabled() )
        {
            LOG.warn( msg );
        }
        
        throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg );
    }

    Schema schema = getSchema( schemaName, targetRegistries );

    if ( schema == null )
    {
        // The schema is disabled. We still have to update the backend
        if ( LOG.isInfoEnabled() )
        {
            LOG.info( I18n.err( I18n.ERR_16023_CANNOT_ADD_CMP_IN_REGISTRY, entry.getDn().getName(), schemaName ) );
        }
        
        schema = schemaManager.getLoadedSchema( schemaName );
    }

    // The FQCN
    String fqcn = getFqcn( entry, SchemaConstants.COMPARATOR );

    // The ByteCode
    Attribute byteCode = entry.get( MetaSchemaConstants.M_BYTECODE_AT );

    try
    {
        // Class load the comparator
        LdapComparator<?> comparator = classLoadComparator( schemaManager, oid, fqcn, byteCode );

        // Update the common fields
        setSchemaObjectProperties( comparator, entry, schema );

        // return the resulting comparator
        return comparator;
    }
    catch ( Exception e )
    {
        throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, e.getMessage(), e );
    }
}
 
Example 17
Source File: SchemaEntityFactory.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public ObjectClass getObjectClass( SchemaManager schemaManager, Entry entry, Registries targetRegistries,
    String schemaName ) throws LdapException
{
    checkEntry( entry, SchemaConstants.OBJECT_CLASS );

    // The ObjectClass OID
    String oid = getOid( entry, SchemaConstants.OBJECT_CLASS, schemaManager.isStrict() );

    // Get the schema
    if ( !schemaManager.isSchemaLoaded( schemaName ) )
    {
        // The schema is not loaded. We can't create the requested ObjectClass
        String msg = I18n.err( I18n.ERR_16030_CANNOT_ADD_OC, entry.getDn().getName(), schemaName );
        
        if ( LOG.isWarnEnabled() )
        {
            LOG.warn( msg );
        }
        
        throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg );
    }

    Schema schema = getSchema( schemaName, targetRegistries );

    if ( schema == null )
    {
        // The schema is disabled. We still have to update the backend
        if ( LOG.isInfoEnabled() )
        {
            LOG.info( I18n.err( I18n.ERR_16031_CANNOT_ADD_OC_IN_REGISTRY, entry.getDn().getName(), schemaName ) );
        }
        
        schema = schemaManager.getLoadedSchema( schemaName );
    }

    // Create the ObjectClass instance
    ObjectClass oc = new ObjectClass( oid );

    // The Sup field
    Attribute mSuperiors = entry.get( MetaSchemaConstants.M_SUP_OBJECT_CLASS_AT );

    if ( mSuperiors != null )
    {
        oc.setSuperiorOids( getStrings( mSuperiors ) );
    }

    // The May field
    Attribute mMay = entry.get( MetaSchemaConstants.M_MAY_AT );

    if ( mMay != null )
    {
        oc.setMayAttributeTypeOids( getStrings( mMay ) );
    }

    // The Must field
    Attribute mMust = entry.get( MetaSchemaConstants.M_MUST_AT );

    if ( mMust != null )
    {
        oc.setMustAttributeTypeOids( getStrings( mMust ) );
    }

    // The objectClassType field
    Attribute mTypeObjectClass = entry.get( MetaSchemaConstants.M_TYPE_OBJECT_CLASS_AT );

    if ( mTypeObjectClass != null )
    {
        String type = mTypeObjectClass.getString();
        oc.setType( ObjectClassTypeEnum.getClassType( type ) );
    }

    // Common properties
    setSchemaObjectProperties( oc, entry, schema );

    return oc;
}
 
Example 18
Source File: SearchResultEntryTest.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * Test parsing of a response with 2 Attr 1 Value
 */
@Test
public void testResponseWith2Attr1Value()
{
    Dsmlv2ResponseParser parser = null;
    try
    {
        parser = new Dsmlv2ResponseParser( getCodec() );

        parser.setInput(
            SearchResultEntryTest.class.getResource( "response_with_2_attr_1_value.xml" ).openStream(), "UTF-8" );

        parser.parse();
    }
    catch ( Exception e )
    {
        fail( e.getMessage() );
    }

    SearchResultEntry searchResultEntry = ( ( SearchResponse ) parser.getBatchResponse().getCurrentResponse()
        .getDecorated() )
        .getCurrentSearchResultEntry();

    Entry entry = searchResultEntry.getEntry();
    assertEquals( 2, entry.size() );

    Attribute objectClassAttribute = entry.get( "objectclass" );
    assertEquals( 1, objectClassAttribute.size() );

    Iterator<Value> valueIterator = objectClassAttribute.iterator();
    assertTrue( valueIterator.hasNext() );
    Value value = valueIterator.next();
    assertEquals( "top", value.getString() );
    assertFalse( valueIterator.hasNext() );

    Attribute dcAttribute = entry.get( "dc" );
    assertEquals( 1, objectClassAttribute.size() );

    valueIterator = dcAttribute.iterator();
    assertTrue( valueIterator.hasNext() );
    value = valueIterator.next();
    assertEquals( "example", value.getString() );
    assertFalse( valueIterator.hasNext() );
}
 
Example 19
Source File: SchemaEntityFactory.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Normalizer getNormalizer( SchemaManager schemaManager, Entry entry, Registries targetRegistries,
    String schemaName ) throws LdapException
{
    checkEntry( entry, SchemaConstants.NORMALIZER );

    // The Normalizer OID
    String oid = getOid( entry, SchemaConstants.NORMALIZER, schemaManager.isStrict() );

    // Get the schema
    if ( !schemaManager.isSchemaLoaded( schemaName ) )
    {
        // The schema is not loaded. We can't create the requested Normalizer
        String msg = I18n.err( I18n.ERR_16024_CANNOT_ADD_NORMALIZER, entry.getDn().getName(), schemaName );
        
        if ( LOG.isWarnEnabled() )
        {
            LOG.warn( msg );
        }
        
        throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg );
    }

    Schema schema = getSchema( schemaName, targetRegistries );

    if ( schema == null )
    {
        // The schema is disabled. We still have to update the backend
        if ( LOG.isInfoEnabled() )
        {
            LOG.info( I18n.err( I18n.ERR_16025_CANNOT_ADD_NORMALIZER_IN_REGISTRY, entry.getDn().getName(), schemaName ) );
        }
        
        schema = schemaManager.getLoadedSchema( schemaName );
    }

    // The FQCN
    String className = getFqcn( entry, SchemaConstants.NORMALIZER );

    // The ByteCode
    Attribute byteCode = entry.get( MetaSchemaConstants.M_BYTECODE_AT );

    try
    {
        // Class load the Normalizer
        Normalizer normalizer = classLoadNormalizer( schemaManager, oid, className, byteCode );

        // Update the common fields
        setSchemaObjectProperties( normalizer, entry, schema );

        // return the resulting Normalizer
        return normalizer;
    }
    catch ( Exception e )
    {
        throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, e.getMessage(), e );
    }
}
 
Example 20
Source File: ObjectQueryService.java    From guacamole-client with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the identifier of the object represented by the given LDAP
 * entry. Multiple attributes may be declared as containing the identifier
 * of the object when present on an LDAP entry. If multiple such attributes
 * are present on the same LDAP entry, the value of the attribute with
 * highest priority is used. If multiple copies of the same attribute are
 * present on the same LDAPentry, the first value of that attribute is
 * used.
 *
 * @param entry
 *     The entry representing the Guacamole object whose unique identifier
 *     should be determined.
 *
 * @param attributes
 *     A collection of all attributes which may be used to specify the
 *     unique identifier of the Guacamole object represented by an LDAP
 *     entry, in order of decreasing priority.
 *
 * @return
 *     The identifier of the object represented by the given LDAP entry, or
 *     null if no attributes declared as containing the identifier of the
 *     object are present on the entry.
 * 
 * @throws LdapInvalidAttributeValueException
 *     If an error occurs retrieving the value of the identifier attribute.
 */
public String getIdentifier(Entry entry, Collection<String> attributes) 
        throws LdapInvalidAttributeValueException {

    // Retrieve the first value of the highest priority identifier attribute
    for (String identifierAttribute : attributes) {
        Attribute identifier = entry.get(identifierAttribute);
        if (identifier != null)
            return identifier.getString();
    }

    // No identifier attribute is present on the entry
    return null;

}