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 *    https://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.schema.loader;
021
022
023import java.io.ByteArrayInputStream;
024import java.io.IOException;
025import java.util.HashMap;
026import java.util.Map;
027import java.util.jar.JarEntry;
028import java.util.jar.JarInputStream;
029
030import org.apache.directory.api.i18n.I18n;
031import org.apache.directory.api.ldap.model.entry.Attribute;
032import org.apache.directory.api.ldap.model.entry.Value;
033import org.apache.directory.api.ldap.model.exception.LdapException;
034import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException;
035import org.apache.directory.api.ldap.model.message.ResultCodeEnum;
036import java.io.ByteArrayOutputStream;
037import java.io.InputStream;
038
039
040/**
041 * A class loader that loads classes from an attribute within an entry.
042 * 
043 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
044 */
045public class AttributeClassLoader extends ClassLoader
046{
047    /** The attribute. */
048    private Attribute attribute;
049
050
051    /**
052     * Instantiates a new attribute class loader.
053     */
054    public AttributeClassLoader()
055    {
056        super( AttributeClassLoader.class.getClassLoader() );
057    }
058
059
060    /**
061     * Sets the attribute.
062     *
063     * @param attribute the new attribute
064     * @throws LdapException if the attribute is not binary.
065     */
066    public void setAttribute( Attribute attribute ) throws LdapException
067    {
068        if ( attribute.isHumanReadable() )
069        {
070            throw new LdapInvalidAttributeValueException( ResultCodeEnum.CONSTRAINT_VIOLATION,
071                I18n.err( I18n.ERR_16007_BINARY_REQUIRED ) );
072        }
073
074        this.attribute = attribute;
075    }
076    
077    
078    /**
079     * Read data from a jar, and write them into a byte[]
080     * 
081     * @param input The Stream we will load the Attribute from
082     * @return A byte[] containing the Attribute
083     * @throws IOException If the stream can't be read
084     */
085    private static byte[] getBytes( InputStream input ) throws IOException 
086    {
087        ByteArrayOutputStream result = new ByteArrayOutputStream();
088
089        byte[] buf = new byte[2048];
090        int bytesRead = input.read( buf );
091
092        while ( bytesRead != -1 ) 
093        {
094            result.write( buf, 0, bytesRead );
095            bytesRead = input.read( buf );
096        }
097      
098        result.flush();
099        result.close();
100        
101        return result.toByteArray();
102    }
103
104    
105    /**
106     * Load classes from a jar
107     *  
108     * @param jarBytes The jar bytes
109     * @return A map containing the read classes
110     * @throws IOException If the stream can't be read
111     */
112    private Map<String, Class<?>> loadClasses( byte[] jarBytes ) throws IOException 
113    {
114        Map<String, Class<?>> map = new HashMap<>();
115        
116        try ( JarInputStream jis = new JarInputStream( new ByteArrayInputStream( jarBytes ) ) ) 
117        {
118            JarEntry entry;
119            boolean isJar = false;
120            
121            while ( ( entry = jis.getNextJarEntry() ) != null ) 
122            {
123                String fileName = entry.getName();
124                isJar = true;
125                
126                // Just consider the files ending with .class
127                if ( fileName.endsWith( ".class" ) )
128                {
129                    String className = fileName.substring( 0,  fileName.length() - ".class".length() ).replace( '/', '.' );
130                    byte[] classBytes = getBytes( jis );
131                    
132                    Class<?> clazz = defineClass( className, classBytes, 0, classBytes.length );
133                    map.put( className, clazz );
134                }
135            }
136            
137            if ( !isJar )
138            {
139                return null;
140            }
141        }
142
143        return map;
144    }
145
146
147    /**
148     * {@inheritDoc}
149     */
150    @Override
151    public Class<?> findClass( String name ) throws ClassNotFoundException
152    {
153        byte[] classBytes;
154
155        Value value = attribute.get();
156
157        if ( value.isHumanReadable() )
158        {
159            throw new ClassNotFoundException( I18n.err( I18n.ERR_16008_AT_ACCESS_FAILURE ) );
160        }
161
162        classBytes = value.getBytes();
163
164        // May be we are dealing with a JAR ?
165        try 
166        {
167            Map<String, Class<?>> classes = loadClasses( classBytes );
168            
169            if ( classes == null )
170            {
171                // May be a simple class ?
172                return defineClass( name, classBytes, 0, classBytes.length );
173            }
174            
175            for ( Map.Entry<String, Class<?>> entry : classes.entrySet() )
176            {
177                if ( entry.getKey().contains( name ) )
178                {
179                    return entry.getValue();
180                }
181            }
182        }
183        catch ( IOException ioe )
184        {
185            // Ok, may be a pure class
186            return defineClass( name, classBytes, 0, classBytes.length );
187        }
188        
189        return null;
190    }
191}