Java Code Examples for org.apache.directory.api.ldap.model.exception.LdapException#getMessage()

The following examples show how to use org.apache.directory.api.ldap.model.exception.LdapException#getMessage() . 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: DefaultAttributeTypeRegistry.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public AttributeType unregister( String numericOid ) throws LdapException
{
    try
    {
        AttributeType removed = super.unregister( numericOid );

        removeMappingFor( removed );

        // Deleting an AT which might be used as a superior means we have
        // to recursively update the descendant map. We also have to remove
        // the at.oid -> descendant relation
        oidToDescendantSet.remove( numericOid );

        // Now recurse if needed
        unregisterDescendants( removed, removed.getSuperior() );

        return removed;
    }
    catch ( LdapException ne )
    {
        throw new LdapNoSuchAttributeException( ne.getMessage(), ne );
    }
}
 
Example 2
Source File: DefaultObjectClassRegistry.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public ObjectClass unregister( String numericOid ) throws LdapException
{
    try
    {
        ObjectClass removed = super.unregister( numericOid );

        // Deleting an ObjectClass which might be used as a superior means we have
        // to recursively update the descendant map. We also have to remove
        // the at.oid -> descendant relation
        oidToDescendants.remove( numericOid );

        // Now recurse if needed
        unregisterDescendants( removed, removed.getSuperiors() );

        return removed;
    }
    catch ( LdapException ne )
    {
        throw new LdapNoSuchAttributeException( ne.getMessage(), ne );
    }
}
 
Example 3
Source File: Dsmlv2Grammar.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void action( Dsmlv2Container container ) throws XmlPullParserException
{
    ModifyRequestDsml modifyRequest = ( ModifyRequestDsml )
        container.getBatchRequest().getCurrentRequest();

    XmlPullParser xpp = container.getParser();

    try
    {
        // We have to catch the type Attribute Value before going to the next Text node
        String typeValue = ParserUtils.getXsiTypeAttributeValue( xpp );

        // Getting the value
        String nextText = xpp.nextText();
        // We are testing if nextText equals "" since a modification can be "".

        try
        {
            if ( ParserUtils.isBase64BinaryValue( xpp, typeValue ) )
            {
                modifyRequest.addAttributeValue( Base64.decode( nextText.trim().toCharArray() ) );
            }
            else
            {
                modifyRequest.addAttributeValue( nextText.trim() );
            }
        }
        catch ( LdapException le )
        {
            throw new XmlPullParserException( le.getMessage(), xpp, le );
        }
    }
    catch ( IOException ioe )
    {
        throw new XmlPullParserException( I18n.err( I18n.ERR_03008_UNEXPECTED_ERROR, ioe.getMessage() ), xpp, ioe );
    }
}
 
Example 4
Source File: UserDAO.java    From directory-fortress-core with Apache License 2.0 5 votes vote down vote up
/**
 * @param user
 * @throws UpdateException
 */
void resetUserPassword( User user ) throws UpdateException
{
    LdapConnection ld = null;
    String userDn = getDn( user.getUserId(), user.getContextId() );

    try
    {
        List<Modification> mods = new ArrayList<Modification>();

        mods.add( new DefaultModification( ModificationOperation.REPLACE_ATTRIBUTE, SchemaConstants
            .USER_PASSWORD_AT, user.getPassword() ) );

        mods.add( new DefaultModification( ModificationOperation.REPLACE_ATTRIBUTE, OPENLDAP_PW_RESET, "TRUE" ) );

        ld = getAdminConnection();
        modify( ld, userDn, mods, user );
    }
    catch ( LdapException e )
    {
        String warning = "resetUserPassword userId [" + user.getUserId() + "] caught LDAPException=" + e
            .getMessage();
        throw new UpdateException( GlobalErrIds.USER_PW_RESET_FAILED, warning, e );
    }
    finally
    {
        closeAdminConnection( ld );
    }
}
 
Example 5
Source File: AcceleratorDAO.java    From directory-fortress-core with Apache License 2.0 5 votes vote down vote up
/**
 * Delete the stored session on impl accelerator server.
 * It uses the {@link RbacDeleteSessionRequest} and {@link RbacDeleteSessionResponse} accelerator APIs.
 *
 * @param session contains a valid sessionId captured from accelerator createSession method.
 * @throws SecurityException rethrows {@code LdapException} with {@code GlobalErrIds.ACEL_DELETE_SESSION_ERR}.
 */
