Java Code Examples for org.apache.directory.api.util.Strings#getBytesUtf8()

The following examples show how to use org.apache.directory.api.util.Strings#getBytesUtf8() . 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: SchemaAwareEntryTest.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Test the serialization of a complete entry
 */
@Test
public void testSerializeCompleteEntry() throws LdapException, IOException, ClassNotFoundException
{
    Dn dn = new Dn( schemaManager,  "ou=system" );

    byte[] password = Strings.getBytesUtf8( "secret" );
    Entry entry = new DefaultEntry( dn );
    entry.add( "ObjectClass", "top", "person" );
    entry.add( "cn", "test1" );
    entry.add( "userPassword", password );

    Entry entrySer = deserializeValue( serializeValue( entry ) );

    assertEquals( entry, entrySer );
}
 
Example 2
Source File: AttributeTest.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Test the serialization of a client attribute with a binary value
 */
@Test
public void testSerializeAttributeBinaryValue() throws LdapException, IOException, ClassNotFoundException
{
    DefaultAttribute dca = new DefaultAttribute( "UserPassword" );
    byte[] password = Strings.getBytesUtf8( "secret" );
    dca.add( password );

    DefaultAttribute dcaSer = deserializeValue( serializeValue( dca ) );
    assertEquals( dca.toString(), dcaSer.toString() );
    assertEquals( "userpassword", dcaSer.getId() );
    assertEquals( "UserPassword", dcaSer.getUpId() );
    assertTrue( Arrays.equals( dca.getBytes(), dcaSer.getBytes() ) );
    assertEquals( 1, dcaSer.size() );
    assertTrue( dcaSer.contains( password ) );
    assertFalse( dcaSer.isHumanReadable() );
}
 
Example 3
Source File: SchemaParser.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Thread safe method parses an OpenLDAP schemaObject element/object.
 *
 * @param schemaObject the String image of a complete schema object
 * @return The list of parsed schema elements
 * @throws java.io.IOException If the schema file can't be processed
 * @throws java.text.ParseException If we weren't able to parse the schema
 */
public synchronized List<SchemaElement> parse( String schemaObject ) throws IOException, ParseException
{
    if ( ( schemaObject == null ) || ( schemaObject.trim().equals( Strings.EMPTY_STRING ) ) )
    {
        throw new ParseException( I18n.err( I18n.ERR_15002_EMPTY_OR_NULL_SCHEMA_OBJECT ), 0 );
    }

    schemaIn = new ByteArrayInputStream( Strings.getBytesUtf8( schemaObject ) );

    if ( producerThread == null )
    {
        producerThread = new Thread( new DataProducer() );
    }

    producerThread.start();

    return invokeParser( schemaObject );
}
 
Example 4
Source File: SchemaAwareEntryTest.java    From directory-ldap-api with 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 5
Source File: BinaryValueAttributeTypeTest.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Test serialization of a Value which normalized value is the same
 * than the value
 */
@Test
public void testNormalizedBinarySameValueSerialization() throws LdapException, IOException, ClassNotFoundException
{
    byte[] v1 = Strings.getBytesUtf8( "Test   Test" );

    // First check with a value which will be normalized
    Value sbv = new Value( at, v1 );

    Value sbvSer = deserializeValue( serializeValue( sbv ), at );

    assertEquals( sbv, sbvSer );
}
 
Example 6
Source File: DefaultCoreSession.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
private Value<?> convertToValue( String oid, Object value ) throws LdapException
{
    Value<?> val = null;

    AttributeType attributeType = directoryService.getSchemaManager().lookupAttributeTypeRegistry( oid );

    // make sure we add the request controls to operation
    if ( attributeType.getSyntax().isHumanReadable() )
    {
        if ( value instanceof String )
        {
            val = new StringValue( attributeType, ( String ) value );
        }
        else if ( value instanceof byte[] )
        {
            val = new StringValue( attributeType, Strings.utf8ToString( ( byte[] ) value ) );
        }
        else
        {
            throw new LdapException( I18n.err( I18n.ERR_309, oid ) );
        }
    }
    else
    {
        if ( value instanceof String )
        {
            val = new BinaryValue( attributeType, Strings.getBytesUtf8( ( String ) value ) );
        }
        else if ( value instanceof byte[] )
        {
            val = new BinaryValue( attributeType, ( byte[] ) value );
        }
        else
        {
            throw new LdapException( I18n.err( I18n.ERR_309, oid ) );
        }
    }

    return val;
}
 
