001    /*
002     * Created on Jan 5, 2010
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005     * in compliance with the License. You may obtain a copy of the License at
006     *
007     * http://www.apache.org/licenses/LICENSE-2.0
008     *
009     * Unless required by applicable law or agreed to in writing, software distributed under the License
010     * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011     * or implied. See the License for the specific language governing permissions and limitations under
012     * the License.
013     *
014     * Copyright @2010 the original author or authors.
015     */
016    package org.fest.swing.util;
017    
018    import org.fest.reflect.core.Reflection;
019    import org.fest.util.VisibleForTesting;
020    
021    /**
022     * Understands installation of AWT exception handlers.
023     * <p>
024     * An exception handler is passed to the JVM using the system property "sun.awt.exception.handler" to override the
025     * default exception handling behavior of the event dispatch thread.
026     * </p>
027     * <p>
028     * This is a Sun-specific feature (or "bug".) See <a
029     * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4714232" target="_blank">bug 4714232</a>.
030     * </p>
031     *
032     * @author Alex Ruiz
033     */
034    public final class AWTExceptionHandlerInstaller {
035    
036      private static final SystemPropertyWriter WRITER = new SystemPropertyWriter();
037    
038      /**
039       * Installs the given exception handler type.
040       * @param exceptionHandlerType the type of exception handler to be installed in the current JVM.
041       * @throws IllegalArgumentException if the given type does not have a default constructor.
042       */
043      public static void installAWTExceptionHandler(Class<?> exceptionHandlerType) {
044        installAWTExceptionHandler(exceptionHandlerType, WRITER);
045      }
046    
047      @VisibleForTesting
048      static void installAWTExceptionHandler(Class<?> exceptionHandlerType, SystemPropertyWriter writer) {
049        try {
050          Reflection.constructor().in(exceptionHandlerType).info();
051        } catch (RuntimeException e) {
052          throw new IllegalArgumentException("The exception handler type should have a default constructor");
053        }
054        writer.updateSystemProperty("sun.awt.exception.handler", exceptionHandlerType.getName());
055      }
056    
057      private AWTExceptionHandlerInstaller() {}
058    }