void deleteSession( Session session ) throws SecurityException
{
    LdapConnection ld = null;

    try
    {
        ld = getAdminConnection();
        RbacDeleteSessionRequest deleteSessionRequest = new RbacDeleteSessionRequestImpl();
        deleteSessionRequest.setSessionId( session.getSessionId() );
        deleteSessionRequest.setUserIdentity( session.getUserId() );
        // Send the request
        RbacDeleteSessionResponse deleteSessionResponse = ( RbacDeleteSessionResponse ) ld.extended(
            deleteSessionRequest );
        LOG.debug( "deleteSession result: {}", deleteSessionResponse.getLdapResult().getResultCode() );
    }
    catch ( LdapException e )
    {
        String error = "deleteSession caught LDAPException=" + " msg=" + e
            .getMessage();
        throw new SecurityException( GlobalErrIds.ACEL_DELETE_SESSION_ERR, error, e );
    }
    finally
    {
        closeAdminConnection( ld );
    }
}
 
Example 6
Source File: DefaultSchemaManager.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance of DefaultSchemaManager with LDIF based SchemaLoader,
 * Strict schema validation
 */
public DefaultSchemaManager()
{
    this( STRICT, jarLdifSchemaLoader().getAllSchemas() );
    
    try
    {
        loadAllEnabled();
    }
    catch ( LdapException e )
    {
        LOG.error( I18n.err( I18n.ERR_16077_SCHEMA_MANAGER_CANT_BE_LOADED, e.getMessage() ) );
        throw new RuntimeException( e.getMessage() );
    }
}
 
Example 7
Source File: AcceleratorDAO.java    From directory-fortress-core with Apache License 2.0 5 votes vote down vote up
/**
 * Deactivate user role from impl session
 * This function follows the pattern from: {@link org.apache.directory.fortress.core.AccessMgr#dropActiveRole(org.apache.directory.fortress.core.model.Session, org.apache.directory.fortress.core.model.UserRole)}.
 * Success will result in impl session state to be modified inside server-side cache.
 * It uses the {@link RbacDropRoleRequest} and {@link RbacDropRoleResponse} accelerator APIs.
 *
 * @param session contains a valid sessionId captured from accelerator createSession method.
 * @param userRole both the {@link org.apache.directory.fortress.core.model.UserRole#userId} and {@link UserRole#name} fields must be set before invoking.
 * @throws SecurityException rethrows {@code LdapException} with {@code GlobalErrIds.ACEL_DROP_ROLE_ERR}.
 */
void dropActiveRole( Session session, UserRole userRole ) throws SecurityException
{
    LdapConnection ld = null;

    try
    {
        ld = getAdminConnection();
        RbacDropRoleRequest dropRoleRequest = new RbacDropRoleRequestImpl();
        dropRoleRequest.setSessionId( session.getSessionId() );
        dropRoleRequest.setRole( userRole.getName() );
        dropRoleRequest.setUserIdentity( userRole.getUserId() );
        // Send the request
        RbacDropRoleResponse rbacDropRoleResponse = ( RbacDropRoleResponse ) ld.extended(
            dropRoleRequest );
        LOG.debug( "dropActiveRole result: {}", rbacDropRoleResponse.getLdapResult().getResultCode() );

        if ( rbacDropRoleResponse.getLdapResult().getResultCode() != ResultCodeEnum.SUCCESS )
        {
            String info = "dropActiveRole Role [" + userRole.getName() + "] User ["
                + session.getUserId() + "], not previously activated.";
            throw new SecurityException( GlobalErrIds.URLE_NOT_ACTIVE, info );
        }
    }
    catch ( LdapException e )
    {
        String error = "dropActiveRole role name [" + userRole.getName() + "] caught LDAPException=" + " msg=" + e
            .getMessage();
        throw new SecurityException( GlobalErrIds.ACEL_DROP_ROLE_ERR, error, e );
    }
    finally
    {
        closeAdminConnection( ld );
    }
}
 
