Java Code Examples for org.apache.directory.api.util.Strings

The following examples show how to use org.apache.directory.api.util.Strings. These examples are extracted from open source projects. 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
@Override
protected void useBundleClasses() throws Exception
{
    List<Schema> schemas = new ArrayList<Schema>();

    Schema schema = new Schema();
    schema.setName( "foo" );
    schema.setInput( new ByteArrayInputStream(
        Strings.getBytesUtf8( "attributetype ( 1.3.6.1.4.1.18060.0.4.2.3.14 NAME ( 'at' 'attribute' ) )" ) ) );

    Writer out = new StringWriter( 2048 );
    schema.setOutput( out );
    schemas.add( schema );

    SchemaToLdif.transform( schemas );
}
 
Example 2
Source Project: directory-ldap-api   Source File: SchemaAwareEntryTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test method for userCertificate;binary AT
 */
@Test
public void testUserCertificateBinary() throws LdapException
{
    Entry entry = new DefaultEntry( schemaManager );
    entry.add( "objectClass", "top", "person", "inetorgPerson" );
    entry.add( "cn", "test1", "test2" );
    entry.add( "sn", "Test1", "Test2" );
    entry.add( "userPassword", BYTES1, BYTES2 );

    entry.add( "userCertificate;binary", Strings.getBytesUtf8( "secret" ) );
    assertTrue( entry.containsAttribute( "userCertificate;binary" ) );
    assertTrue( entry.containsAttribute( "userCertificate" ) );

    entry.removeAttributes( "userCertificate;binary" );
    assertFalse( entry.containsAttribute( "userCertificate;binary" ) );
    assertFalse( entry.containsAttribute( "userCertificate" ) );

    entry.add( "userCertificate", Strings.getBytesUtf8( "secret" ) );
    assertTrue( entry.containsAttribute( "userCertificate;binary" ) );
    assertTrue( entry.containsAttribute( "userCertificate" ) );
}
 
Example 3
/**
 * Initialize OIDs maps for normalization
 */
@BeforeAll
public static void setup() throws Exception
{
    schemaManager = new DefaultSchemaManager();
    cn = schemaManager.getAttributeType( "cn" );
    dc = schemaManager.getAttributeType( "dc" );
    userCertificate = schemaManager.getAttributeType( "userCertificate" );

    bv1 = new Value( userCertificate, DATA );
    bv2 = new Value( userCertificate, Strings.EMPTY_BYTES );
    bv3 = new Value( userCertificate, ( byte[] ) null );
    bv1n = new Value( userCertificate, DATA );
    bv2n = new Value( userCertificate, Strings.EMPTY_BYTES );
    bv3n = new Value( userCertificate, ( byte[] ) null );
    sv1 = new Value( cn, "test" );
    sv2 = new Value( dc, "" );
    sv3 = new Value( dc, ( String ) null );
    sv1n = new Value( cn, "test" );
    sv2n = new Value( dc, "" );
    sv3n = new Value( dc, ( String ) null );
}
 
Example 4
/**
 * Parses a subtree specification without exhausting the parser.
 * 
 * @param spec
 *            the specification to be parsed
 * @return the specification bean
 * @throws ParseException
 *             if there are any recognition errors (bad syntax)
 */
public synchronized SubtreeSpecification parse( String spec ) throws ParseException
{
    SubtreeSpecification ss;

    if ( ( spec == null ) || Strings.isEmpty( spec.trim() ) )
    {
        return null;
    }

    // reset and initialize the parser / lexer pair
    reset( spec );

    try
    {
        ss = this.parser.wrapperEntryPoint();
    }
    catch ( TokenStreamException | RecognitionException e )
    {
        String msg = I18n.err( I18n.ERR_13028_SUBTREE_SPEC_PARSER_FAILURE, spec, e.getLocalizedMessage() );
        throw new ParseException( msg, 0 );
    }

    return ss;
}
 