Example 7
Source File: Csn.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Get the CSN as a byte array. The data are stored as :
 * bytes 1 to 8  : timestamp, big-endian
 * bytes 9 to 12 : change count, big endian
 * bytes 13 to ... : ReplicaId 
 * 
 * @return A copy of the byte array representing theCSN
 */
public byte[] getBytes()
{
    if ( bytes == null )
    {
        bytes = Strings.getBytesUtf8( csnStr );
    }

    byte[] copy = new byte[bytes.length];
    System.arraycopy( bytes, 0, copy, 0, bytes.length );
    return copy;
}
 
Example 8
Source File: Csn.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance of SimpleCSN from the serialized data
 *
 * @param value The byte array which contains the serialized CSN
 */
Csn( byte[] value )
{
    csnStr = Strings.utf8ToString( value );
    Csn csn = new Csn( csnStr );
    timestamp = csn.timestamp;
    changeCount = csn.changeCount;
    replicaId = csn.replicaId;
    operationNumber = csn.operationNumber;
    bytes = Strings.getBytesUtf8( csnStr );
}
 
Example 9
Source File: AbstractLdapConnection.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void bind( Dn name, String credentials ) throws LdapException
{
    byte[] credBytes = credentials == null ? Strings.EMPTY_BYTES : Strings.getBytesUtf8( credentials );

    BindRequest bindRequest = new BindRequestImpl();
    bindRequest.setDn( name );
    bindRequest.setCredentials( credBytes );

    BindResponse bindResponse = bind( bindRequest );

    processResponse( bindResponse );
}
 
Example 10
Source File: DefaultCoreSession.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
private Value<?> convertToValue( String oid, Object value ) throws LdapException
{
    Value<?> val = null;

    AttributeType attributeType = directoryService.getSchemaManager().lookupAttributeTypeRegistry( oid );

    // make sure we add the request controls to operation
    if ( attributeType.getSyntax().isHumanReadable() )
    {
        if ( value instanceof String )
        {
            val = new StringValue( attributeType, ( String ) value );
        }
        else if ( value instanceof byte[] )
        {
            val = new StringValue( attributeType, Strings.utf8ToString( ( byte[] ) value ) );
        }
        else
        {
            throw new LdapException( I18n.err( I18n.ERR_309, oid ) );
        }
    }
    else
    {
        if ( value instanceof String )
        {
            val = new BinaryValue( attributeType, Strings.getBytesUtf8( ( String ) value ) );
        }
        else if ( value instanceof byte[] )
        {
            val = new BinaryValue( attributeType, ( byte[] ) value );
        }
        else
        {
            throw new LdapException( I18n.err( I18n.ERR_309, oid ) );
        }
    }

    return val;
}
 
Example 11
Source File: StoredProcedureRequestImpl.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a new stored procedure request.
 *
 * @param messageId the message id
 * @param procedure the procedure
 * @param language the language
 */
public StoredProcedureRequestImpl( int messageId, String procedure, String language )
{
    super( messageId );
    this.setRequestName( EXTENSION_OID );
    this.language = language;
    this.procedure = Strings.getBytesUtf8( procedure );
}
 
Example 12
Source File: SearchResultReferenceTest.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * Test the decoding of a SearchResultReference
 */