Example 8
Source File: ImmutableAttributeTypeRegistry.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String getOidByName( String name ) throws LdapException
{
    try
    {
        return immutableAttributeTypeRegistry.getOidByName( name );
    }
    catch ( LdapException le )
    {
        throw new LdapNoSuchAttributeException( le.getMessage(), le );
    }
}
 
Example 9
Source File: DefaultObjectClassRegistry.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void unregisterDescendants( ObjectClass attributeType, List<ObjectClass> ancestors )
    throws LdapException
{
    // add this attribute to descendant list of other attributes in superior chain
    if ( ( ancestors == null ) || ancestors.isEmpty() )
    {
        return;
    }

    for ( ObjectClass ancestor : ancestors )
    {
        // Get the ancestor's descendant, if any
        Set<ObjectClass> descendants = oidToDescendants.get( ancestor.getOid() );

        if ( descendants != null )
        {
            descendants.remove( attributeType );

            if ( descendants.isEmpty() )
            {
                oidToDescendants.remove( ancestor.getOid() );
            }
        }

        try
        {
            // And recurse until we reach the top of the hierarchy
            unregisterDescendants( attributeType, ancestor.getSuperiors() );
        }
        catch ( LdapException ne )
        {
            throw new LdapNoSuchAttributeException( ne.getMessage(), ne );
        }
    }
}
 
Example 10
Source File: DefaultObjectClassRegistry.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void registerDescendants( ObjectClass objectClass, List<ObjectClass> ancestors )
    throws LdapException
{
    // add this attribute to descendant list of other attributes in superior chain
    if ( ( ancestors == null ) || ancestors.isEmpty() )
    {
        return;
    }

    for ( ObjectClass ancestor : ancestors )
    {
        // Get the ancestor's descendant, if any
        Set<ObjectClass> descendants = oidToDescendants.get( ancestor.getOid() );

        // Initialize the descendant Set to store the descendants for the attributeType
        if ( descendants == null )
        {
            descendants = new HashSet<>( 1 );
            oidToDescendants.put( ancestor.getOid(), descendants );
        }

        // Add the current ObjectClass as a descendant
        descendants.add( objectClass );

        try
        {
            // And recurse until we reach the top of the hierarchy
            registerDescendants( objectClass, ancestor.getSuperiors() );
        }
        catch ( LdapException ne )
        {
            throw new LdapNoSuchAttributeException( ne.getMessage(), ne );
        }
    }
}
 
Example 11
Source File: DefaultObjectClassRegistry.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean hasDescendants( String ancestorId ) throws LdapException
{
    try
    {
        String oid = getOidByName( ancestorId );
        Set<ObjectClass> descendants = oidToDescendants.get( oid );
        return ( descendants != null ) && !descendants.isEmpty();
    }
    catch ( LdapException ne )
    {
        throw new LdapNoSuchAttributeException( ne.getMessage(), ne );
    }
}
 
Example 12
Source File: LdifReader.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * A method which parses a ldif string and returns a list of entries.
 *
 * @param ldif The ldif string
 * @return A list of entries, or an empty List
 * @throws LdapLdifException If something went wrong
 */
public List<LdifEntry> parseLdif( String ldif ) throws LdapLdifException
{
    if ( LOG.isDebugEnabled() )
    {
        LOG.debug( I18n.msg( I18n.MSG_13407_STARTS_PARSING_LDIF ) );
    }

    if ( Strings.isEmpty( ldif ) )
    {
        return new ArrayList<>();
    }

    try ( BufferedReader bufferReader = new BufferedReader( new StringReader( ldif ) ) )
    {
        List<LdifEntry> entries = parseLdif( bufferReader );

        if ( LOG.isDebugEnabled() )
        {
            LOG.debug( I18n.msg( I18n.MSG_13403_PARSED_N_ENTRIES, Integer.valueOf( entries.size() ) ) );
        }

        return entries;
    }
    catch ( LdapLdifException ne )
    {
        LOG.error( I18n.err( I18n.ERR_13428_CANNOT_PARSE_LDIF, ne.getLocalizedMessage() ) );
        throw new LdapLdifException( I18n.err( I18n.ERR_13442_ERROR_PARSING_LDIF_BUFFER ), ne );
    }
    catch ( LdapException le )
    {
        throw new LdapLdifException( le.getMessage(), le );
    }
    catch ( IOException ioe )
    {
        throw new LdapLdifException( I18n.err( I18n.ERR_13450_CANNOT_CLOSE_FILE ), ioe );
    }
}
 