Example 5
Source Project: directory-ldap-api   Source File: PasswordUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * generates a hash based on the <a href="http://en.wikipedia.org/wiki/PBKDF2">PKCS5S2 spec</a>
 * 
 * Note: this has been implemented to generate hashes compatible with what JIRA generates.
 *       See the <a href="http://pythonhosted.org/passlib/lib/passlib.hash.atlassian_pbkdf2_sha1.html">JIRA's passlib</a>
 *       
 * @param credentials the credentials
 * @param algorithm the algorithm to use
 * @param salt the optional salt
 * @return the digested credentials
 */
private static byte[] generatePbkdf2Hash( byte[] credentials, LdapSecurityConstants algorithm, byte[] salt )
{
    try
    {
        SecretKeyFactory sk = SecretKeyFactory.getInstance( algorithm.getAlgorithm() );
        char[] password = Strings.utf8ToString( credentials ).toCharArray();
        KeySpec keySpec = new PBEKeySpec( password, salt, 10000, PKCS5S2_LENGTH * 8 );
        Key key = sk.generateSecret( keySpec );
        return key.getEncoded();
    }
    catch ( Exception e )
    {
        throw new RuntimeException( e );
    }
}
 
Example 6
/**
 * Parses the system properties to obtain the intermediate responses.
 * Such intermediate responses are stored in the <b>apacheds.intermediateResponses</b>
 * and <b>default.intermediateResponses.requests</b> system properties.
 *
 * @return a list of intermediate responses
 */
private static List<String> getIntermediateResponsesFromSystemProperties()
{
    List<String> intermediateResponsesList = new ArrayList<>();

    // Loading extended operations from command line properties if it exists
    String defaultIntermediateResponsesList = System.getProperty( INTERMEDIATE_RESPONSES_LIST );

    if ( !Strings.isEmpty( defaultIntermediateResponsesList ) )
    {
        for ( String intermediateResponse : defaultIntermediateResponsesList.split( "," ) )
        {
            intermediateResponsesList.add( intermediateResponse );
        }
    }

    return intermediateResponsesList;
}
 
Example 7
/**
 * Test an extended operation.
 */
@Test
public void testLoadingExtendedOperation() throws Exception
{
    LdapApiService codec = LdapApiServiceFactory.getSingleton();
    StoredProcedureRequest req = new StoredProcedureRequestImpl();
    req.setLanguage( "Java" );
    req.setProcedure( Strings.getBytesUtf8( "bogusProc" ) );

    assertNotNull( req );
    assertNotNull( codec );
    
    StoredProcedureFactory factory = ( StoredProcedureFactory ) codec.getExtendedRequestFactories().get( 
        StoredProcedureRequest.EXTENSION_OID );
    
    req = factory.newRequest();
    assertNotNull( req );
}
 
Example 8
/**
 * @see Object#toString()
 */
@Override
public String toString()
{
    StringBuilder sb = new StringBuilder();

    sb.append( "StartTransactionResponse :" );
    sb.append( "\n    transactionID : " );

    if ( transactionId != null )
    {
        sb.append( Strings.dumpBytes( transactionId ) );
    }
    else
    {
        sb.append( "null" );
    }

    return sb.toString();
}
 
Example 9
Source Project: directory-fortress-core   Source File: RegExUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *  Perform safe text validation on character string.
 *
 * @param  value Contains the string to check.
 * @exception org.apache.directory.fortress.core.ValidationException  In the event the data validation fails.
 */
void safeText( String value ) throws ValidationException
{
    if ( Strings.isEmpty( SAFE_TEXT_PATTERN_STRING ) )
    {
        LOG.debug( "safeText can't find safeText regular expression pattern.  Check your Fortress cfg" );
    }
    else
    {
        Matcher safeTextMatcher = safeTextPattern.matcher( value );
        
        if ( !safeTextMatcher.find() )
        {
            String error = "safeText has detected invalid value [" + value + "]";
            throw new ValidationException( GlobalErrIds.CONST_INVLD_TEXT, error );
        }
    }
}
 
