Java Code Examples for org.apache.directory.server.i18n.I18n#err()

The following examples show how to use org.apache.directory.server.i18n.I18n#err() . 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: ExceptionInterceptor.java    From MyVirtualDirectory with Apache License 2.0 6 votes vote down vote up
/**
 * Checks to make sure the entry being deleted exists, and has no children, otherwise throws the appropriate
 * LdapException.
 */
public void delete( DeleteOperationContext deleteContext ) throws LdapException
{
    Dn dn = deleteContext.getDn();

    if ( dn.equals( subschemSubentryDn ) )
    {
        throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, I18n.err( I18n.ERR_253,
            subschemSubentryDn ) );
    }

    next( deleteContext );

    // Update the alias cache
    synchronized ( notAliasCache )
    {
        if ( notAliasCache.containsKey( dn.getNormName() ) )
        {
            notAliasCache.remove( dn.getNormName() );
        }
    }
}
 
Example 3
Source File: SchemaInterceptor.java    From MyVirtualDirectory with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean compare( CompareOperationContext compareContext ) throws LdapException
{
    if ( IS_DEBUG )
    {
        LOG.debug( "Operation Context: {}", compareContext );
    }

    // Check that the requested AT exists
    // complain if we do not recognize the attribute being compared
    if ( !schemaManager.getAttributeTypeRegistry().contains( compareContext.getOid() ) )
    {
        throw new LdapInvalidAttributeTypeException( I18n.err( I18n.ERR_266, compareContext.getOid() ) );
    }

    boolean result = next( compareContext );

    return result;
}
 
Example 4
Source File: ExceptionInterceptor.java    From MyVirtualDirectory with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void move( MoveOperationContext moveContext ) throws LdapException
{
    Dn oriChildName = moveContext.getDn();

    if ( oriChildName.equals( subschemSubentryDn ) )
    {
        throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, I18n.err( I18n.ERR_258,
            subschemSubentryDn, subschemSubentryDn ) );
    }

    next( moveContext );

    // Remove the original entry from the NotAlias cache, if needed
    synchronized ( notAliasCache )
    {
        if ( notAliasCache.containsKey( oriChildName.getNormName() ) )
        {
            notAliasCache.remove( oriChildName.getNormName() );
        }
    }
}
 
Example 5
Source File: ExceptionInterceptor.java    From MyVirtualDirectory with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void moveAndRename( MoveAndRenameOperationContext moveAndRenameContext ) throws LdapException
{
    Dn oldDn = moveAndRenameContext.getDn();

    // Don't allow M&R in the SSSE
    if ( oldDn.equals( subschemSubentryDn ) )
    {
        throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, I18n.err( I18n.ERR_258,
            subschemSubentryDn, subschemSubentryDn ) );
    }

    // Remove the original entry from the NotAlias cache, if needed
    synchronized ( notAliasCache )
    {
        if ( notAliasCache.containsKey( oldDn.getNormName() ) )
        {
            notAliasCache.remove( oldDn.getNormName() );
        }
    }

    next( moveAndRenameContext );
}
 
Example 6
Source File: DefaultPartitionNexus.java    From MyVirtualDirectory with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Partition getPartition( Dn dn ) throws LdapException
{
    Partition parent = null;

    synchronized ( partitionLookupTree )
    {
        parent = partitionLookupTree.getElement( dn );
    }

    if ( parent == null )
    {
        throw new LdapNoSuchObjectException( I18n.err( I18n.ERR_268, dn ) );
    }
    else
    {
        return parent;
    }
}
 
Example 7
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 8
Source File: LdapTestEnvironment.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
/**
 * initialize the schema manager and add the schema partition to directory
 * service
 *
 * @throws Exception if the schema LDIF files are not found on the classpath
 */