Example 13
Source File: AttributeUtils.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a BasicAttributes or a AttributesImpl to an Entry
 *
 * @param attributes the BasicAttributes or AttributesImpl instance to convert
 * @param dn The Dn which is needed by the Entry
 * @return An instance of a Entry object
 * 
 * @throws LdapException If we get an invalid attribute
 */
public static Entry toEntry( Attributes attributes, Dn dn ) throws LdapException
{
    if ( attributes instanceof BasicAttributes )
    {
        try
        {
            Entry entry = new DefaultEntry( dn );

            for ( NamingEnumeration<? extends javax.naming.directory.Attribute> attrs = attributes.getAll(); attrs
                .hasMoreElements(); )
            {
                javax.naming.directory.Attribute attr = attrs.nextElement();

                Attribute entryAttribute = toApiAttribute( attr );

                if ( entryAttribute != null )
                {
                    entry.put( entryAttribute );
                }
            }

            return entry;
        }
        catch ( LdapException ne )
        {
            throw new LdapInvalidAttributeTypeException( ne.getMessage(), ne );
        }
    }
    else
    {
        return null;
    }
}
 
Example 14
Source File: Dsmlv2ResponseGrammar.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void action( Dsmlv2Container container ) throws XmlPullParserException
{
    SearchResponse searchResponse = ( SearchResponse )
        container.getBatchResponse().getCurrentResponse().getDecorated();
    SearchResultEntryDsml searchResultEntry = searchResponse.getCurrentSearchResultEntry();

    XmlPullParser xpp = container.getParser();

    try
    {
        // We have to catch the type Attribute Value before going to the next Text node
        String typeValue = ParserUtils.getXsiTypeAttributeValue( xpp );

        // Getting the value
        String nextText = xpp.nextText();

        try
        {
            if ( ParserUtils.isBase64BinaryValue( xpp, typeValue ) )
            {
                searchResultEntry.addAttributeValue( Base64.decode( nextText.toCharArray() ) );
            }
            else
            {
                searchResultEntry.addAttributeValue( nextText );
            }
        }
        catch ( LdapException le )
        {
            throw new XmlPullParserException( le.getMessage(), xpp, le );
        }
    }
    catch ( IOException ioe )
    {
        throw new XmlPullParserException( I18n.err( I18n.ERR_03008_UNEXPECTED_ERROR, ioe.getMessage() ), xpp, ioe );
    }
}
 
Example 15
Source File: AcceleratorDAO.java    From directory-fortress-core with Apache License 2.0 4 votes vote down vote up
/**
 * Perform user impl authorization.  This function returns a Boolean value meaning whether the subject of a given session is
 * allowed or not to perform a given operation on a given object. The function is valid if and
 * only if the session is a valid Fortress session, the object is a member of the OBJS data set,
 * and the operation is a member of the OPS data set. The session's subject has the permission
 * to perform the operation on that object if and only if that permission is assigned to (at least)
 * one of the session's active roles. This implementation will verify the roles or userId correspond
 * to the subject's active roles are registered in the object's access control list.
 * It uses the {@link RbacCheckAccessRequest} and {@link RbacCheckAccessResponse} accelerator APIs.
 *
 * @param session This object must be instantiated by calling {@link #createSession} method before passing into the method.  No variables need to be set by client after returned from createSession.
 * @param perm  must contain the object, {@link org.apache.directory.fortress.core.model.Permission#objName}, and operation, {@link org.apache.directory.fortress.core.model.Permission#opName}, of permission User is trying to access.
 * @return True if user has access, false otherwise.
 * @throws SecurityException rethrows {@code LdapException} with {@code GlobalErrIds.ACEL_CHECK_ACCESS_ERR}.
 */
