Exemplo n.º 1
1
 private Object newInstance(Class type) {
   try {
     return type.newInstance();
   } catch (Exception ex) {
     try {
       // Try a private constructor.
       Constructor constructor = type.getDeclaredConstructor();
       constructor.setAccessible(true);
       return constructor.newInstance();
     } catch (SecurityException ignored) {
     } catch (NoSuchMethodException ignored) {
       if (type.isArray())
         throw new SerializationException(
             "Encountered JSON object when expected array of type: " + type.getName(), ex);
       else if (type.isMemberClass() && !Modifier.isStatic(type.getModifiers()))
         throw new SerializationException(
             "Class cannot be created (non-static member class): " + type.getName(), ex);
       else
         throw new SerializationException(
             "Class cannot be created (missing no-arg constructor): " + type.getName(), ex);
     } catch (Exception privateConstructorException) {
       ex = privateConstructorException;
     }
     throw new SerializationException(
         "Error constructing instance of class: " + type.getName(), ex);
   }
 }
 protected T createProviderInstanceFromType(
     final Class<? extends T> execClass, final String providerName)
     throws ProviderCreationException {
   boolean ctrfound = true;
   try {
     final Constructor<? extends T> method =
         execClass.getDeclaredConstructor(new Class[] {Framework.class});
     final T executor = method.newInstance(framework);
     return executor;
   } catch (NoSuchMethodException e) {
     ctrfound = false;
   } catch (Exception e) {
     throw new ProviderCreationException(
         "Unable to create provider instance: " + e.getMessage(), e, getName(), providerName);
   }
   try {
     final Constructor<? extends T> method = execClass.getDeclaredConstructor(new Class[0]);
     final T executor = method.newInstance();
     return executor;
   } catch (NoSuchMethodException e) {
     throw new ProviderCreationException(
         "No constructor found with signature (Framework) or (): " + e.getMessage(),
         e,
         getName(),
         providerName);
   } catch (Exception e) {
     throw new ProviderCreationException(
         "Unable to create provider instance: " + e.getMessage(), e, getName(), providerName);
   }
 }
Exemplo n.º 3
0
 /**
  * Get the dns resolver from class <code>resolverClassName</code> with optional <code>
  * hostRegionOverrides</code>.
  *
  * <p>It would try to load the class with the constructor with <code>hostRegionOverrides</code>.
  * If it fails, it would fall back to load the class with default empty constructor. The
  * interpretion of <code>hostRegionOverrides</code> is up to the implementation.
  *
  * @param resolverCls resolver class
  * @param hostRegionOverrides host region overrides
  * @return dns resolver
  */
 public static DNSToSwitchMapping getDNSResolver(
     Class<? extends DNSToSwitchMapping> resolverCls, String hostRegionOverrides) {
   // first try to construct the dns resolver with overrides
   Constructor<? extends DNSToSwitchMapping> constructor;
   Object[] parameters;
   try {
     constructor = resolverCls.getDeclaredConstructor(String.class);
     parameters = new Object[] {hostRegionOverrides};
   } catch (NoSuchMethodException nsme) {
     // no constructor with overrides
     try {
       constructor = resolverCls.getDeclaredConstructor();
       parameters = new Object[0];
     } catch (NoSuchMethodException nsme1) {
       throw new RuntimeException(
           "Unable to find constructor for dns resolver " + resolverCls, nsme1);
     }
   }
   constructor.setAccessible(true);
   try {
     return constructor.newInstance(parameters);
   } catch (InstantiationException ie) {
     throw new RuntimeException("Unable to instantiate dns resolver " + resolverCls, ie);
   } catch (IllegalAccessException iae) {
     throw new RuntimeException("Illegal access to dns resolver " + resolverCls, iae);
   } catch (InvocationTargetException ite) {
     throw new RuntimeException("Unable to construct dns resolver " + resolverCls, ite);
   }
 }
 private Constructor<?> getTypeExcludeFilterConstructor(Class<?> type)
     throws NoSuchMethodException {
   try {
     return type.getDeclaredConstructor(Class.class);
   } catch (Exception ex) {
     return type.getDeclaredConstructor();
   }
 }