protected void initSchemaPartition() throws Exception {
  InstanceLayout instanceLayout = service.getInstanceLayout();

  File schemaPartitionDirectory = new File(instanceLayout.getPartitionsDirectory(), "schema");

  // Extract the schema on disk (a brand new one) and load the registries
  if (schemaPartitionDirectory.exists()) {
    LOG.info("schema partition already exists, skipping schema extraction");
  } else {
    SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor(instanceLayout.getPartitionsDirectory());
    extractor.extractOrCopy();
  }

  SchemaLoader loader = new LdifSchemaLoader(schemaPartitionDirectory);
  SchemaManager schemaManager = new DefaultSchemaManager(loader);

  // We have to load the schema now, otherwise we won't be able
  // to initialize the Partitions, as we won't be able to parse
  // and normalize their suffix Dn
  schemaManager.loadAllEnabled();

  List<Throwable> errors = schemaManager.getErrors();

  if (!errors.isEmpty()) {
    throw new Exception(I18n.err(I18n.ERR_317, Exceptions.printErrors(errors)));
  }

  service.setSchemaManager(schemaManager);

  // Init the LdifPartition with schema
  LdifPartition schemaLdifPartition = new LdifPartition(schemaManager, service.getDnFactory());
  schemaLdifPartition.setPartitionPath(schemaPartitionDirectory.toURI());

  // The schema partition
  SchemaPartition schemaPartition = new SchemaPartition(schemaManager);
  schemaPartition.setWrappedPartition(schemaLdifPartition);
  service.setSchemaPartition(schemaPartition);
}
 
Example 9
Source File: SchemaInterceptor.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
/**
 * Checks to see the presence of all required attributes within an entry.
 */
private void assertRequiredAttributesPresent( Dn dn, Entry entry, Set<String> must ) throws LdapException
{
    for ( Attribute attribute : entry )
    {
        must.remove( attribute.getAttributeType().getOid() );
    }

    if ( must.size() != 0 )
    {
        // include AT names for better error reporting
        StringBuilder sb = new StringBuilder();
        sb.append( '[' );

        for ( String oid : must )
        {
            String name = schemaManager.getAttributeType( oid ).getName();
            sb.append( name )
                .append( '(' )
                .append( oid )
                .append( "), " );
        }

        int end = sb.length();
        sb.replace( end - 2, end, "" ); // remove the trailing ', '
        sb.append( ']' );

        throw new LdapSchemaViolationException( ResultCodeEnum.OBJECT_CLASS_VIOLATION, I18n.err( I18n.ERR_279,
            sb, dn.getName() ) );
    }
}
 
Example 10
Source File: DefaultOperationManager.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
/**
 * Eagerly populates fields of operation contexts so multiple Interceptors
 * in the processing pathway can reuse this value without performing a
 * redundant lookup operation.
 *
 * @param opContext the operation context to populate with cached fields
 */
private void eagerlyPopulateFields( OperationContext opContext ) throws LdapException
{
    // If the entry field is not set for ops other than add for example
    // then we set the entry but don't freak if we fail to do so since it
    // may not exist in the first place

    if ( opContext.getEntry() == null )
    {
        // We have to use the admin session here, otherwise we may have
        // trouble reading the entry due to insufficient access rights
        CoreSession adminSession = opContext.getSession().getDirectoryService().getAdminSession();

        LookupOperationContext lookupContext = new LookupOperationContext( adminSession, opContext.getDn(),
            SchemaConstants.ALL_ATTRIBUTES_ARRAY );
        Entry foundEntry = opContext.getSession().getDirectoryService().getPartitionNexus().lookup( lookupContext );

        if ( foundEntry != null )
        {
            opContext.setEntry( foundEntry );
        }
        else
        {
            // This is an error : we *must* have an entry if we want to be able to rename.
            LdapNoSuchObjectException ldnfe = new LdapNoSuchObjectException( I18n.err( I18n.ERR_256_NO_SUCH_OBJECT,
                opContext.getDn() ) );

            throw ldnfe;
        }
    }
}
 
Example 11
Source File: SchemaInterceptor.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
private Value<?> convert( AttributeType attributeType, Value<?> value ) throws LdapException
{
    if ( attributeType.getSyntax().isHumanReadable() )
    {
        if ( value instanceof BinaryValue )
        {
            try
            {
                return new StringValue( attributeType, new String( ( ( BinaryValue ) value ).getBytes(), "UTF-8" ) );
            }
            catch ( UnsupportedEncodingException uee )
            {
                String message = I18n.err( I18n.ERR_47 );
                LOG.error( message );
                throw new LdapException( message );
            }
        }
    }
    else
    {
        if ( value instanceof StringValue )
        {
            return new BinaryValue( attributeType, ( ( StringValue ) value ).getBytes() );
        }
    }

    return null;
}
 