boolean checkAccess( Session session, Permission perm ) throws SecurityException
{
    boolean result = false;
    LdapConnection ld = null;

    try
    {
        ld = getAdminConnection();
        RbacCheckAccessRequest rbacCheckAccessRequest = new RbacCheckAccessRequestImpl();
        rbacCheckAccessRequest.setSessionId( session.getSessionId() );
        rbacCheckAccessRequest.setObject( perm.getObjName() );

        // objectId is optional
        if ( StringUtils.isNotEmpty( perm.getObjId() ) )
        {
            rbacCheckAccessRequest.setObjectId( perm.getObjId() );
        }

        rbacCheckAccessRequest.setOperation( perm.getOpName() );
        // Send the request
        RbacCheckAccessResponse rbacCheckAccessResponse = ( RbacCheckAccessResponse ) ld.extended(
            rbacCheckAccessRequest );
        LOG.debug( "checkAccess result: {}", rbacCheckAccessResponse.getLdapResult().getResultCode() );

        result = rbacCheckAccessResponse.getLdapResult().getResultCode() == ResultCodeEnum.SUCCESS;
    }
    catch ( LdapException e )
    {
        String error = "checkAccess perm obj [" + perm.getObjName() + "], operation [" + perm.getOpName()
            + "] caught LDAPException=" + " msg=" + e
                .getMessage();
        throw new SecurityException( GlobalErrIds.ACEL_CHECK_ACCESS_ERR, error, e );
    }
    finally
    {
        closeAdminConnection( ld );
    }

    return result;
}
 
Example 16
Source File: AcceleratorDAO.java    From directory-fortress-core with Apache License 2.0 4 votes vote down vote up
/**
 * SessionRoles returns a list of UserRole's activated for user on impl server.
 * It uses the {@link RbacSessionRolesRequest} and {@link RbacSessionRolesResponse} accelerator APIs.
 *
 * todo: This method does not yet, but will soon populate temporal constraints associated with entities returned.
 *
 * @param session contains a valid sessionId captured from accelerator createSession method.
 * @return List of type UserRole.  May be null if user has no roles activated in session stored - server side.
 * @throws SecurityException rethrows {@code LdapException} with {@code GlobalErrIds.ACEL_SESSION_ROLES_ERR}.
 */
List<UserRole> sessionRoles( Session session ) throws SecurityException
{
    LdapConnection ld = null;
    List<UserRole> userRoleList = null;

    try
    {
        ld = getAdminConnection();
        RbacSessionRolesRequest sessionRolesRequest = new RbacSessionRolesRequestImpl();
        sessionRolesRequest.setSessionId( session.getSessionId() );
        sessionRolesRequest.setUserIdentity( session.getUserId() );
        // Send the request
        RbacSessionRolesResponse sessionRolesResponse = ( RbacSessionRolesResponse ) ld.extended(
            sessionRolesRequest );
        LOG.debug( "sessionRoles result: {}", sessionRolesResponse.getLdapResult().getResultCode().getResultCode() );

        if ( CollectionUtils.isNotEmpty( sessionRolesResponse.getRoles() ) )
        {
            userRoleList = new ArrayList<UserRole>();

            for ( String roleNm : sessionRolesResponse.getRoles() )
            {
                userRoleList.add( new UserRole( session.getUserId(), roleNm ) );
                // todo: add temporal constraints here
            }
        }
    }
    catch ( LdapException e )
    {
        String error = "sessionRoles caught LDAPException=" + " msg=" + e
            .getMessage();
        throw new SecurityException( GlobalErrIds.ACEL_SESSION_ROLES_ERR, error, e );
    }
    finally
    {
        closeAdminConnection( ld );
    }

    return userRoleList;
}
 
Example 17
Source File: AcceleratorDAO.java    From directory-fortress-core with Apache License 2.0 4 votes vote down vote up
/**
 * Activate user role into impl session
 * This function follows the pattern from: {@link org.apache.directory.fortress.core.AccessMgr#addActiveRole(org.apache.directory.fortress.core.model.Session, org.apache.directory.fortress.core.model.UserRole)}.
 * Success will result in impl session state to be modified inside server-side cache.
 * It uses the {@link RbacAddRoleRequest} and {@link RbacAddRoleResponse} accelerator APIs.
 *
 * @param session contains a valid sessionId captured from accelerator createSession method.
 * @param userRole both the {@link org.apache.directory.fortress.core.model.UserRole#userId} and {@link UserRole#name} fields must be set before invoking.
 * @throws SecurityException rethrows {@code LdapException} with {@code GlobalErrIds.ACEL_ADD_ROLE_ERR}.
 */