@Test
public void testDecodeSearchResultReferenceSuccess() throws DecoderException, EncoderException
{
    ByteBuffer stream = ByteBuffer.allocate( 0x3d8 );

    String[] ldapUrls = new String[]
        {
            "ldap:///", "ldap://directory.apache.org:80/", "ldap://d-a.org:80/", "ldap://1.2.3.4/",
            "ldap://1.2.3.4:80/", "ldap://1.1.1.100000.a/", "ldap://directory.apache.org:389/dc=example,dc=org/",
            "ldap://directory.apache.org:389/dc=example", "ldap://directory.apache.org:389/dc=example%202,dc=org",
            "ldap://directory.apache.org:389/dc=example,dc=org?ou",
            "ldap://directory.apache.org:389/dc=example,dc=org?ou,objectclass,dc",
            "ldap://directory.apache.org:389/dc=example,dc=org?ou,dc,ou",
            "ldap:///o=University%20of%20Michigan,c=US",
            "ldap://ldap.itd.umich.edu/o=University%20of%20Michigan,c=US",
            "ldap://ldap.itd.umich.edu/o=University%20of%20Michigan,c=US?postalAddress",
            "ldap://host.com:6666/o=University%20of%20Michigan,c=US??sub?(cn=Babs%20Jensen)",
            "ldap://ldap.itd.umich.edu/c=GB?objectClass?one", "ldap://ldap.question.com/o=Question%3f,c=US?mail",
            "ldap://ldap.netscape.com/o=Babsco,c=US???(int=%5c00%5c00%5c00%5c04)",
            "ldap:///??sub??bindname=cn=Manager%2co=Foo", "ldap:///??sub??!bindname=cn=Manager%2co=Foo"
        };

    stream.put( new byte[]
        {
            0x30, ( byte ) 0x82, 0x03, ( byte ) 0xd4,   // LDAPMessage SEQUENCE {
              0x02, 0x01, 0x01,                         // messageID MessageID
              0x73, ( byte ) 0x82, 0x03, ( byte ) 0xcd, // CHOICE { ...,
                                                        // searchResEntry
                                                        // SearchResultEntry,
                                                        // ...
                                                        // SearchResultReference ::= [APPLICATION 19] SEQUENCE OF LDAPURL
    } );

    for ( int i = 0; i < ldapUrls.length; i++ )
    {
        stream.put( ( byte ) 0x04 );
        stream.put( ( byte ) Strings.getBytesUtf8( ldapUrls[i] ).length );

        byte[] bytes = Strings.getBytesUtf8( ldapUrls[i] );

        for ( int j = 0; j < bytes.length; j++ )
        {
            stream.put( bytes[j] );
        }
    }

    stream.flip();

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

    Asn1Decoder.decode( stream, ldapMessageContainer );

    SearchResultReference searchResultReference = ldapMessageContainer.getMessage();

    assertEquals( 1, searchResultReference.getMessageId() );

    Set<String> ldapUrlsSet = new HashSet<String>();

    for ( int i = 0; i < ldapUrls.length; i++ )
    {
        ldapUrlsSet.add( ldapUrls[i] );
    }

    Referral referral = searchResultReference.getReferral();

    assertNotNull( referral );

    for ( String ldapUrl : referral.getLdapUrls() )
    {
        if ( ldapUrlsSet.contains( ldapUrl ) )
        {
            ldapUrlsSet.remove( ldapUrl );
        }
        else
        {
            fail( ldapUrl.toString() + " is not present" );
        }
    }

    assertTrue( ldapUrlsSet.size() == 0 );

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

    LdapEncoder.encodeMessage( buffer, codec, searchResultReference );

    assertArrayEquals( stream.array(), buffer.getBytes().array() );
}
 
Example 13
Source File: PasswordUtil.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * encrypts the given credentials based on the algorithm name and optional salt
 *
 * @param credentials the credentials to be encrypted
 * @param algorithm the algorithm to be used for encrypting the credentials
 * @param salt value to be used as salt (optional)
 * @return the encrypted credentials
 */
