001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one
003 *  or more contributor license agreements.  See the NOTICE file
004 *  distributed with this work for additional information
005 *  regarding copyright ownership.  The ASF licenses this file
006 *  to you under the Apache License, Version 2.0 (the
007 *  "License"); you may not use this file except in compliance
008 *  with the License.  You may obtain a copy of the License at
009 *  
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *  
012 *  Unless required by applicable law or agreed to in writing,
013 *  software distributed under the License is distributed on an
014 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *  KIND, either express or implied.  See the License for the
016 *  specific language governing permissions and limitations
017 *  under the License. 
018 *  
019 */
020package org.apache.directory.api.ldap.schemaloader;
021
022
023import org.apache.directory.api.i18n.I18n;
024import org.apache.directory.api.ldap.model.entry.Attribute;
025import org.apache.directory.api.ldap.model.entry.Value;
026import org.apache.directory.api.ldap.model.exception.LdapException;
027import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException;
028import org.apache.directory.api.ldap.model.message.ResultCodeEnum;
029
030
031/**
032 * A class loader that loads classes from an attribute within an entry.
033 * 
034 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
035 */
036public class AttributeClassLoader extends ClassLoader
037{
038
039    /** The attribute. */
040    private Attribute attribute;
041
042
043    /**
044     * Instantiates a new attribute class loader.
045     */
046    public AttributeClassLoader()
047    {
048        super( AttributeClassLoader.class.getClassLoader() );
049    }
050
051
052    /**
053     * Sets the attribute.
054     *
055     * @param attribute the new attribute
056     * @throws LdapException if the attribute is not binary.
057     */
058    public void setAttribute( Attribute attribute ) throws LdapException
059    {
060        if ( attribute.isHumanReadable() )
061        {
062            throw new LdapInvalidAttributeValueException( ResultCodeEnum.CONSTRAINT_VIOLATION,
063                I18n.err( I18n.ERR_10001 ) );
064        }
065
066        this.attribute = attribute;
067    }
068
069
070    /**
071     * {@inheritDoc}
072     */
073    public Class<?> findClass( String name ) throws ClassNotFoundException
074    {
075        byte[] classBytes = null;
076
077        Value<?> value = attribute.get();
078
079        if ( value.isHumanReadable() )
080        {
081            throw new ClassNotFoundException( I18n.err( I18n.ERR_10002 ) );
082        }
083
084        classBytes = value.getBytes();
085
086        return defineClass( name, classBytes, 0, classBytes.length );
087    }
088}