Example 10
Source Project: directory-ldap-api   Source File: SchemaElementImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return The description as a ldif line
 * @throws org.apache.directory.api.ldap.model.exception.LdapException If the conversion goes wrong
 */
private String descToLdif() throws LdapException
{
    if ( Strings.isEmpty( description ) )
    {
        return "";
    }
    else
    {
        Entry entry = new DefaultEntry();
        Attribute attribute = new DefaultAttribute( "m-description", description );

        entry.put( attribute );

        return LdifUtils.convertAttributesToLdif( entry );
    }
}
 
Example 11
Source Project: directory-ldap-api   Source File: StoreMatchingRuleType.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void action( LdapMessageContainer<SearchRequest> container ) throws DecoderException
{
    TLV tlv = container.getCurrentTLV();

    if ( tlv.getLength() == 0 )
    {
        String msg = I18n.err( I18n.ERR_05141_NULL_MATCHING_RULE_ASSERTION_TYPE );
        LOG.error( msg );
        throw new DecoderException( msg );
    }
    else
    {
        // Store the value.
        ExtensibleMatchFilter extensibleMatchFilter = ( ExtensibleMatchFilter ) container.getTerminalFilter();

        String type = Strings.utf8ToString( tlv.getValue().getData() );
        extensibleMatchFilter.setType( type );

        if ( LOG.isDebugEnabled() )
        {
            LOG.debug( I18n.msg( I18n.MSG_05166_STORED_TYPE_MATCHING_RULE, type ) );
        }
    }
}
 
Example 12
Source Project: directory-ldap-api   Source File: BindResponseImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get a String representation of a BindResponse
 * 
 * @return A BindResponse String
 */
@Override
public String toString()
{
    StringBuilder sb = new StringBuilder();

    sb.append( "    BindResponse\n" );
    sb.append( super.toString() );

    if ( serverSaslCreds != null )
    {
        sb.append( "        Server sasl credentials : '" ).append( Strings.dumpBytes( serverSaslCreds ) )
            .append( "'\n" );
    }

    return super.toString( sb.toString() );
}
 
Example 13
Source Project: directory-ldap-api   Source File: ExtendedRequestTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test parsing of a request with a RequestValue element with Base64 value
 */