Exemplo n.º 5
0
  private Task createTaskObject(
      Project project, Class<? extends Task> type, String name, boolean generateGetters) {
    if (!Task.class.isAssignableFrom(type)) {
      throw new GradleException(
          String.format(
              "Cannot create task of type '%s' as it does not implement the Task interface.",
              type.getSimpleName()));
    }

    Class<? extends Task> generatedType;
    if (generateGetters) {
      generatedType = generator.generate(type);
    } else {
      generatedType = type;
    }

    Constructor<? extends Task> constructor = null;
    Object[] params = null;
    try {
      constructor = generatedType.getDeclaredConstructor();
      params = new Object[0];
    } catch (NoSuchMethodException e) {
      // Ignore
    }
    try {
      constructor = generatedType.getDeclaredConstructor(Project.class, String.class);
      params = new Object[] {project, name};
    } catch (NoSuchMethodException e) {
      // Ignore
    }
    if (constructor == null) {
      throw new GradleException(
          String.format(
              "Cannot create task of type '%s' as it does not have an appropriate public constructor.",
              type.getSimpleName()));
    }

    AbstractTask.injectIntoNextInstance(project, name);
    try {
      return constructor.newInstance(params);
    } catch (InvocationTargetException e) {
      throw new GradleException(
          String.format("Could not create task of type '%s'.", type.getSimpleName()), e.getCause());
    } catch (Exception e) {
      throw new GradleException(
          String.format("Could not create task of type '%s'.", type.getSimpleName()), e);
    } finally {
      AbstractTask.injectIntoNextInstance(null, null);
    }
  }
 /**
  * Finds the conversion method.
  *
  * @param <T> the type of the converter
  * @param cls the class to find a method for, not null
  * @return the method to call, null means use {@code toString}
  * @throws RuntimeException if invalid
  */
 private <T> Constructor<T> findFromStringConstructor(Class<T> cls) {
   Constructor<T> con;
   try {
     con = cls.getDeclaredConstructor(String.class);
   } catch (NoSuchMethodException ex) {
     try {
       con = cls.getDeclaredConstructor(CharSequence.class);
     } catch (NoSuchMethodException ex2) {
       return null;
     }
   }
   FromString fromString = con.getAnnotation(FromString.class);
   return fromString != null ? con : null;
 }
  protected boolean hasValidProviderSignature(final Class clazz) {

    try {
      final Constructor method = clazz.getDeclaredConstructor(new Class[] {Framework.class});
      return null != method;
    } catch (NoSuchMethodException e) {
    }
    try {
      final Constructor method = clazz.getDeclaredConstructor(new Class[0]);
      return null != method;
    } catch (NoSuchMethodException e) {
    }
    return false;
  }
