private void prepareSuite() {
    Class<?> benchmarkClass;
    try {
      benchmarkClass = getClassByName(suiteClassName);
    } catch (ExceptionInInitializerError e) {
      throw new ExceptionFromUserCodeException(e.getCause());
    } catch (ClassNotFoundException ignored) {
      throw new NoSuchClassException(suiteClassName);
    }

    Object s;
    try {
      Constructor<?> constructor = benchmarkClass.getDeclaredConstructor();
      constructor.setAccessible(true);
      s = constructor.newInstance();
    } catch (InstantiationException ignore) {
      throw new AbstractBenchmarkException(benchmarkClass);
    } catch (NoSuchMethodException ignore) {
      throw new NoParameterlessConstructorException(benchmarkClass);
    } catch (IllegalAccessException impossible) {
      throw new AssertionError(impossible); // shouldn't happen since we setAccessible(true)
    } catch (InvocationTargetException e) {
      throw new ExceptionFromUserCodeException(e.getCause());
    }

    if (s instanceof Benchmark) {
      this.suite = (Benchmark) s;
    } else {
      throw new DoesntImplementBenchmarkException(benchmarkClass);
    }
  }
Exemple #2
0
  /**
   * Invoke the method on the instance, with any arguments specified, casting the result of invoking
   * the method to the expected return type.
   *
   * <p>
   *
   * <p>This method wraps {@link Method#invoke(Object, Object...)}, converting the checked
   * exceptions that {@link Method#invoke(Object, Object...)} specifies to runtime exceptions.
   *
   * <p>
   *
   * <p>If instructed, this method attempts to set the accessible flag of the method in a {@link
   * PrivilegedAction} before invoking the method.
   *
   * @param setAccessible flag indicating whether method should first be set as accessible
   * @param method the method to invoke
   * @param instance the instance to invoke the method
   * @param args the arguments to the method
   * @return the result of invoking the method, or null if the method's return type is void
   * @throws RuntimeException if this <code>Method</code> object enforces Java language access
   *     control and the underlying method is inaccessible or if the underlying method throws an
   *     exception or if the initialization provoked by this method fails.
   * @throws IllegalArgumentException if the method is an instance method and the specified <code>
   *     instance</code> argument is not an instance of the class or interface declaring the
   *     underlying method (or of a subclass or implementor thereof); if the number of actual and
   *     formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if,
   *     after possible unwrapping, a parameter value cannot be converted to the corresponding
   *     formal parameter type by a method invocation conversion.
   * @throws NullPointerException if the specified <code>instance</code> is null and the method is
   *     an instance method.
   * @throws ClassCastException if the result of invoking the method cannot be cast to the
   *     expectedReturnType
   * @throws ExceptionInInitializerError if the initialization provoked by this method fails.
   * @see Method#invoke(Object, Object...)
   */
  public static <T> T invokeMethod(
      boolean setAccessible,
      Method method,
      Class<T> expectedReturnType,
      Object instance,
      Object... args) {
    if (setAccessible && !method.isAccessible()) {
      setAccessible(method);
    }

    try {
      return expectedReturnType.cast(method.invoke(instance, args));
    } catch (IllegalAccessException ex) {
      throw new RuntimeException(buildInvokeMethodErrorMessage(method, instance, args), ex);
    } catch (IllegalArgumentException ex) {
      throw new IllegalArgumentException(buildInvokeMethodErrorMessage(method, instance, args), ex);
    } catch (InvocationTargetException ex) {
      throw new RuntimeException(
          buildInvokeMethodErrorMessage(method, instance, args), ex.getCause());
    } catch (NullPointerException ex) {
      NullPointerException ex2 =
          new NullPointerException(buildInvokeMethodErrorMessage(method, instance, args));
      ex2.initCause(ex.getCause());
      throw ex2;
    } catch (ExceptionInInitializerError e) {
      ExceptionInInitializerError e2 =
          new ExceptionInInitializerError(buildInvokeMethodErrorMessage(method, instance, args));
      e2.initCause(e.getCause());
      throw e2;
    }
  }