@Test
public void testRequestWithBase64RequestValue()
{
    Dsmlv2Parser parser = null;
    try
    {
        parser = newParser();

        parser.setInput( ExtendedRequestTest.class.getResource( "request_with_base64_requestValue.xml" )
            .openStream(), "UTF-8" );

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

    ExtendedRequestDsml<?, ?> extendedRequest =
        ( ExtendedRequestDsml<?, ?> ) parser.getBatchRequest().getCurrentRequest();

    assertEquals( "DSMLv2.0 rocks!!", Strings.utf8ToString( extendedRequest.getRequestValue() ) );
}
 
Example 14
Source Project: directory-ldap-api   Source File: StoreMatchingRuleId.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void action( LdapMessageContainer<SearchRequest> container ) throws DecoderException
{
    TLV tlv = container.getCurrentTLV();

    // Store the value.
    ExtensibleMatchFilter extensibleMatchFilter = ( ExtensibleMatchFilter )
        container.getTerminalFilter();

    if ( tlv.getLength() == 0 )
    {
        String msg = I18n.err( I18n.ERR_05001_EMPTY_MATCHING_RULE );
        LOG.error( msg );

        // It will generate a PROTOCOL_ERROR
        throw new DecoderException( msg );
    }
    else
    {
        extensibleMatchFilter.setMatchingRule( Strings.utf8ToString( tlv.getValue().getData() ) );
    }
}
 
Example 15
Source Project: directory-ldap-api   Source File: AbstractSchemaObject.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<String> getExtension( String extension )
{
    String name = Strings.toUpperCaseAscii( extension );
    
    if ( hasExtension( name ) )
    {
        for ( Map.Entry<String, List<String>> entry : extensions.entrySet() )
        {
            String key = entry.getKey();
            
            if ( name.equalsIgnoreCase( key ) )
            {
                return entry.getValue();
            }
        }
    }

    return null;
}
 
Example 16
@Test
public void testAdDirSyncControlNoCookie() throws DecoderException, EncoderException
{
    ByteBuffer bb = ByteBuffer.allocate( 0x0A );

    bb.put( new byte[]
        {
            0x30, 0x08,
              0x02, 0x01, 0x01,  // flag (LDAP_DIRSYNC_OBJECT_SECURITY)
              0x02, 0x01, 0x00,  // maxReturnLength (no limit)
              0x04, 0x00         // the cookie
        } );

    bb.flip();

    AdDirSyncResponseFactory factory = ( AdDirSyncResponseFactory ) codec.getResponseControlFactories().
        get( AdDirSyncResponse.OID );
    AdDirSyncResponse adDirSyncResponse = factory.newControl();
    factory.decodeValue( adDirSyncResponse, bb.array() );

    assertEquals( EnumSet.of( AdDirSyncResponseFlag.LDAP_DIRSYNC_OBJECT_SECURITY ), adDirSyncResponse.getFlags() );
    assertEquals( 0, adDirSyncResponse.getMaxReturnLength() );
    assertEquals( "", Strings.utf8ToString( adDirSyncResponse.getCookie() ) );

    // Check the reverse encoding
    Asn1Buffer asn1Buffer = new Asn1Buffer();

    factory.encodeValue( asn1Buffer, adDirSyncResponse );

    assertArrayEquals( bb.array(),  asn1Buffer.getBytes().array() );
}
 
Example 17
Source Project: directory-ldap-api   Source File: DefaultEntry.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean contains( String upId, String... values )
{
    if ( Strings.isEmpty( upId ) )
    {
        return false;
    }

    String id = getId( upId );

    if ( schemaManager != null )
    {
        try
        {
            return contains( schemaManager.lookupAttributeTypeRegistry( id ), values );
        }
        catch ( LdapException le )
        {
            return false;
        }
    }

    Attribute attribute = attributes.get( id );

    if ( attribute == null )
    {
        return false;
    }

    return attribute.contains( values );
}
 
Example 18
/**
 * {@inheritDoc}
 */
@Override
public boolean isValidSyntax( Object value )
{
    String strValue;

    if ( value == null )
    {
        if ( LOG.isDebugEnabled() )
        {
            LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) );
        }
        
        return false;
    }

    if ( value instanceof String )
    {
        strValue = ( String ) value;
    }
    else if ( value instanceof byte[] )
    {
        strValue = Strings.utf8ToString( ( byte[] ) value );
    }
    else
    {
        strValue = value.toString();
    }

    strValue = Strings.trim( Strings.toLowerCaseAscii( strValue ) );

    return "base".equals( strValue ) || "one".equals( strValue ) || "sub".equals( strValue );
}
 
Example 19
Source Project: directory-ldap-api   Source File: SchemaAwareEntryTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test the serialization of an entry with no Dn
 */
@Test
public void testSerializeEntryWithNoDN() throws LdapException, IOException, ClassNotFoundException
{
    byte[] password = Strings.getBytesUtf8( "secret" );
    Entry entry = new DefaultEntry();
    entry.add( "ObjectClass", "top", "person" );
    entry.add( "cn", "test1" );
    entry.add( "userPassword", password );

    Entry entrySer = deserializeValue( serializeValue( entry ) );

    assertEquals( entry, entrySer );
}
 
Example 20
Source Project: directory-ldap-api   Source File: UuidSyntaxChecker.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean isValidSyntax( Object value )
{
    if ( value == null )
    {
        if ( LOG.isDebugEnabled() )
        {
            LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) );
        }
        
        return false;
    }

    if ( value instanceof UUID )
    {
        return true;
    }

    if ( !( value instanceof String ) )
    {
        if ( LOG.isDebugEnabled() )
        {
            LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) );
        }
        
        return false;
    }

    return Strings.isValidUuid( ( String ) value );
}
 