Exemplo n.º 8
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  private void registerEventHandlers_() {
    if (!Boolean.parseBoolean(
        Play.configuration.getProperty("morphia.autoRegisterEventHandler", "true"))) return;

    // -- register handlers from event handler class --
    List<Class> classes = Play.classloader.getAssignableClasses(IMorphiaEventHandler.class);
    for (Class c : classes) {
      IMorphiaEventHandler h = null;
      try {
        Constructor cnst = c.getDeclaredConstructor();
        cnst.setAccessible(true);
        h = (IMorphiaEventHandler) cnst.newInstance();
      } catch (Exception e) {
        Logger.error(e, "Cannot init IMorphiaEventHandler from class: %s", c.getName());
        continue;
      }
      Watch w = (Watch) c.getAnnotation(Watch.class);
      if (null != w) {
        Class[] ca = w.value();
        for (Class modelClass : ca) {
          registerModelEventHandlers_(modelClass, h);
        }
      }
    }

    // -- register handlers from model class --
    classes = Play.classloader.getAssignableClasses(Model.class);
    for (Class c : classes) {
      WatchBy wb = (WatchBy) c.getAnnotation(WatchBy.class);
      if (null == wb) continue;
      Class[] ca = wb.value();
      for (Class handler : ca) {
        if ((IMorphiaEventHandler.class.isAssignableFrom(handler))) {
          IMorphiaEventHandler h = null;
          try {
            Constructor cnst = handler.getDeclaredConstructor();
            cnst.setAccessible(true);
            h = (IMorphiaEventHandler) cnst.newInstance();
          } catch (Exception e) {
            Logger.error(e, "Cannot init IMorphiaEventHandler from class: %s", c.getName());
            continue;
          }
          registerModelEventHandlers_(c, h);
        }
      }
    }
  }
  /**
   * Retrieves a new HsqlSocketFactory whose class is determined by the implClass argument. The
   * basic contract here is that implementations constructed by this method should return true upon
   * calling isSecure() iff they actually create secure sockets. There is no way to guarantee this
   * directly here, so it is simply trusted that an implementation is secure if it returns true for
   * calls to isSecure();
   *
   * @return a new secure socket factory
   * @param implClass the fully qaulified name of the desired class to construct
   * @throws Exception if a new secure socket factory cannot be constructed
   */
  private static final HsqlSocketFactory newFactory(String implClass) throws Exception {

    Class clazz;
    Constructor ctor;
    Class[] ctorParm;
    Object[] ctorArg;
    Object factory;

    clazz = Class.forName(implClass);
    ctorParm = new Class[0];

    // protected constructor
    ctor = clazz.getDeclaredConstructor(ctorParm);
    ctorArg = new Object[0];

    try {
      factory = ctor.newInstance(ctorArg);
    } catch (InvocationTargetException e) {
      Throwable t = e.getTargetException();

      throw (t instanceof Exception) ? ((Exception) t) : new RuntimeException(t.toString());
    }

    return (HsqlSocketFactory) factory;
  }
Exemplo n.º 10
0
  protected void extractLZMA(String in, String out) throws Exception {
    File f = new File(in);
    if (!f.exists()) return;
    FileInputStream fileInputHandle = new FileInputStream(f);

    Class clazz = Class.forName("LZMA.LzmaInputStream");
    Constructor constructor = clazz.getDeclaredConstructor(new Class[] {InputStream.class});

    InputStream inputHandle = (InputStream) constructor.newInstance(new Object[] {fileInputHandle});

    OutputStream outputHandle = new FileOutputStream(out);

    byte[] buffer = new byte[16384];

    int ret = inputHandle.read(buffer);
    while (ret >= 1) {
      outputHandle.write(buffer, 0, ret);
      ret = inputHandle.read(buffer);
    }

    inputHandle.close();
    outputHandle.close();

    outputHandle = null;
    inputHandle = null;

    f.delete();
  }
 protected final JComponent buildPage(String className, PropertyValueModel subjectHolder)
     throws Exception {
   Class page = Class.forName(className);
   Constructor constructor = page.getDeclaredConstructor(new Class[] {PropertyValueModel.class});
   constructor.setAccessible(true);
   return (JComponent) constructor.newInstance(new Object[] {subjectHolder});
 }
  /**
   * Abrir archivos con la opción 1
   *
   * @param pathFile ruta al fichero que se abrirá
   * @return ModelViewer con el objeto "dibujado"
   */
  public ModelViewer abrirArchivosO2(final String pathFile) {
    //        String ext = getExtension(pathFile);
    //        ModelViewer model = new ModelViewer();
    //        if (ext.equals("igs")) {
    //
    //        } else {
    final Vector<ModelViewer> modelviewer = new Vector<ModelViewer>();
    Class Viewer = ModelViewer.class;
    try {
      modelviewer.add(
          (ModelViewer)
              Viewer.getDeclaredConstructor(
                      String.class, int.class, int.class, boolean.class, boolean.class)
                  .newInstance("ModelViewer.ini", 600, 600, true, true));
    } catch (Exception e) {
      System.err.print("Error: " + e);
    }
    new Thread(
            new Runnable() {
              public void run() {
                modelviewer.get(0).load(pathFile, null);
              }
            })
        .start();
    return modelviewer.get(0);
    //            Mesh m = mlSTP.load(pathFile);
    //            m.initialize();
    //            model.load(pathFile);
    //        } else if (ext.equals("ply")) {
    //            //Mesh m = mlPLY.load(pathFile);
    //            model.load(pathFile);
    //        }
    //        return model;

  }
  public static LogicSearchRule get(EntitySearchRule entityRule) {

    Class logicRuleClass = (Class) registered.get(entityRule.getClass());

    if (logicRuleClass != null) {

      try {

        Constructor constructor =
            logicRuleClass.getDeclaredConstructor(new Class[] {EntitySearchRule.class});

        return (LogicSearchRule) constructor.newInstance(new Object[] {entityRule});

      } catch (InstantiationException exception) {

        throw new RuntimeException(exception);

      } catch (IllegalAccessException exception) {

        throw new RuntimeException(exception);

      } catch (NoSuchMethodException exception) {

        throw new RuntimeException(exception);

      } catch (InvocationTargetException exception) {

        throw new RuntimeException(exception);
      }
    }

    throw new IllegalArgumentException("Can't find rule by entity rule " + entityRule);
  }