Exemple #3
0
 /**
  * Get the value of the field, on the specified instance, casting the value of the field to the
  * expected type.
  *
  * <p>
  *
  * <p>This method wraps {@link Field#get(Object)}, converting the checked exceptions that {@link
  * Field#get(Object)} specifies to runtime exceptions.
  *
  * @param <T> the type of the field's value
  * @param field the field to operate on
  * @param instance the instance from which to retrieve the value
  * @param expectedType the expected type of the field's value
  * @return the value of the field
  * @throws RuntimeException if the underlying field is inaccessible.
  * @throws IllegalArgumentException if the specified <code>instance</code> is not an instance of
  *     the class or interface declaring the underlying field (or a subclass or implementor
  *     thereof).
  * @throws NullPointerException if the specified <code>instance</code> is null and the field is an
  *     instance field.
  * @throws ExceptionInInitializerError if the initialization provoked by this method fails.
  */
 public static <T> T getFieldValue(Field field, Object instance, Class<T> expectedType) {
   try {
     return Reflections.cast(field.get(instance));
   } catch (IllegalAccessException e) {
     throw new RuntimeException(buildGetFieldValueErrorMessage(field, instance), e);
   } catch (NullPointerException ex) {
     NullPointerException ex2 =
         new NullPointerException(buildGetFieldValueErrorMessage(field, instance));
     ex2.initCause(ex.getCause());
     throw ex2;
   } catch (ExceptionInInitializerError e) {
     ExceptionInInitializerError e2 =
         new ExceptionInInitializerError(buildGetFieldValueErrorMessage(field, instance));
     e2.initCause(e.getCause());
     throw e2;
   }
 }
  @AdviseWith(adviceClasses = {PropsUtilAdvice.class})
  @Test
  public void testClassInitializationFailed() {
    System.setProperty(PropsKeys.INTRABAND_IMPL, "NoSuchClass");

    try {
      MPIHelperUtil.getMPI();

      Assert.fail();
    } catch (ExceptionInInitializerError eiie) {
      Throwable throwable = eiie.getCause();

      Assert.assertSame(RuntimeException.class, throwable.getClass());

      Assert.assertEquals("Unable to instantiate NoSuchClass", throwable.getMessage());
    } finally {
      System.clearProperty(PropsKeys.INTRABAND_IMPL);
    }
  }
Exemple #5
0
  /**
   * Sets the value of a field on the instance to the specified value.
   *
   * <p>
   *
   * <p>This method wraps {@link Field#set(Object, Object)}, converting the checked exceptions that
   * {@link Field#set(Object, Object)} specifies to runtime exceptions.
   *
   * <p>
   *
   * <p>If instructed, this method attempts to set the accessible flag of the method in a {@link
   * PrivilegedAction} before invoking the method.
   *
   * @param field the field on which to operate, or null if the field is static
   * @param instance the instance on which the field value should be set upon
   * @param value the value to set the field to
   * @throws RuntimeException if the underlying field is inaccessible.
   * @throws IllegalArgumentException if the specified <code>instance</code> is not an instance of
   *     the class or interface declaring the underlying field (or a subclass or implementor
   *     thereof), or if an unwrapping conversion fails.
   * @throws NullPointerException if the specified <code>instance</code> is null and the field is an
   *     instance field.
   * @throws ExceptionInInitializerError if the initialization provoked by this method fails.
   * @see Field#set(Object, Object)
   */
  public static void setFieldValue(
      boolean setAccessible, Field field, Object instance, Object value) {
    if (setAccessible && !field.isAccessible()) {
      setAccessible(field);
    }

    try {
      field.set(instance, value);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(buildSetFieldValueErrorMessage(field, instance, value), e);
    } catch (NullPointerException ex) {
      NullPointerException ex2 =
          new NullPointerException(buildSetFieldValueErrorMessage(field, instance, value));
      ex2.initCause(ex.getCause());
      throw ex2;
    } catch (ExceptionInInitializerError e) {
      ExceptionInInitializerError e2 =
          new ExceptionInInitializerError(buildSetFieldValueErrorMessage(field, instance, value));
      e2.initCause(e.getCause());
      throw e2;
    }
  }
  /**
   * This is used by standalone tools to force static initialization of DatabaseDescriptor, and fail
   * if configuration is bad.
   */
  public static void initDatabaseDescriptor() {
    try {
      DatabaseDescriptor.forceStaticInitialization();
    } catch (ExceptionInInitializerError e) {
      Throwable cause = e.getCause();
      boolean logStackTrace =
          !(cause instanceof ConfigurationException)
              || ((ConfigurationException) cause).logStackTrace;
      System.out.println(
          "Exception ("
              + cause.getClass().getName()
              + ") encountered during startup: "
              + cause.getMessage());

      if (logStackTrace) {
        cause.printStackTrace();
        System.exit(3);
      } else {
        System.err.println(cause.getMessage());
        System.exit(3);
      }
    }
  }