private static byte[] encryptPassword( byte[] credentials, LdapSecurityConstants algorithm, byte[] salt )
{
    switch ( algorithm )
    {
        case HASH_METHOD_SHA:
        case HASH_METHOD_SSHA:
            return digest( LdapSecurityConstants.HASH_METHOD_SHA, credentials, salt );

        case HASH_METHOD_SHA256:
        case HASH_METHOD_SSHA256:
            return digest( LdapSecurityConstants.HASH_METHOD_SHA256, credentials, salt );

        case HASH_METHOD_SHA384:
        case HASH_METHOD_SSHA384:
            return digest( LdapSecurityConstants.HASH_METHOD_SHA384, credentials, salt );

        case HASH_METHOD_SHA512:
        case HASH_METHOD_SSHA512:
            return digest( LdapSecurityConstants.HASH_METHOD_SHA512, credentials, salt );

        case HASH_METHOD_MD5:
        case HASH_METHOD_SMD5:
            return digest( LdapSecurityConstants.HASH_METHOD_MD5, credentials, salt );

        case HASH_METHOD_CRYPT:
            String saltWithCrypted = Crypt.crypt( Strings.utf8ToString( credentials ), Strings
                .utf8ToString( salt ) );
            String crypted = saltWithCrypted.substring( 2 );
            return Strings.getBytesUtf8( crypted );

        case HASH_METHOD_CRYPT_MD5:
        case HASH_METHOD_CRYPT_SHA256:
        case HASH_METHOD_CRYPT_SHA512:
            String saltWithCrypted2 = Crypt.crypt( Strings.utf8ToString( credentials ),
                algorithm.getSubPrefix() + Strings.utf8ToString( salt ) );
            String crypted2 = saltWithCrypted2.substring( saltWithCrypted2.lastIndexOf( '$' ) + 1 );
            return Strings.getBytesUtf8( crypted2 );

        case HASH_METHOD_CRYPT_BCRYPT:
            String crypted3 = BCrypt.hashPw( Strings.utf8ToString( credentials ), Strings.utf8ToString( salt ) );
            return Strings.getBytesUtf8( crypted3.substring( crypted3.length() - 31 ) );
            
        case HASH_METHOD_PKCS5S2:
            return generatePbkdf2Hash( credentials, algorithm, salt );

        default:
            return credentials;
    }
}
 
Example 14
Source File: PasswordUtil.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * create a hashed password in a format that can be stored in the server.
 * If the specified algorithm requires a salt then a random salt of 8 byte size is used
 *  
 * @param credentials the plain text password
 * @param algorithm the hashing algorithm to be applied
 * @return the password after hashing with the given algorithm 
 */
public static byte[] createStoragePassword( byte[] credentials, LdapSecurityConstants algorithm )
{
    // check plain text password
    if ( algorithm == null )
    {
        return credentials;
    }

    byte[] salt;

    switch ( algorithm )
    {
        case HASH_METHOD_SSHA:
        case HASH_METHOD_SSHA256:
        case HASH_METHOD_SSHA384:
        case HASH_METHOD_SSHA512:
        case HASH_METHOD_SMD5:
            // we use 8 byte salt always except for "crypt" which needs 2 byte salt
            salt = new byte[8];
            new SecureRandom().nextBytes( salt );
            break;

        case HASH_METHOD_PKCS5S2:
            // we use 16 byte salt for PKCS5S2
            salt = new byte[16];
            new SecureRandom().nextBytes( salt );
            break;

        case HASH_METHOD_CRYPT:
            salt = generateCryptSalt( 2 );
            break;

        case HASH_METHOD_CRYPT_MD5:
        case HASH_METHOD_CRYPT_SHA256:
        case HASH_METHOD_CRYPT_SHA512:
            salt = generateCryptSalt( 8 );
            break;
            
        case HASH_METHOD_CRYPT_BCRYPT:
            salt = Strings.getBytesUtf8( BCrypt.genSalt() );
            break;

        default:
            salt = null;
    }

    byte[] hashedPassword = encryptPassword( credentials, algorithm, salt );
    StringBuilder sb = new StringBuilder();

    sb.append( '{' ).append( Strings.upperCase( algorithm.getPrefix() ) ).append( '}' );

    if ( algorithm == LdapSecurityConstants.HASH_METHOD_CRYPT
        || algorithm == LdapSecurityConstants.HASH_METHOD_CRYPT_BCRYPT )
    {
        sb.append( Strings.utf8ToString( salt ) );
        sb.append( Strings.utf8ToString( hashedPassword ) );
    }
    else if ( algorithm == LdapSecurityConstants.HASH_METHOD_CRYPT_MD5
        || algorithm == LdapSecurityConstants.HASH_METHOD_CRYPT_SHA256
        || algorithm == LdapSecurityConstants.HASH_METHOD_CRYPT_SHA512 )
    {
        sb.append( algorithm.getSubPrefix() );
        sb.append( Strings.utf8ToString( salt ) );
        sb.append( '$' );
        sb.append( Strings.utf8ToString( hashedPassword ) );
    }
    else if ( salt != null )
    {
        byte[] hashedPasswordWithSaltBytes = new byte[hashedPassword.length + salt.length];

        if ( algorithm == LdapSecurityConstants.HASH_METHOD_PKCS5S2 )
        {
            merge( hashedPasswordWithSaltBytes, salt, hashedPassword );
        }
        else
        {
            merge( hashedPasswordWithSaltBytes, hashedPassword, salt );
        }

        sb.append( String.valueOf( Base64.encode( hashedPasswordWithSaltBytes ) ) );
    }
    else
    {
        sb.append( String.valueOf( Base64.encode( hashedPassword ) ) );
    }

    return Strings.getBytesUtf8( sb.toString() );
}
 