void addActiveRole( Session session, UserRole userRole ) throws SecurityException
{
    LdapConnection ld = null;

    try
    {
        ld = getAdminConnection();
        RbacAddRoleRequest addRoleRequest = new RbacAddRoleRequestImpl();
        addRoleRequest.setSessionId( session.getSessionId() );
        addRoleRequest.setRole( userRole.getName() );
        addRoleRequest.setUserIdentity( userRole.getUserId() );
        // Send the request
        RbacAddRoleResponse rbacAddRoleResponse = ( RbacAddRoleResponse ) ld.extended(
            addRoleRequest );
        LOG.debug( "addActiveRole result: {}", rbacAddRoleResponse.getLdapResult().getResultCode() );

        if ( rbacAddRoleResponse.getLdapResult().getResultCode() != ResultCodeEnum.SUCCESS )
        {
            String info;
            int rc;

            if ( rbacAddRoleResponse.getLdapResult().getResultCode() == ResultCodeEnum.ATTRIBUTE_OR_VALUE_EXISTS )
            {
                info = "addActiveRole Role [" + userRole.getName() + "] User ["
                    + session.getUserId() + "], already activated.";
                rc = GlobalErrIds.URLE_ALREADY_ACTIVE;
            }
            else
            {
                info = "addActiveRole Role [" + userRole.getName() + "] User ["
                    + session.getUserId() + "], not authorized for user.";
                rc = GlobalErrIds.URLE_ACTIVATE_FAILED;
            }

            throw new SecurityException( rc, info );
        }
    }
    catch ( LdapException e )
    {
        String error = "addActiveRole role name [" + userRole.getName() + "] caught LDAPException=" + " msg=" + e
            .getMessage();
        throw new SecurityException( GlobalErrIds.ACEL_ADD_ROLE_ERR, error, e );
    }
    finally
    {
        closeAdminConnection( ld );
    }
}
 
Example 18
Source File: Value.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * Deserialize a StringValue from a byte[], starting at a given position
 * 
 * @param buffer The buffer containing the StringValue
 * @param pos The position in the buffer
 * @return The new position
 * @throws IOException If the serialized value is not a StringValue
 * @throws LdapInvalidAttributeValueException If the value is invalid
 */
public int deserialize( byte[] buffer, int pos ) throws IOException, LdapInvalidAttributeValueException
{
    if ( ( pos < 0 ) || ( pos >= buffer.length ) )
    {
        throw new ArrayIndexOutOfBoundsException();
    }

    // Read the isHR flag
    isHR = Serialize.deserializeBoolean( buffer, pos );
    pos++;

    if ( isHR )
    {
        // Read the user provided value, if it's not null
        boolean hasValue = Serialize.deserializeBoolean( buffer, pos );
        pos++;

        if ( hasValue )
        {
            bytes = Serialize.deserializeBytes( buffer, pos );
            pos += 4 + bytes.length;

            upValue = Strings.utf8ToString( bytes );
        }

        // Read the prepared value, if not null
        boolean hasPreparedValue = Serialize.deserializeBoolean( buffer, pos );
        pos++;

        if ( hasPreparedValue )
        {
            byte[] preparedBytes = Serialize.deserializeBytes( buffer, pos );
            pos += 4 + preparedBytes.length;
            normValue = Strings.utf8ToString( preparedBytes );
        }
    }
    else
    {
        // Read the user provided value, if it's not null
        boolean hasBytes = Serialize.deserializeBoolean( buffer, pos );
        pos++;

        if ( hasBytes )
        {
            bytes = Serialize.deserializeBytes( buffer, pos );
            pos += 4 + bytes.length;
        }

    }
    
    if ( attributeType != null )
    {
        try
        {
            computeNormValue();
        }
        catch ( LdapException le )
        {
            throw new LdapInvalidAttributeValueException( ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, le.getMessage() );
        }
    }
    
    hashCode();

    return pos;
}
 
