All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.glassfish.gmbal.generic.Algorithms Maven / Gradle / Ivy

There is a newer version: 4.0.4
Show newest version
/* 
 *  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *  
 *  Copyright (c) 2007-2010 Oracle and/or its affiliates. All rights reserved.
 *  
 *  The contents of this file are subject to the terms of either the GNU
 *  General Public License Version 2 only ("GPL") or the Common Development
 *  and Distribution License("CDDL") (collectively, the "License").  You
 *  may not use this file except in compliance with the License.  You can
 *  obtain a copy of the License at
 *  https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
 *  or packager/legal/LICENSE.txt.  See the License for the specific
 *  language governing permissions and limitations under the License.
 *  
 *  When distributing the software, include this License Header Notice in each
 *  file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 *  
 *  GPL Classpath Exception:
 *  Oracle designates this particular file as subject to the "Classpath"
 *  exception as provided by Oracle in the GPL Version 2 section of the License
 *  file that accompanied this code.
 *  
 *  Modifications:
 *  If applicable, add the following below the License Header, with the fields
 *  enclosed by brackets [] replaced by your own identifying information:
 *  "Portions Copyright [year] [name of copyright owner]"
 *  
 *  Contributor(s):
 *  If you wish your version of this file to be governed by only the CDDL or
 *  only the GPL Version 2, indicate your decision by adding "[Contributor]
 *  elects to include this software in this distribution under the [CDDL or GPL
 *  Version 2] license."  If you don't indicate a single choice of license, a
 *  recipient has the option to distribute your version of this file under
 *  either the CDDL, the GPL Version 2 or to extend the choice of license to
 *  its licensees as provided above.  However, if you add GPL Version 2 code
 *  and therefore, elected the GPL Version 2 license, then the option applies
 *  only if the new code is made subject to such option by the copyright
 *  holder.
 */ 
package org.glassfish.gmbal.generic ;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.List ;
import java.util.Map ;
import java.util.ArrayList ;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.midi.SysexMessage;

public final class Algorithms {
    private Algorithms() {}
    
    public static  List list( T... arg ) {
        List result = new ArrayList() ;
        for (T obj : arg) {
            result.add( obj ) ;
        }
        return result ;
    }

    public static  Pair pair( S first, T second ) {
        return new Pair( first, second ) ;
    }
    
    public static  Map map( Pair... pairs ) {
        Map result = new HashMap() ;
        for (Pair pair : pairs ) {
            result.put( pair.first(), pair.second() ) ;
        }
        return result ;
    }
        
    public static  UnaryFunction mapToFunction( final Map map ) {
        return new UnaryFunction() {
            public R evaluate( A arg ) {
                return map.get( arg ) ;
            }
        } ;
    }

    public static  void map( final Collection arg, 
        final Collection result,
        final UnaryFunction func ) {

        for (A a : arg) {
            final R newArg = func.evaluate( a ) ;
            if (newArg != null) {
                result.add( newArg ) ;
            }
        }
    }

    public static  Map map( final Map arg,
        final UnaryFunction func ) {
        
        Map result = new HashMap() ;
        for (Map.Entry entry : arg.entrySet()) {
            result.put( entry.getKey(), 
                func.evaluate( entry.getValue())) ;
        }
        
        return result ;
    }
    
    public static  List map( final List arg, 
        final UnaryFunction func ) {

	final List result = new ArrayList() ;
	map( arg, result, func ) ;
	return result ;
    }

    public static  Predicate and( 
        final Predicate arg1,
        final Predicate arg2 ) {
    
        return new Predicate() {
            public boolean evaluate( A arg ) {
                return arg1.evaluate( arg ) && arg2.evaluate( arg ) ;
            }
        } ;
    }
    
    public static  Predicate or( 
        final Predicate arg1,
        final Predicate arg2 ) {

        return new Predicate() {
            public boolean evaluate( A arg ) {
                return arg1.evaluate( arg ) || arg2.evaluate( arg ) ;
            }
        } ;
    }
    
    public static  Predicate FALSE( Class cls
        ) {
        
        return new Predicate() {
            public boolean evaluate( T arg ) {
                return false ;
            }
        } ;
    } ;
    