Example 15
Source File: LdifReader.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * Parse an AttributeType/AttributeValue
 *
 * @param entry The entry where to store the value
 * @param line The line to parse
 * @param lowerLine The same line, lowercased
 * @throws LdapException If anything goes wrong
 */
public void parseAttributeValue( LdifEntry entry, String line, String lowerLine ) throws LdapException
{
    int colonIndex = line.indexOf( ':' );

    String attributeType = lowerLine.substring( 0, colonIndex );

    // We should *not* have a Dn twice
    if ( "dn".equals( attributeType ) )
    {
        LOG.error( I18n.err( I18n.ERR_13400_ENTRY_WITH_TWO_DNS, lineNumber ) );
        throw new LdapLdifException( I18n.err( I18n.ERR_13439_LDIF_ENTRY_WITH_TWO_DNS ) );
    }

    Object attributeValue = parseValue( attributeType, line, colonIndex );

    if ( schemaManager != null )
    {
        AttributeType at = schemaManager.getAttributeType( attributeType );

        if ( at != null )
        {
            if ( at.getSyntax().isHumanReadable() )
            {
                if ( attributeValue == null )
                {
                    attributeValue = "";
                }
                else if ( attributeValue instanceof byte[] )
                {
                    attributeValue = Strings.utf8ToString( ( byte[] ) attributeValue );
                }
            }
            else
            {
                if ( attributeValue instanceof String )
                {
                    attributeValue = Strings.getBytesUtf8( ( String ) attributeValue );
                }
            }
        }
    }

    // Update the entry
    try
    {
        entry.addAttribute( attributeType, attributeValue );
    }
    catch ( Exception e )
    {
        // The attribute does not exist already, create a fake one 
        if ( ( schemaManager != null ) && schemaManager.isRelaxed() )
        {
            AttributeType newAttributeType = new AttributeType( "1.3.6.1.4.1.18060.0.9999." + oidCounter++ );
            newAttributeType.setNames( attributeType );
            newAttributeType.setSyntax( schemaManager.getLdapSyntaxRegistry().get( SchemaConstants.DIRECTORY_STRING_SYNTAX ) );
            schemaManager.add( newAttributeType );
            entry.addAttribute( attributeType, attributeValue );
        }
    }
}
 
Example 16
Source File: Value.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * Serialize the Value into a buffer at the given position.
 * 
 * @param buffer The buffer which will contain the serialized StringValue
 * @param pos The position in the buffer for the serialized value
 * @return The new position in the buffer
 */