Exemplo n.º 14
0
  /**
   * Create a new IRCApplication.
   *
   * @param config the IRC configuration.
   * @param startupConfig the startup configuration.
   * @param source a container in wich the application will display. Maybe null. If null, a new
   *     Frame will be opened.
   */
  public IRCApplication(
      IRCConfiguration config, StartupConfiguration startupConfig, Container source) {
    super(config);
    _container = source;
    _start = startupConfig;
    _plugins = new Vector<Plugin>();
    _pluginsTable = new Hashtable<String, Plugin>();

    String gui = config.getS("gui");
    try {
      Class<?> cl = Class.forName("irc.gui." + gui + ".Interface");
      java.lang.reflect.Constructor<?> ctr =
          cl.getDeclaredConstructor(new Class[] {config.getClass()});
      _interface = (IRCInterface) ctr.newInstance(new Object[] {config});
    } catch (java.lang.reflect.InvocationTargetException iex) {
      iex.getTargetException().printStackTrace();
      throw new Error("Unable to load interface " + gui + " : " + iex.getTargetException());
    } catch (Throwable ex) {
      ex.printStackTrace();
      throw new Error("Unable to load interface " + gui + " : " + ex);
    }

    _servers = new Hashtable<Server, Server>();
    _defaultSource = new DefaultSource(_ircConfiguration);
    DefaultInterpretor defaultInter = new DefaultInterpretor(_ircConfiguration, _start, this, this);
    _defaultSource.setInterpretor(defaultInter);
  }
Exemplo n.º 15
0
 private <T> ObjectConstructor<T> newDefaultConstructor(Class<? super T> rawType) {
   try {
     final Constructor<? super T> constructor = rawType.getDeclaredConstructor(new Class[0]);
     if (!constructor.isAccessible()) {
       constructor.setAccessible(true);
     }
     new ObjectConstructor() {
       public T construct() {
         try {
           Object[] args = null;
           return (T) constructor.newInstance(args);
         } catch (InstantiationException e) {
           throw new RuntimeException("Failed to invoke " + constructor + " with no args", e);
         } catch (InvocationTargetException e) {
           throw new RuntimeException(
               "Failed to invoke " + constructor + " with no args", e.getTargetException());
         } catch (IllegalAccessException e) {
           throw new AssertionError(e);
         }
       }
     };
   } catch (NoSuchMethodException e) {
   }
   return null;
 }
 protected CustomEventBanner internalCreate(String className) throws Exception {
   Class<? extends CustomEventBanner> bannerClass =
       Class.forName(className).asSubclass(CustomEventBanner.class);
   Constructor<?> bannerConstructor = bannerClass.getDeclaredConstructor((Class[]) null);
   bannerConstructor.setAccessible(true);
   return (CustomEventBanner) bannerConstructor.newInstance();
 }