Example 21
/**
 * {@inheritDoc}
 */
public void action( LdapMessageContainer<SearchResultEntry> container ) throws DecoderException
{
    SearchResultEntry searchResultEntry = container.getMessage();

    TLV tlv = container.getCurrentTLV();

    // Store the value.
    if ( tlv.getLength() == 0 )
    {
        searchResultEntry.setObjectName( Dn.EMPTY_DN );
    }
    else
    {
        byte[] dnBytes = tlv.getValue().getData();
        String dnStr = Strings.utf8ToString( dnBytes );

        try
        {
            Dn objectName = new Dn( dnStr );
            searchResultEntry.setObjectName( objectName );
        }
        catch ( LdapInvalidDnException ine )
        {
            // This is for the client side. We will never decode LdapResult on the server
            String msg = I18n.err( I18n.ERR_05157_INVALID_DN, Strings.dumpBytes( dnBytes ), ine.getMessage() );
            LOG.error( I18n.err( I18n.ERR_05114_ERROR_MESSAGE, msg, ine.getMessage() ) );
            throw new DecoderException( msg, ine );
        }
    }

    if ( LOG.isDebugEnabled() )
    {
        LOG.debug( I18n.msg( I18n.MSG_05182_SEARCH_RESULT_ENTRY_DN, searchResultEntry.getObjectName() ) );
    }
}
 
Example 22
/**
 * Test the decoding of an IntermediateResponse without name
 */
@Test
public void testDecodeIntermediateResponseNoName() throws EncoderException, DecoderException
{
    ByteBuffer stream = ByteBuffer.allocate( 0x0E );

    stream.put( new byte[]
        { 
            0x30, 0x0C,             // LDAPMessage ::= SEQUENCE {
              0x02, 0x01, 0x01,     // messageID MessageID
                                    // CHOICE { ..., intermediateResponse IntermediateResponse, ...
              0x79, 0x07,           // IntermediateResponse ::= [APPLICATION 25] SEQUENCE {
                                    // responseValue [1] OCTET STRING OPTIONAL,
                ( byte ) 0x81, 0x05,
                  'v', 'a', 'l', 'u', 'e' 
        } );

    stream.flip();

    // Allocate a LdapMessage Container
    LdapMessageContainer<IntermediateResponse> ldapMessageContainer =
        new LdapMessageContainer<>( codec );

    // Decode the IntermediateResponse PDU
    Asn1Decoder.decode( stream, ldapMessageContainer );

    // Check the decoded IntermediateResponse PDU
    IntermediateResponse intermediateResponse = ldapMessageContainer.getMessage();

    assertEquals( 1, intermediateResponse.getMessageId() );
    assertEquals( "", intermediateResponse.getResponseName() );
    assertEquals( "value", Strings.utf8ToString( intermediateResponse.getResponseValue() ) );

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

    LdapEncoder.encodeMessage( buffer, codec, intermediateResponse );

    assertArrayEquals( stream.array(), buffer.getBytes().array() );
}
 
Example 23
Source Project: directory-ldap-api   Source File: BerValue.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Encode an OctetString
 *
 * @param buffer The PDU in which the value will be put
 * @param data The byte[] to be encoded
 */
public static void encodeOctetString( Asn1Buffer buffer, byte[] data )
{
    if ( Strings.isEmpty( data ) )
    {
        buffer.put( ( byte ) 0 );
    }
    else
    {
        buffer.put( data );
        buffer.put( TLV.getBytes( data.length ) );
    }

    buffer.put( UniversalTag.OCTET_STRING.getValue() );
}
 
Example 24
Source Project: MyVirtualDirectory   Source File: DefaultEntry.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the attributeType from an Attribute ID.
 */