Example 19
Source File: Dsmlv2Grammar.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void action( Dsmlv2Container container ) throws XmlPullParserException
{
    AddRequestDsml addRequest = ( AddRequestDsml )
        container.getBatchRequest().getCurrentRequest();

    XmlPullParser xpp = container.getParser();

    try
    {
        // We have to catch the type Attribute Value before going to the next Text node
        String typeValue = ParserUtils.getXsiTypeAttributeValue( xpp );

        // Getting the value
        String nextText = xpp.nextText();

        if ( !Strings.isEmpty( nextText ) )
        {
            try
            {
                if ( ParserUtils.isBase64BinaryValue( xpp, typeValue ) )
                {
                    addRequest.addAttributeValue( Base64.decode( nextText.trim().toCharArray() ) );
                }
                else
                {
                    addRequest.addAttributeValue( nextText.trim() );
                }
            }
            catch ( LdapException le )
            {
                throw new XmlPullParserException( le.getMessage(), xpp, le );
            }
        }
    }
    catch ( IOException ioe )
    {
        throw new XmlPullParserException( I18n.err( I18n.ERR_03008_UNEXPECTED_ERROR, ioe.getMessage() ), xpp, ioe );
    }
}
 
Example 20
Source File: AcceleratorDAO.java    From directory-fortress-core with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticate user and return sessionId inside {@link org.apache.directory.fortress.core.model.Session#sessionId}.
 * This function follows the pattern from: {@link org.apache.directory.fortress.core.AccessMgr#createSession(org.apache.directory.fortress.core.model.User, boolean)}
 * Success will result in impl session state, i.e. {@link org.apache.directory.fortress.core.model.Session}, to be stored on server-side.
 * Result may be stored inside RBAC server-side audit record and retrieved with {@link org.apache.directory.fortress.core.AuditMgr#searchBinds(org.apache.directory.fortress.core.model.UserAudit)}
 *
 * It uses the {@link RbacCreateSessionRequest} and {@link RbacCreateSessionResponse} accelerator APIs.
 *
 *
 * @param user
 * @return session contains a valid sessionId captured from accelerator createSession method.
 *
 * @throws SecurityException rethrows {@code LdapException} with {@code GlobalErrIds.ACEL_CREATE_SESSION_ERR}.
 *
 */
Session createSession( User user ) throws SecurityException
{
    Session session = null;
    LdapConnection ld = null;

    try
    {
        ld = getAdminConnection();
        ld.setTimeOut( 0 );
        // Create a new RBAC session
        RbacCreateSessionRequest rbacCreateSessionRequest = new RbacCreateSessionRequestImpl();
        //rbacCreateSessionRequest.setTenantId( "jts" );
        rbacCreateSessionRequest.setTenantId( user.getContextId() );
        rbacCreateSessionRequest.setUserIdentity( user.getUserId() );
        rbacCreateSessionRequest.setPassword( new String( user.getPassword() ) );

        if ( CollectionUtils.isNotEmpty( user.getRoles() ) )
        {
            for ( UserRole userRole : user.getRoles() )
            {
                rbacCreateSessionRequest.addRole( userRole.getName() );
            }
        }

        // Send the request
        RbacCreateSessionResponse rbacCreateSessionResponse = ( RbacCreateSessionResponse ) ld.extended(
            rbacCreateSessionRequest );
        LOG.debug( "createSession userId: {}, sessionId: {}, resultCode: {}",
            user.getUserId(), rbacCreateSessionResponse.getSessionId(),
            rbacCreateSessionResponse.getLdapResult().getResultCode() );
        session = new Session( user, rbacCreateSessionResponse.getSessionId() );

        if ( rbacCreateSessionResponse.getLdapResult().getResultCode() == ResultCodeEnum.SUCCESS )
        {
            session.setAuthenticated( true );
        }
        else
        {
            session.setAuthenticated( false );
            String info = "createSession UserId [" + user.getUserId() + "] failed: "
                + rbacCreateSessionResponse.getLdapResult() + " , resultCode: "
                + rbacCreateSessionResponse.getLdapResult().getResultCode().getResultCode();
            throw new SecurityException( GlobalErrIds.USER_PW_INVLD, info );
        }
    }
    catch ( LdapException e )
    {
        String error = "createSession userId [" + user.getUserId() + "] caught LDAPException=" + " msg=" + e
            .getMessage();
        throw new SecurityException( GlobalErrIds.ACEL_CREATE_SESSION_ERR, error, e );
    }
    finally
    {
        closeAdminConnection( ld );
    }

    return session;
}