Exemplo n.º 17
0
 private boolean hasDefaultConstructor(Class<?> clazz) {
   try {
     return clazz.getDeclaredConstructor() != null;
   } catch (NoSuchMethodException e) {
     return false;
   }
 }
Exemplo n.º 18
0
  @BeforeClass
  public static void setUpClass() throws Exception {
    PortalUtil portalUtil = new PortalUtil();

    portalUtil.setPortal(new PortalImpl());

    PortalUUIDUtil portalUUIDUtil = new PortalUUIDUtil();

    portalUUIDUtil.setPortalUUID(new PortalUUIDImpl());

    Field field = ReflectionUtil.getDeclaredField(LockLocalServiceUtil.class, "_service");

    LockLocalService lockLocalService = new MockLockLocalService();

    field.set(null, lockLocalService);

    field = ClusterableContextThreadLocal.class.getDeclaredField("_contextThreadLocal");

    field.setAccessible(true);

    _threadLocalContext = (ThreadLocal<HashMap<String, Serializable>>) field.get(null);

    Method method = ClusterSchedulerEngine.class.getDeclaredMethod("delete", String.class);

    Clusterable clusterable = method.getAnnotation(Clusterable.class);

    Class<? extends ClusterInvokeAcceptor> clusterInvokeAcceptorClass = clusterable.acceptor();

    Constructor<? extends ClusterInvokeAcceptor> constructor =
        clusterInvokeAcceptorClass.getDeclaredConstructor();

    constructor.setAccessible(true);

    _clusterInvokeAcceptor = constructor.newInstance();
  }
Exemplo n.º 19
0
  static Car initByDefaultConst()
      throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
          InvocationTargetException, InstantiationException {
    // 1. 通过类加载器,获取Car的Class对象
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Class clazz = classLoader.loadClass("top.ningg.spring.ioc.Car");

    // 获取Car的Class对象的其他方法:
    // Class clazz = Class.forName("top.ningg.spring.ioc.Car");
    // Class clazz = Car.class;
    // Class clazz = new Car().getClass();

    // 思考: 上述几种获取 Class 对象的方式, 哪种最优?

    // 2. 获取Car的Class中的默认构造方法,创建Car对象
    // 补充: getDeclaredConstructor((Class[])null), 使用 Class[] 是因为底层使用
    // Object[] 来匹配构造方法的输入参数, 如果使用(Class)null, 则抛出异常.
    Constructor constructor = clazz.getDeclaredConstructor((Class[]) null);
    Car car = (Car) constructor.newInstance();

    // 3. 获取Car的Class中的setter方法,设置属性
    Method setBrand = clazz.getMethod("setBrand", String.class);
    setBrand.invoke(car, "new Brand");
    Method setColor = clazz.getMethod("setColor", String.class);
    setColor.invoke(car, "Red");
    Method setMaxSpeed = clazz.getMethod("setMaxSpeed", int.class);
    setMaxSpeed.invoke(car, 1000);

    return car;
  }
 private BaseController getController(Class<? extends BaseController> controllerClass)
     throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
         InstantiationException {
   BaseController controller;
   if (ResourceUpsert.class.isAssignableFrom(controllerClass)) {
     Constructor<? extends BaseController> declaredConstructor =
         controllerClass.getDeclaredConstructor(
             ResourceRegistry.class, TypeParser.class, ObjectMapper.class);
     controller = declaredConstructor.newInstance(resourceRegistry, typeParser, objectMapper);
   } else {
     Constructor<? extends BaseController> declaredConstructor =
         controllerClass.getDeclaredConstructor(ResourceRegistry.class, TypeParser.class);
     controller = declaredConstructor.newInstance(resourceRegistry, typeParser);
   }
   return controller;
 }
Exemplo n.º 21
0
 private Constructor getConstructor(Class class1) throws Exception {
   class1 = class1.getDeclaredConstructor(new Class[0]);
   if (!class1.isAccessible()) {
     class1.setAccessible(true);
   }
   return class1;
 }