protected AttributeType getAttributeType( String upId ) throws LdapException
{
    if ( Strings.isEmpty( Strings.trim( upId ) ) )
    {
        String message = I18n.err( I18n.ERR_04457_NULL_ATTRIBUTE_ID );
        LOG.error( message );
        throw new IllegalArgumentException( message );
    }

    return schemaManager.lookupAttributeTypeRegistry( upId );
}
 
Example 25
Source Project: directory-ldap-api   Source File: VLVRequestControlTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodeOffsetWithContextID() throws DecoderException, EncoderException
{
    ByteBuffer bb = ByteBuffer.allocate( 0x16 );

    bb.put( new byte[]
        {
            0x30, 0x14,             // VirtualListViewRequest ::= SEQUENCE {
              0x02, 0x01, 0x01,     //    beforeCount    INTEGER (0..maxInt),
              0x02, 0x01, 0x01,     //    afterCount     INTEGER (0..maxInt),
              ( byte ) 0xA0, 0x06,  //    target       CHOICE {
                                    //                   byOffset        [0] SEQUENCE {
                0x02, 0x01, 0x01,   //                        offset          INTEGER (1 .. maxInt),
                0x02, 0x01, 0x01,   //                        contentCount    INTEGER (0 .. maxInt) },
              0x04, 0x04,           //    contextID     OCTET STRING OPTIONAL }
                'a', 'b', 'c', 'd'
        } );

    bb.flip();

    // Test decoding
    VirtualListViewRequestFactory factory = ( VirtualListViewRequestFactory ) codec.getRequestControlFactories().
        get( VirtualListViewRequest.OID );
    VirtualListViewRequest virtualListView = factory.newControl();
    factory.decodeValue( virtualListView, bb.array() );

    assertEquals( 1, virtualListView.getBeforeCount() );
    assertEquals( 1, virtualListView.getAfterCount() );
    assertTrue( virtualListView.hasOffset() );
    assertEquals( 1, virtualListView.getOffset() );
    assertEquals( 1, virtualListView.getContentCount() );
    assertEquals( "abcd", Strings.utf8ToString( virtualListView.getContextId() ) );

    // Check the reverse encoding
    Asn1Buffer asn1Buffer = new Asn1Buffer();

    factory.encodeValue( asn1Buffer, virtualListView );

    assertArrayEquals( bb.array(),  asn1Buffer.getBytes().array() );
}
 
Example 26
/**
 * Test the decoding of a SyncInfoValue control, refreshDelete choice,
 * refreshDone = false
 */
@Test
public void testDecodeSyncInfoValueControlRefreshDeleteRefreshDoneFalse() throws DecoderException, EncoderException
{
    ByteBuffer bb = ByteBuffer.allocate( 0x0A );
    bb.put( new byte[]
        {
            ( byte ) 0xA1, 0x08,                // syncInfoValue ::= CHOICE {
                                                //     refreshDelete [1] SEQUENCE {
              0x04, 0x03,
                'a', 'b', 'c',                  //         cookie       syncCookie OPTIONAL,
              0x01, 0x01, ( byte ) 0x00         //         refreshDone  BOOLEAN DEFAULT TRUE
        } );
    bb.flip();

    SyncInfoValueFactory factory = ( SyncInfoValueFactory ) codec.getIntermediateResponseFactories().
        get( SyncInfoValue.OID );
    SyncInfoValue syncInfoValue = factory.newResponse();
    factory.decodeValue( syncInfoValue, bb.array() );

    assertEquals( SynchronizationInfoEnum.REFRESH_DELETE, syncInfoValue.getSyncInfoValueType() );
    assertEquals( "abc", Strings.utf8ToString( syncInfoValue.getCookie() ) );
    assertFalse( syncInfoValue.isRefreshDone() );

    // Check the revert encoding
    Asn1Buffer asn1Buffer = new Asn1Buffer();

    factory.encodeValue( asn1Buffer, syncInfoValue );
    
    assertArrayEquals( bb.array(), asn1Buffer.getBytes().array() );
}
 