Example 12
Source File: SchemaInterceptor.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
/**
 * Check a String attribute to see if there is some byte[] value in it.
 *
 * If this is the case, try to change it to a String value.
 */
private boolean checkHumanReadable( Attribute attribute ) throws LdapException
{
    boolean isModified = false;

    // Loop on each values
    for ( Value<?> value : attribute )
    {
        if ( value instanceof StringValue )
        {
            continue;
        }
        else if ( value instanceof BinaryValue )
        {
            // we have a byte[] value. It should be a String UTF-8 encoded
            // Let's transform it
            try
            {
                String valStr = new String( value.getBytes(), "UTF-8" );
                attribute.remove( value );
                attribute.add( valStr );
                isModified = true;
            }
            catch ( UnsupportedEncodingException uee )
            {
                throw new LdapException( I18n.err( I18n.ERR_281 ) );
            }
        }
        else
        {
            throw new LdapException( I18n.err( I18n.ERR_282 ) );
        }
    }

    return isModified;
}
 
Example 13
Source File: SchemaInterceptor.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
/**
 * Checks to see the presence of all required attributes within an entry.
 */
private void assertRequiredAttributesPresent( Dn dn, Entry entry, Set<String> must ) throws LdapException
{
    for ( Attribute attribute : entry )
    {
        must.remove( attribute.getAttributeType().getOid() );
    }

    if ( must.size() != 0 )
    {
        // include AT names for better error reporting
        StringBuilder sb = new StringBuilder();
        sb.append( '[' );

        for ( String oid : must )
        {
            String name = schemaManager.getAttributeType( oid ).getName();
            sb.append( name )
                .append( '(' )
                .append( oid )
                .append( "), " );
        }

        int end = sb.length();
        sb.replace( end - 2, end, "" ); // remove the trailing ', '
        sb.append( ']' );

        throw new LdapSchemaViolationException( ResultCodeEnum.OBJECT_CLASS_VIOLATION, I18n.err( I18n.ERR_279,
            sb, dn.getName() ) );
    }
}
 
Example 14
Source File: NormalizationInterceptor.java    From syncope with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean compare( CompareOperationContext compareContext ) throws LdapException
{
    Dn dn = compareContext.getDn();
    
    if ( !dn.isSchemaAware() )
    {
        compareContext.setDn( new Dn( schemaManager, dn ) );
    }

    // Get the attributeType from the OID
    try
    {
        AttributeType attributeType = schemaManager.lookupAttributeTypeRegistry( compareContext.getOid() );

        // Translate the value from binary to String if the AT is HR
        if ( attributeType.getSyntax().isHumanReadable() && ( !compareContext.getValue().isHumanReadable() ) )
        {
            compareContext.setValue( compareContext.getValue() );
        }

        compareContext.setAttributeType( attributeType );
    }
    catch ( LdapException le )
    {
        throw new LdapInvalidAttributeTypeException( I18n.err( I18n.ERR_266, compareContext.getOid() ) );
    }

    return next( compareContext );
}
 
Example 15
Source File: SchemaInterceptor.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
/**
 * Checks to see numbers of values of attributes conforms to the schema
 */
private void assertNumberOfAttributeValuesValid( Attribute attribute ) throws LdapInvalidAttributeValueException
{
    if ( attribute.size() > 1 && attribute.getAttributeType().isSingleValued() )
    {
        throw new LdapInvalidAttributeValueException( ResultCodeEnum.CONSTRAINT_VIOLATION, I18n.err( I18n.ERR_278,
            attribute.getUpId() ) );
    }
}
 
Example 16
Source File: DefaultPartitionNexus.java    From MyVirtualDirectory with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void setId( String id )
{
    throw new UnsupportedOperationException( I18n.err( I18n.ERR_264 ) );
}
 