Exemplo n.º 22
0
 public static <T> T createInstance(Class<T> claz, JSONObject _jobj) {
   try {
     return claz.getDeclaredConstructor(JSONObject.class).newInstance(_jobj);
   } catch (Exception exp) {
     throw new RuntimeException(exp);
   }
 }
  private static Object[] translateFields(Object objs[]) throws NoSuchFieldException {
    try {
      java.io.ObjectStreamField fields[] = (java.io.ObjectStreamField[]) objs;
      Object translation[] = null;

      if (translatedFields == null) translatedFields = new Hashtable();

      translation = (Object[]) translatedFields.get(fields);

      if (translation != null) return translation;
      else {
        Class osfClass = com.sun.corba.se.impl.orbutil.ObjectStreamField.class;

        translation = (Object[]) java.lang.reflect.Array.newInstance(osfClass, objs.length);
        Object arg[] = new Object[2];
        Class types[] = {String.class, Class.class};
        Constructor constructor = osfClass.getDeclaredConstructor(types);
        for (int i = fields.length - 1; i >= 0; i--) {
          arg[0] = fields[i].getName();
          arg[1] = fields[i].getType();

          translation[i] = constructor.newInstance(arg);
        }
        translatedFields.put(fields, translation);
      }

      return (Object[]) translation;
    } catch (Throwable t) {
      throw new NoSuchFieldException();
    }
  }
Exemplo n.º 24
0
  /**
   * @param config {@link MessageDispatcher}'s config
   * @see org.o3project.odenos.remoteobject.messagingclient.redis.PubSubDriverImpl
   */
  public MessageDispatcher(Config config) {

    // Config
    systemManagerId = config.getSystemManagerId();
    eventManagerId = config.getEventManagerId();
    sourceDispatcherId = config.getSourceDispatcherId();
    mode = config.getMode();
    localRequestsToPubSubServer = config.getMode().contains(MODE.LOCAL_REQUESTS_TO_PUBSUB);

    // Actor system instantiation.
    // The number of woker threads: the max number of remote transactions.
    actor = Actor.getInstance(config.getRemoteTransactionsMax());

    // Instantiates IPubSubDriver impl. class
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    try {
      Class<?> clazz = classLoader.loadClass(config.getPubSubDriverImpl());
      Constructor<?> constructor =
          clazz.getDeclaredConstructor(Config.class, IMessageListener.class);
      driverImpl = (IPubSubDriver) constructor.newInstance(config, this);
    } catch (Exception e) {
      log.error("class load error", e);
    }

    // Remote Transactions pool
    remoteTransactions = new RemoteTransactions(this, config);
  }
Exemplo n.º 25
0
  public Tool createTool(Class<? extends Tool> toolClass) {
    Tool tool;
    try {
      Constructor<? extends Tool> constructor = toolClass.getDeclaredConstructor(new Class[] {});
      tool = constructor.newInstance(new Object[] {});
      //			tool = constructor.newInstance((Object) null);

      buttonGroup.add(tool);
      toolMap.put(toolClass, tool);
      tool.setToolbox(this);
      return tool;
    } catch (InstantiationException e) {
      TabletopTool.showError(
          I18N.getText("msg.error.toolCannotInstantiate", toolClass.getName()), e);
    } catch (IllegalAccessException e) {
      TabletopTool.showError(
          I18N.getText("msg.error.toolNeedPublicConstructor", toolClass.getName()), e);
    } catch (NoSuchMethodException nsme) {
      TabletopTool.showError(
          I18N.getText("msg.error.toolNeedValidConstructor", toolClass.getName()), nsme);
    } catch (InvocationTargetException ite) {
      TabletopTool.showError(
          I18N.getText("msg.error.toolConstructorFailed", toolClass.getName()), ite);
    }
    return null;
  }
  /** Invokes a given method via {@link Method#invoke(Object, Object...)}. */
  default Object invoke(ResolvedJavaMethod method, Object receiver, Object... args) {
    try {
      JavaType[] parameterTypes = method.toParameterTypes();
      Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
      for (int i = 0; i < parameterClasses.length; ++i) {
        JavaType type = parameterTypes[i];
        if (type.getJavaKind() != JavaKind.Object) {
          parameterClasses[i] = type.getJavaKind().toJavaClass();
        } else {
          parameterClasses[i] = resolveClassForSnippet(parameterTypes[i]);
        }
      }

      Class<?> c = resolveClassForSnippet(method.getDeclaringClass());
      if (method.isConstructor()) {
        Constructor<?> javaConstructor = c.getDeclaredConstructor(parameterClasses);
        javaConstructor.setAccessible(true);
        return javaConstructor.newInstance(args);
      } else {
        Method javaMethod = c.getDeclaredMethod(method.getName(), parameterClasses);
        javaMethod.setAccessible(true);
        return javaMethod.invoke(receiver, args);
      }
    } catch (IllegalAccessException
        | InstantiationException
        | InvocationTargetException
        | ClassNotFoundException
        | NoSuchMethodException ex) {
      throw new IllegalArgumentException(ex);
    }
  }