Example 27
Source Project: directory-ldap-api   Source File: AbstractSchemaObject.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add an extension with its values
 * @param key The extension key
 * @param values The associated values
 */
@Override
public void addExtension( String key, List<String> values )
{
    if ( locked )
    {
        throw new UnsupportedOperationException( I18n.err( I18n.ERR_13700_CANNOT_MODIFY_LOCKED_SCHEMA_OBJECT, getName() ) );
    }

    extensions.put( Strings.toUpperCaseAscii( key ), values );
    
    computeHashCode();
}
 
Example 28
Source Project: MyVirtualDirectory   Source File: DefaultEntry.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean contains( String upId, Value<?>... values )
{
    if ( Strings.isEmpty( upId ) )
    {
        return false;
    }

    String id = getId( upId );

    if ( schemaManager != null )
    {
        try
        {
            return contains( schemaManager.lookupAttributeTypeRegistry( id ), values );
        }
        catch ( LdapException le )
        {
            return false;
        }
    }

    Attribute attribute = attributes.get( id );

    if ( attribute == null )
    {
        return false;
    }

    return attribute.contains( values );
}
 
Example 29
/**
 * Test the decoding of a PasswordModifyRequest with a user identity
 */
@Test
public void testDecodePasswordModifyRequestUserIdentityValueOldPasswordValue() throws DecoderException
{
    byte[] bb = new byte[]
        { 
            0x30, 0x0C,                 // PasswordModifyRequest ::= SEQUENCE {
              ( byte ) 0x80, 0x04,      // userIdentity    [0]  OCTET STRING OPTIONAL
                'a', 'b', 'c', 'd',
              ( byte ) 0x81, 0x04,      // oldPassword    [1]  OCTET STRING OPTIONAL
                'e', 'f', 'g', 'h'
        };

    PasswordModifyFactory factory = ( PasswordModifyFactory ) codec.getExtendedRequestFactories().
        get( PasswordModifyRequest.EXTENSION_OID );
    PasswordModifyRequest passwordModifyRequest = ( PasswordModifyRequest ) factory.newRequest( bb );
    
    assertNotNull( passwordModifyRequest.getUserIdentity() );
    assertEquals( "abcd", Strings.utf8ToString( passwordModifyRequest.getUserIdentity() ) );
    assertNotNull( passwordModifyRequest.getOldPassword() );
    assertEquals( "efgh", Strings.utf8ToString( passwordModifyRequest.getOldPassword() ) );
    assertNull( passwordModifyRequest.getNewPassword() );

    // Check the reverse decoding
    Asn1Buffer asn1Buffer = new Asn1Buffer();

    factory.encodeValue( asn1Buffer, passwordModifyRequest );

    assertArrayEquals( bb,  asn1Buffer.getBytes().array() );
}
 
Example 30
Source Project: directory-ldap-api   Source File: ModifyRequestTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test parsing of a request with a (optional) Control element with Base64 Value
 */
@Test
public void testRequestWith1ControlBase64Value()
{
    Dsmlv2Parser parser = null;
    try
    {
        parser = newParser();

        parser.setInput( ModifyRequestTest.class.getResource( "request_with_1_control_base64_value.xml" )
            .openStream(), "UTF-8" );

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

    ModifyRequest modifyRequest = ( ModifyRequest ) parser.getBatchRequest().getCurrentRequest();
    Map<String, Control> controls = modifyRequest.getControls();

    assertEquals( 1, modifyRequest.getControls().size() );

    Control control = controls.get( "1.2.840.113556.1.4.643" );

    assertNotNull( control );
    assertTrue( control.isCritical() );
    assertEquals( "1.2.840.113556.1.4.643", control.getOid() );
    assertEquals( "DSMLv2.0 rocks!!", Strings.utf8ToString( ( ( DsmlControl<?> ) control ).getValue() ) );
}