Example 17
Source File: InMemoryDirectoryServiceFactory.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void init(String name) throws Exception {
    if ((directoryService != null) && directoryService.isStarted()) {
        return;
    }

    directoryService.setInstanceId(name);

    // instance layout
    InstanceLayout instanceLayout = new InstanceLayout(System.getProperty("java.io.tmpdir") + "/server-work-" + name);
    if (instanceLayout.getInstanceDirectory().exists()) {
        try {
            FileUtils.deleteDirectory(instanceLayout.getInstanceDirectory());
        } catch (IOException e) {
            LOG.warn("couldn't delete the instance directory before initializing the DirectoryService", e);
        }
    }
    directoryService.setInstanceLayout(instanceLayout);

    // EhCache in disabled-like-mode
    Configuration ehCacheConfig = new Configuration();
    CacheConfiguration defaultCache = new CacheConfiguration("ApacheDSTestCache", 1).eternal(false).timeToIdleSeconds(30)
            .timeToLiveSeconds(30).overflowToDisk(false);
    ehCacheConfig.addDefaultCache(defaultCache);
    cacheManager = new CacheManager(ehCacheConfig);
    CacheService cacheService = new CacheService(cacheManager);
    directoryService.setCacheService(cacheService);

    // Init the schema
    // SchemaLoader loader = new SingleLdifSchemaLoader();
    SchemaLoader loader = new JarLdifSchemaLoader();
    SchemaManager schemaManager = new DefaultSchemaManager(loader);
    schemaManager.loadAllEnabled();
    ComparatorRegistry comparatorRegistry = schemaManager.getComparatorRegistry();
    for (LdapComparator<?> comparator : comparatorRegistry) {
        if (comparator instanceof NormalizingComparator) {
            ((NormalizingComparator) comparator).setOnServer();
        }
    }
    directoryService.setSchemaManager(schemaManager);
    InMemorySchemaPartition inMemorySchemaPartition = new InMemorySchemaPartition(schemaManager);

    SchemaPartition schemaPartition = new SchemaPartition(schemaManager);
    schemaPartition.setWrappedPartition(inMemorySchemaPartition);
    directoryService.setSchemaPartition(schemaPartition);
    List<Throwable> errors = schemaManager.getErrors();
    if (errors.size() != 0) {
        throw new Exception(I18n.err(I18n.ERR_317, Exceptions.printErrors(errors)));
    }

    // Init system partition
    Partition systemPartition = partitionFactory.createPartition(directoryService.getSchemaManager(), "system",
            ServerDNConstants.SYSTEM_DN, 500, new File(directoryService.getInstanceLayout().getPartitionsDirectory(),
                    "system"));
    systemPartition.setSchemaManager(directoryService.getSchemaManager());
    partitionFactory.addIndex(systemPartition, SchemaConstants.OBJECT_CLASS_AT, 100);
    directoryService.setSystemPartition(systemPartition);

    directoryService.startup();
}
 
Example 18
Source File: Server.java    From MyVirtualDirectory with Apache License 2.0 4 votes vote down vote up
/**
 * initialize the schema manager and add the schema partition to diectory service
 *
 * @throws Exception if the schema LDIF files are not found on the classpath
 */
private void initSchemaPartition() throws Exception
{
    InstanceLayout instanceLayout = directoryService.getInstanceLayout();
    
    File schemaPartitionDirectory = new File( instanceLayout.getPartitionsDirectory(), "schema" );

    // Extract the schema on disk (a brand new one) and load the registries
    if ( schemaPartitionDirectory.exists() )
    {
        System.out.println( "schema partition already exists, skipping schema extraction" );
    }
    else
    {
        SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor( instanceLayout.getPartitionsDirectory() );
        extractor.extractOrCopy();
    }

    SchemaLoader loader = new LdifSchemaLoader( schemaPartitionDirectory );
    SchemaManager schemaManager = new DefaultSchemaManager( loader );

    // We have to load the schema now, otherwise we won't be able
    // to initialize the Partitions, as we won't be able to parse
    // and normalize their suffix Dn
    schemaManager.loadAllEnabled();

    List<Throwable> errors = schemaManager.getErrors();

    if ( errors.size() != 0 )
    {
        throw new Exception( I18n.err( I18n.ERR_317, Exceptions.printErrors( errors ) ) );
    }

    directoryService.setSchemaManager( schemaManager );
    
    // Init the LdifPartition with schema
    LdifPartition schemaLdifPartition = new LdifPartition( schemaManager );
    schemaLdifPartition.setPartitionPath( schemaPartitionDirectory.toURI() );

    // The schema partition
    SchemaPartition schemaPartition = new SchemaPartition( schemaManager );
    schemaPartition.setWrappedPartition( schemaLdifPartition );
    directoryService.setSchemaPartition( schemaPartition );
}
 