Exemplo n.º 27
0
  protected static DeviceImpl importFromBEncodedMapStatic(DeviceManagerImpl manager, Map map)
      throws IOException {
    String impl = ImportExportUtils.importString(map, "_impl");

    if (impl.startsWith(".")) {

      impl = MY_PACKAGE + impl;
    }

    try {
      Class<DeviceImpl> cla = (Class<DeviceImpl>) Class.forName(impl);

      Constructor<DeviceImpl> cons = cla.getDeclaredConstructor(DeviceManagerImpl.class, Map.class);

      cons.setAccessible(true);

      return (cons.newInstance(manager, map));

    } catch (Throwable e) {

      Debug.out("Can't construct device for " + impl, e);

      throw (new IOException("Construction failed: " + Debug.getNestedExceptionMessage(e)));
    }
  }
Exemplo n.º 28
0
 /** This is to mount a plugin at a specific path */
 public void addPlugin(String path, String class_name) {
   String pl_path = path;
   if (!pl_path.startsWith("/")) pl_path = "/" + pl_path;
   if (!pl_path.endsWith("/")) pl_path = pl_path + "/";
   try {
     Class<?> c = Class.forName(class_name);
     Constructor<?> cons = c.getDeclaredConstructor();
     PlaceboPlugin new_plugin = (PlaceboPlugin) cons.newInstance();
     if (new_plugin.startup(this, path)) {
       this.myLogger.logln("Plugin Started (" + class_name + ")");
       this.plugins.put(pl_path, new_plugin);
       this.myLogger.logln("Mounted (" + class_name + ") at " + pl_path);
     } else {
       this.myLogger.logln("Plugin (" + class_name + ") Failed to Startup");
     }
     this.pluginChange();
   } catch (Exception e) {
     this.myLogger.logln(
         "Couldn't Init ("
             + class_name
             + ") at "
             + pl_path
             + " because "
             + e.toString()
             + " / "
             + e.getMessage());
   }
 }
  @SuppressWarnings("unused")
  private static Object _invoke(
      MethodHandler methodHandler,
      Class<? extends ClusterInvokeAcceptor> clusterInvokeAcceptorClass,
      Map<String, Serializable> context)
      throws Exception {

    if (clusterInvokeAcceptorClass != null) {
      Constructor<? extends ClusterInvokeAcceptor> constructor =
          clusterInvokeAcceptorClass.getDeclaredConstructor();

      if (!constructor.isAccessible()) {
        constructor.setAccessible(true);
      }

      ClusterInvokeAcceptor clusterInvokeAcceptor = constructor.newInstance();

      if (!clusterInvokeAcceptor.accept(context)) {
        return null;
      }
    }

    _populateThreadLocalsFromContext(context);

    return methodHandler.invoke();
  }
  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);
    }
  }