001/*
002 * $Id: Contract.java 4028 2011-06-03 19:32:19Z kschaefe $
003 *
004 * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle,
005 * Santa Clara, California 95054, U.S.A. All rights reserved.
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 * 
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
015 * Lesser General Public License for more details.
016 * 
017 * You should have received a copy of the GNU Lesser General Public
018 * License along with this library; if not, write to the Free Software
019 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
020 */
021package org.jdesktop.swingx.util;
022
023
024/**
025 * Utility class for checking contracts.
026 * 
027 * @author Jeanette Winzenburg
028 */
029public class Contract {
030
031    private Contract() {
032        
033    }
034
035    /**
036     * Tests the input parameter against null. If the input is 
037     * an array, checks all of its elements as well. Returns the 
038     * unchanged parameter if not null, throws a NullPointerException
039     * otherwise. <p>
040     * 
041     * PENDING: type of exception? there are raging debates, some
042     *   favour an IllegalArgument? <p>
043     *   
044     * PENDING: the implementation uses a unchecked type cast to an array.
045     *   can we do better, how?
046     *     
047     * 
048     * @param <T> the type of the input parameter
049     * @param input the argument to check against null.
050     * @param message the text of the exception if the argument is null
051     * @return the input if not null
052     * @throws NullPointerException if input is null
053     */
054    @SuppressWarnings("unchecked")
055    public static <T> T asNotNull(T input, String message) {
056        if (input == null) 
057            throw new NullPointerException(message);
058        
059        if (input.getClass().isArray()) {
060            if (!input.getClass().getComponentType().isPrimitive()) {
061                T[] array = (T[]) input;
062                for (int i = 0; i < array.length; i++) {
063                    asNotNull(array[i], message);
064                }
065            }
066        }
067        
068        return input;
069    }
070}