Exemple #7
0
 /**
  * {@linkplain #registerServiceProvider Registers} all factories given by the supplied iterator.
  *
  * @param factories The factories (or "service providers") to register.
  * @param category the category under which to register the providers.
  * @param message A buffer where to write the logging message.
  * @return {@code true} if at least one factory has been registered.
  */
 private <T> boolean register(
     final Iterator<T> factories, final Class<T> category, final StringBuilder message) {
   boolean newServices = false;
   final String lineSeparator = System.getProperty("line.separator", "\n");
   while (factories.hasNext()) {
     T factory;
     try {
       factory = factories.next();
     } catch (OutOfMemoryError error) {
       // Makes sure that we don't try to handle this error.
       throw error;
     } catch (NoClassDefFoundError error) {
       /*
        * A provider can't be registered because of some missing dependencies.
        * This occurs for example when trying to register the WarpTransform2D
        * math transform on a machine without JAI installation. Since the factory
        * may not be essential (this is the case of WarpTransform2D), just skip it.
        */
       loadingFailure(category, error, false);
       continue;
     } catch (ExceptionInInitializerError error) {
       /*
        * If an exception occured during class initialization, log the cause.
        * The ExceptionInInitializerError alone doesn't help enough.
        */
       final Throwable cause = error.getCause();
       if (cause != null) {
         loadingFailure(category, cause, true);
       }
       throw error;
     } catch (Error error) {
       if (!Classes.getShortClassName(error).equals("ServiceConfigurationError")) {
         // We want to handle sun.misc.ServiceConfigurationError only. Unfortunatly, we
         // need to rely on reflection because this error class is not a commited API.
         // TODO: Check if the error is catchable with JSE 6.
         throw error;
       }
       /*
        * Failed to register a factory for a reason probably related to the plugin
        * initialisation. It may be some factory-dependent missing resources.
        */
       loadingFailure(category, error, true);
       continue;
     }
     if (category.isAssignableFrom(factory.getClass())) {
       final Class<? extends T> factoryClass = factory.getClass().asSubclass(category);
       /*
        * If the factory implements more than one interface and an
        * instance were already registered, reuse the same instance
        * instead of duplicating it.
        */
       final T replacement = getServiceProviderByClass(factoryClass);
       if (replacement != null) {
         factory = replacement;
         // Need to register anyway, because the category may not be
         // the same.
       }
       if (registerServiceProvider(factory, category)) {
         /*
          * The factory is now registered. Add it to the message to
          * be logged. We will log all factories together in a single
          * log event because some registration (e.g.
          * MathTransformProviders) would be otherwise quite verbose.
          */
         message.append(lineSeparator);
         message.append("  ");
         message.append(factoryClass.getName());
         newServices = true;
       }
     }
   }
   return newServices;
 }
Exemple #8
0
 private void processConfigurationModules(final Class<?> cmb) {
   for (final Field f : cmb.getFields()) {
     if (ReflectionUtilities.isCoercable(ConfigurationModule.class, f.getType())) {
       final int mod = f.getModifiers();
       boolean ok = true;
       if (Modifier.isPrivate(mod)) {
         System.err.println("Found private ConfigurationModule " + f);
         ok = false;
       }
       if (!Modifier.isFinal(mod)) {
         System.err.println("Found non-final ConfigurationModule " + f);
         ok = false;
       }
       if (!Modifier.isStatic(f.getModifiers())) {
         System.err.println("Found non-static ConfigurationModule " + f);
         ok = false;
       }
       if (ok) {
         //          System.err.println("OK: " + f);
         try {
           f.setAccessible(true);
           final String fS = ReflectionUtilities.getFullName(f);
           if (!modules.containsKey(f)) {
             modules.put(f, (ConfigurationModule) (f.get(null)));
             try {
               modules.get(f).assertStaticClean();
             } catch (final ClassHierarchyException e) {
               System.err.println(fS + ": " + e.getMessage());
             }
             for (final Entry<String, String> e : modules.get(f).toStringPairs()) {
               // System.err.println("e: " + e.getKey() + "=" + e.getValue());
               try {
                 final Node n = ch.getNode(e.getKey());
                 if (!setters.contains(e.getKey(), fS)) {
                   setters.put(e.getKey(), fS);
                 }
                 if (n instanceof ClassNode) {
                   final ClassNode<?> cn = (ClassNode<?>) n;
                   if (!knownClasses.contains(cn)) {
                     knownClasses.add(cn);
                   }
                 }
               } catch (final NameResolutionException ex) {
                 //
               }
               try {
                 final String s = e.getValue();
                 final Node n = ch.getNode(s);
                 if (!usages.contains(ReflectionUtilities.getFullName(f), s)) {
                   //  System.err.println("Added usage: " + ReflectionUtilities.getFullName(f) +
                   // "=" + s);
                   usages.put(s, ReflectionUtilities.getFullName(f));
                 }
                 if (n instanceof ClassNode) {
                   final ClassNode<?> cn = (ClassNode<?>) n;
                   if (!knownClasses.contains(cn)) {
                     System.err.println("Added " + cn + " to known classes");
                     knownClasses.add(cn);
                   }
                 }
               } catch (final NameResolutionException ex) {
                 //
               }
             }
           }
         } catch (final ExceptionInInitializerError e) {
           System.err.println(
               "Field " + ReflectionUtilities.getFullName(f) + ": " + e.getCause().getMessage());
         } catch (final IllegalAccessException e) {
           throw new RuntimeException(e);
         }
       }
     }
   }
 }