public int serialize( byte[] buffer, int pos )
{
    // Compute the length : the isHR flag first, the value and prepared value presence flags
    int length = 1;
    byte[] preparedBytes = null;

    if ( isHR )
    { 
        if ( upValue != null )
        {
            // The presence flag, the length and the value
            length += 1 + 4 + bytes.length;
        }

        if ( normValue != null )
        {
            // The presence flag, the length and the value
            preparedBytes = Strings.getBytesUtf8( normValue );
            length += 1 + 4 + preparedBytes.length;
        }
    }
    else
    {
        if ( bytes != null )
        {
            length = 1 + 1 + 4 + bytes.length;
        }
        else
        {
            length = 1 + 1;
        }
    }

    // Check that we will be able to store the data in the buffer
    if ( buffer.length - pos < length )
    {
        throw new ArrayIndexOutOfBoundsException();
    }

    if ( isHR )
    {
        buffer[pos++] = Serialize.TRUE;

        // Write the user provided value, if not null
        if ( bytes != null )
        {
            buffer[pos++] = Serialize.TRUE;
            pos = Serialize.serialize( bytes, buffer, pos );
        }
        else
        {
            buffer[pos++] = Serialize.FALSE;
        }

        // Write the prepared value, if not null
        if ( normValue != null )
        {
            buffer[pos++] = Serialize.TRUE;
            pos = Serialize.serialize( preparedBytes, buffer, pos );
        }
        else
        {
            buffer[pos++] = Serialize.FALSE;
        }
    }
    else
    {
        buffer[pos++] = Serialize.FALSE;

        if ( bytes != null )
        {
            buffer[pos++] = Serialize.TRUE;
            pos = Serialize.serialize( bytes, buffer, pos );
        }
        else
        {
            buffer[pos++] = Serialize.FALSE;
        }
    }

    return pos;
}
 
Example 17
Source File: Value.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a schema aware StringValue with an initial user provided String value.
 *
 * @param attributeType the schema type associated with this StringValue
 * @param upValue the value to wrap
 * @throws LdapInvalidAttributeValueException If the added value is invalid accordingly
 * to the schema
 */
public Value( AttributeType attributeType, String upValue ) throws LdapInvalidAttributeValueException
{
    init( attributeType );
    this.upValue = upValue;
    
    if ( upValue != null )
    {
        bytes = Strings.getBytesUtf8( upValue );
    }
    else
    {
        bytes = null;
    }
    
    try
    {
        computeNormValue();
    }
    catch ( LdapException le )
    {
        LOG.error( le.getMessage() );
        throw new IllegalArgumentException( I18n.err( I18n.ERR_13247_INVALID_VALUE_CANT_NORMALIZE, upValue ) );
    }
    
    if ( !attributeType.isRelaxed() )
    {
        // Check the value
        LdapSyntax syntax = attributeType.getSyntax();
        
        if ( ( syntax != null ) && ( syntax.getSyntaxChecker() != null ) ) 
        {
            if ( !attributeType.getSyntax().getSyntaxChecker().isValidSyntax( upValue ) )
            {
                throw new LdapInvalidAttributeValueException( ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, 
                    I18n.err( I18n.ERR_13246_INVALID_VALUE_PER_SYNTAX ) );
            }
        }
        else
        {
            // We should always have a SyntaxChecker
            throw new IllegalArgumentException( I18n.err( I18n.ERR_13219_NULL_SYNTAX_CHECKER, normValue ) );
        }
    }
    
    hashCode();
}
 
Example 18
Source File: SchemaAwareLdifReaderTest.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * Test lengths when multiple entries are present
 *
 * @throws Exception
 */