    public static  Predicate TRUE( Class cls
        ) {
        
        return new Predicate() {
            public boolean evaluate( T arg ) {
                return true ;
            }
        } ;
    } ;
    
    public static  Predicate not( 
        final Predicate arg1 ) {
        
        return new Predicate() {
            public boolean evaluate( A arg ) {
                return !arg1.evaluate( arg ) ;
            } 
        } ;
    }
        
    public static  void filter( final List arg, final List result,
	final Predicate predicate ) {

	final UnaryFunction filter = new UnaryFunction() {
	    public A evaluate( A arg ) { 
		return predicate.evaluate( arg ) ? arg : null ; } } ;

	map( arg, result, filter ) ;
    }

    public static  List filter( List arg, Predicate predicate ) {
	List result = new ArrayList() ;
	filter( arg, result, predicate ) ;
	return result ;
    }

    public static  A find( List arg, Predicate predicate ) {
	for (A a : arg) {
	    if (predicate.evaluate( a )) {
		return a ;
	    }
	}

	return null ;
    }

    public static  R fold( List list, R initial, BinaryFunction func ) {
        R result = initial ;
        for (A elem : list) {
            result = func.evaluate( result, elem ) ;
        }
        return result ;
    }
    
    /** Flatten the results of applying map to list into a list of T.
     * 
     * @param  Type of elements of list.
     * @param  Type of elements of result.
     * @param list List of elements of type S.
     * @param map function mapping S to List.
     * @return List containg results of applying map to each element of list.
     */
    public static  List flatten( final List list,
        final UnaryFunction> map ) {        
        
        return fold( list, new ArrayList(), 
            new BinaryFunction,S,List>() {
                public List evaluate( List arg1, S arg2 ) {
                    arg1.addAll( map.evaluate( arg2 ) ) ;
                    return arg1 ;
                }
        } ) ;     
    }

    /** Return the first element of the list, or invoke handleEmptyList if
     * list is empty.
     * @param  The type of the list element.
     * @param list The list 
     * @param handleEmptyList A runnable to call when the list is empty. Typically 
     * throws an exception.
     * @return The first element of the list, if any.
     */
    public static  T getFirst( Collection list, Runnable handleEmptyList ) {
        for (T element : list) {
            return element ;
        }

        handleEmptyList.run();
        return null ;
    }

    /** Converts obj from an Array to a List, if obj is an array.
     * Otherwise just returns a List containing obj.
     */
    public static List convertToList( Object arg ) {
        List result = new ArrayList() ;
        if (arg != null) {
            Class cls = arg.getClass() ;
            if (cls.isArray()) {
                Class cclass = cls.getComponentType() ;
                if (cclass.equals( int.class )) {
                    for (int elem : (int[])arg) {
                        result.add( elem ) ;
                    }
                } else if (cclass.equals( byte.class )) {
                    for (byte elem : (byte[])arg) {
                        result.add( elem ) ;
                    }
                } else if (cclass.equals( boolean.class )) {
                    for (boolean elem : (boolean[])arg) {
                        result.add( elem ) ;
                    }
                } else if (cclass.equals( char.class )) {
                    for (char elem : (char[])arg) {
                        result.add( elem ) ;
                    }
                } else if (cclass.equals( short.class )) {
                    for (short elem : (short[])arg) {
                        result.add( elem ) ;
                    }
                } else if (cclass.equals( long.class )) {
                    for (long elem : (long[])arg) {
                        result.add( elem ) ;
                    }
                } else if (cclass.equals( float.class )) {
                    for (float elem : (float[])arg) {
                        result.add( elem ) ;
                    }
                } else if (cclass.equals( double.class )) {
                    for (double elem : (double[])arg) {
                        result.add( elem ) ;
                    }
                } else {
                    return Arrays.asList( (Object[])arg ) ;
                }
            } else {
                result.add( arg ) ;
                return result ;
            }
        }

        return result ;
    }