Example 19
Source File: AWSIAMAuthenticator.java    From aws-iam-ldap-bridge with Apache License 2.0 4 votes vote down vote up
@Override
public LdapPrincipal authenticate(BindOperationContext bindContext) throws Exception {
    if (!isAWSAccount(bindContext) || disabled) {
        LOG.debug("Skipping " + bindContext.getDn() + " - not an AWS account");
        if (delegatedAuth == null) {
            LOG.error("Delegated auth is null");
            return null;
        }
        return delegatedAuth.authenticate(bindContext);
    }

    LOG.debug("Authenticating " + bindContext.getDn());

    byte[] password = bindContext.getCredentials();

    LookupOperationContext lookupContext = new LookupOperationContext( getDirectoryService().getAdminSession(),
            bindContext.getDn(), SchemaConstants.ALL_USER_ATTRIBUTES, SchemaConstants.ALL_OPERATIONAL_ATTRIBUTES);

    Entry userEntry = getDirectoryService().getPartitionNexus().lookup( lookupContext );

    if (validator.verifyIAMPassword(userEntry, new String(password))) {
        LdapPrincipal principal = new LdapPrincipal( getDirectoryService().getSchemaManager(), bindContext.getDn(),
                AuthenticationLevel.SIMPLE, password);
        IoSession session = bindContext.getIoSession();

        if ( session != null )
        {
            SocketAddress clientAddress = session.getRemoteAddress();
            principal.setClientAddress( clientAddress );
            SocketAddress serverAddress = session.getServiceAddress();
            principal.setServerAddress( serverAddress );
        }

        bindContext.setEntry( new ClonedServerEntry( userEntry ) );
        return principal;
    } else {
        // Bad password ...
        String message = I18n.err( I18n.ERR_230, bindContext.getDn().getName() );
        LOG.info( message );
        throw new LdapAuthenticationException( message );
    }
}
 
Example 20
Source File: LdapServer.java    From MyVirtualDirectory with Apache License 2.0 4 votes vote down vote up
private void startNetwork( Transport transport, IoFilterChainBuilder chainBuilder ) throws Exception
{
    if ( transport.getBackLog() < 0 )
    {
        // Set the backlog to the default value when it's below 0
        transport.setBackLog( 50 );
    }

    chainBuilders.add( chainBuilder );

    try
    {
        SocketAcceptor acceptor = getSocketAcceptor( transport );

        // Now, configure the acceptor
        // Disable the disconnection of the clients on unbind
        acceptor.setCloseOnDeactivation( false );

        // No Nagle's algorithm
        acceptor.getSessionConfig().setTcpNoDelay( true );

        // Inject the chain
        acceptor.setFilterChainBuilder( chainBuilder );

        // Inject the protocol handler
        acceptor.setHandler( getHandler() );

        ( ( AbstractSocketSessionConfig ) acceptor.getSessionConfig() ).setReadBufferSize( 64 * 1024 );
        ( ( AbstractSocketSessionConfig ) acceptor.getSessionConfig() ).setSendBufferSize( 64 * 1024 );

        // Bind to the configured address
        acceptor.bind();

        // We are done !
        started = true;

        if ( LOG.isInfoEnabled() )
        {
            LOG.info( "Successful bind of an LDAP Service (" + transport.getPort() + ") is completed." );
        }
    }
    catch ( IOException e )
    {
        String msg = I18n.err( I18n.ERR_171, transport.getPort() );
        LdapConfigurationException lce = new LdapConfigurationException( msg );
        lce.setCause( e );
        LOG.error( msg, e );
        throw lce;
    }
}