@Test
public void testLdifParserLengthAndOffset() throws Exception
{
    String ldif1 = "dn: cn=app1,ou=applications,ou=conf,dc=apache,dc=org\n" +
        "cn: app1\n" +
        "objectClass: top\n" +
        "objectClass: apApplication\n" +
        "displayName:   app1   \n" +
        "dependencies:\n" +
        "envVars:\n";

    String comment = "# This comment was copied. Delete an entry. The operation will attach the LDAPv3\n" +
        "# Tree Delete Control defined in [9]. The criticality\n" +
        "# field is \"true\" and the controlValue field is\n" +
        "# absent, as required by [9].\n";

    String version = "version:   1\n";

    String ldif =
        version +
            ldif1 +
            "\n" +
            comment +
            ldif1 + "\n";

    LdifReader reader = new LdifReader( schemaManager );

    List<LdifEntry> lstEntries = null;

    try
    {
        lstEntries = reader.parseLdif( ldif );
    }
    catch ( Exception ne )
    {
        fail();
    }
    finally
    {
        reader.close();
    }

    LdifEntry entry1 = lstEntries.get( 0 );

    assertEquals( version.length() + ldif1.length(), entry1.getLengthBeforeParsing() );

    LdifEntry entry2 = lstEntries.get( 1 );

    assertEquals( ldif1.length() + comment.length(), entry2.getLengthBeforeParsing() );

    byte[] data = Strings.getBytesUtf8( ldif );

    String ldif1Bytes = new String( data, ( int ) entry1.getOffset(), entry1.getLengthBeforeParsing(),
        StandardCharsets.UTF_8 );
    assertNotNull( reader.parseLdif( ldif1Bytes ).get( 0 ) );

    String ldif2Bytes = new String( data, ( int ) entry2.getOffset(), entry2.getLengthBeforeParsing(),
        StandardCharsets.UTF_8 );
    assertNotNull( reader.parseLdif( ldif2Bytes ).get( 0 ) );

    File file = File.createTempFile( "offsetTest", "ldif" );
    file.deleteOnExit();
    OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream( file ), Charset.defaultCharset() );
    writer.write( ldif );
    writer.close();

    RandomAccessFile raf = new RandomAccessFile( file, "r" );

    LdifReader ldifReader = new LdifReader( file );

    LdifEntry rafEntry1 = ldifReader.next();

    data = new byte[rafEntry1.getLengthBeforeParsing()];
    raf.read( data, ( int ) rafEntry1.getOffset(), data.length );

    reader = new LdifReader( schemaManager );
    LdifEntry reReadeRafEntry1 = reader.parseLdif( new String( data, Charset.defaultCharset() ) ).get( 0 );
    assertNotNull( reReadeRafEntry1 );
    assertEquals( rafEntry1.getOffset(), reReadeRafEntry1.getOffset() );
    assertEquals( rafEntry1.getLengthBeforeParsing(), reReadeRafEntry1.getLengthBeforeParsing() );
    reader.close();

    LdifEntry rafEntry2 = ldifReader.next();

    data = new byte[rafEntry2.getLengthBeforeParsing()];
    raf.readFully( data, 0, data.length );

    reader = new LdifReader( schemaManager );
    LdifEntry reReadeRafEntry2 = reader.parseLdif( new String( data, Charset.defaultCharset() ) ).get( 0 );
    assertNotNull( reReadeRafEntry2 );
    assertEquals( rafEntry2.getLengthBeforeParsing(), reReadeRafEntry2.getLengthBeforeParsing() );
    reader.close();
    ldifReader.close();
    raf.close();
}
 
Example 19
Source File: PresentFilter.java    From directory-ldap-api with Apache License 2.0 3 votes vote down vote up
/**
 * Compute the PresentFilter length 
 * <br>
 * PresentFilter :
 * <pre> 
 * 0x87 L1 present
 * 
 * Length(PresentFilter) = Length(0x87) + Length(super.computeLength()) +
 *      super.computeLength()
 * </pre>
 * 
 * @return The encoded length
 */
@Override
public int computeLength()
{
    attributeDescriptionBytes = Strings.getBytesUtf8( attributeDescription );
    return 1 + TLV.getNbBytes( attributeDescriptionBytes.length ) + attributeDescriptionBytes.length;
}
 
Example 20
Source File: StoredProcedureRequestImpl.java    From directory-ldap-api with Apache License 2.0 2 votes vote down vote up
/**
 * Store the procedure's name
 * 
 * @param procedure The procedure's name
 */
public void setProcedure( String procedure )
{
    this.procedure = Strings.getBytesUtf8( procedure );
}