    /** Convert argument to String, either by toString, ot Arrays.toString.
     *
     * @param arg Object to convert.
     * @return arg converted to string.
     */
    public static String convertToString( Object arg ) {
        if (arg == null) {
            return "";
        }

        Class cls = arg.getClass() ;
        if (cls.isArray()) {
            Class cclass = cls.getComponentType() ;
            if (cclass.equals( int.class )) {
                return Arrays.toString((int[]) arg);
            }
            if (cclass.equals( byte.class )) {
                return Arrays.toString((byte[]) arg);
            }
            if (cclass.equals( boolean.class )) {
                return Arrays.toString((boolean[]) arg);
            }
            if (cclass.equals( char.class )) {
                return Arrays.toString((char[]) arg);
            }
            if (cclass.equals( short.class )) {
                return Arrays.toString((short[]) arg);
            }
            if (cclass.equals( long.class )) {
                return Arrays.toString((long[]) arg);
            }
            if (cclass.equals( float.class )) {
                return Arrays.toString((float[]) arg);
            }
            if (cclass.equals( double.class )) {
                return Arrays.toString((double[]) arg);
            }
            return Arrays.toString( (Object[])arg ) ;
        } else {
            return arg.toString() ;
        }
    }

    private static List getDeclaredMethods( final Class cls ) {
        SecurityManager sman = System.getSecurityManager() ;
        if (sman == null) {
            return Arrays.asList( cls.getDeclaredMethods() ) ;
        } else {
            return AccessController.doPrivileged(
                new PrivilegedAction>() {
                    public List run() {
                        return Arrays.asList( cls.getDeclaredMethods() ) ;
                    }
                }
            ) ;

        }
    }

    private static Set annotationMethods ;
    static {
        annotationMethods = new HashSet() ;
        for (Method m : getDeclaredMethods( Annotation.class )) {
            annotationMethods.add( m.getName()) ;
        }
    }

    /** Given an annotation, return a Map that maps each field (given by a 
     * method name) to its value in the annotation.  If the value is an 
     * annotation, that value is recursively converted into a Map in the
     * same way.
     * 
     * @param ann The annotation to examine.
     * @param convertArraysToLists true if annotation values of array type
     * should be converted to an appropriate list.  This is often MUCH more
     * useful, but some contexts require arrays.
     * @return A map of annotation fields to their values.
     */
    public static Map getAnnotationValues( Annotation ann,
        boolean convertArraysToLists ) {
        // We must ignore all of the methods defined in the java.lang.Annotation API.
        Map result = new HashMap() ;
        for (Method m : getDeclaredMethods( ann.getClass() )) {
            String name = m.getName() ;
            if (!annotationMethods.contains( name ) ) {
                Object value = null ;
                // Note: the following invoke should never fail
                try {
                    value = m.invoke(ann);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(Algorithms.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalArgumentException ex) {
                    Logger.getLogger(Algorithms.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InvocationTargetException ex) {
                    Logger.getLogger(Algorithms.class.getName()).log(Level.SEVERE, null, ex);
                }

                if (value != null) {
                    Class valueClass = value.getClass() ;
                    if (valueClass.isAnnotation()) {
                        value = getAnnotationValues( (Annotation)value,
                            convertArraysToLists ) ;
                    } else if (convertArraysToLists && valueClass.isArray()) {
                        value = convertToList(value) ;
                    }
                }

                result.put( name, value ) ;
            }
        }

        return result ;
    }

    public static interface Action {
        T run() throws Exception ;
    }

    private static  PrivilegedAction makePrivilegedAction(
        final Action act ) {

        return new PrivilegedAction() {
            public T run() {
                try {
                    return act.run() ;
                } catch (RuntimeException exc) {
                    throw exc ;
                } catch (Exception ex) {
                    throw new RuntimeException( ex ) ;
                }
            }
        } ;
    }

    public static  T doPrivileged( Action func ) {
        SecurityManager sman = System.getSecurityManager() ;
        try {
            if (sman == null) {
                return func.run() ;
            } else {
                return AccessController.doPrivileged( makePrivilegedAction(
                    func ) ) ;
            }
        } catch (RuntimeException rex) {
            throw rex ;
        } catch (Exception ex) {
            throw new RuntimeException( ex ) ;
        }
    }
}