Example #1
1
 public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
     throws BeansException {
   if (annotationPackage == null || annotationPackage.length() == 0) {
     return;
   }
   if (beanFactory instanceof BeanDefinitionRegistry) {
     try {
       // init scanner
       Class<?> scannerClass =
           ClassUtils.loadClass(
               "org.springframework.context.annotation.ClassPathBeanDefinitionScanner");
       Object scanner =
           scannerClass
               .getConstructor(new Class<?>[] {BeanDefinitionRegistry.class, boolean.class})
               .newInstance(new Object[] {(BeanDefinitionRegistry) beanFactory, true});
       // add filter
       Class<?> filterClass =
           ClassUtils.loadClass("org.springframework.core.type.filter.AnnotationTypeFilter");
       Object filter = filterClass.getConstructor(Class.class).newInstance(Service.class);
       Method addIncludeFilter =
           scannerClass.getMethod(
               "addIncludeFilter",
               ClassUtils.loadClass("org.springframework.core.type.filter.TypeFilter"));
       addIncludeFilter.invoke(scanner, filter);
       // scan packages
       String[] packages = Constants.COMMA_SPLIT_PATTERN.split(annotationPackage);
       Method scan = scannerClass.getMethod("scan", new Class<?>[] {String[].class});
       scan.invoke(scanner, new Object[] {packages});
     } catch (Throwable e) {
       // spring 2.0
     }
   }
 }
  static {
    Class c;
    Constructor constr;
    int constrParamCnt;
    try {
      c = ClassUtil.forName("java.util.concurrent.ConcurrentHashMap");
      try {
        constr = c.getConstructor(new Class[] {Integer.TYPE, Float.TYPE, Integer.TYPE});
        constrParamCnt = 3;
      } catch (Exception e) {
        throw new RuntimeException("Failed to get ConcurrentHashMap constructor", e);
      }
    } catch (ClassNotFoundException e) {
      c = HashMap.class;
      try {
        constr = c.getConstructor(new Class[] {Integer.TYPE, Float.TYPE});
        constrParamCnt = 2;
      } catch (Exception e2) {
        throw new RuntimeException("Failed to get HashMap constructor", e2);
      }
    }

    bestHashMapClass = c;
    bestHashMapClassConstructor = constr;
    bestHashMapClassConstructorParamCnt = constrParamCnt;
  }
  public CircuitElementView instantiateElement(
      UUID elementUUID,
      float positionX,
      float positionY,
      CircuitElementManager elementManager,
      WireManager wireManager)
      throws InvocationTargetException, IllegalAccessException, InstantiationException,
          NoSuchMethodException {
    Class<? extends CircuitElementView> viewType = ElementTypeUUID.VIEW_MAP.get(elementUUID);
    if (viewType == null) throw new IllegalArgumentException("Missing element view UUID");

    Class<? extends CircuitElement> elementType = ElementTypeUUID.ELEMENT_MAP.get(elementUUID);
    if (elementType == null) throw new IllegalArgumentException("Missing element type UUID");

    Constructor<? extends CircuitElementView> viewConstructor;
    viewConstructor =
        viewType.getConstructor(
            Context.class, CircuitElement.class, float.class, float.class, WireManager.class);

    Constructor<? extends CircuitElement> elementConstructor;
    elementConstructor = elementType.getConstructor(CircuitElementManager.class);

    CircuitElement element = elementConstructor.newInstance(elementManager);

    return viewConstructor.newInstance(context, element, 0, 0, wireManager);
  }
  @SuppressWarnings({"fallthrough"})
  private static Permission getPermission(String type, String name, String actions)
      throws ClassNotFoundException, InstantiationException, IllegalAccessException,
          NoSuchMethodException, InvocationTargetException {
    Class<?> clazz = Class.forName(type);
    int nArgs = actions != null ? 2 : name != null ? 1 : 0;

    switch (nArgs) {
      case 0:
        try {
          return (Permission) clazz.getConstructor().newInstance();
        } catch (NoSuchMethodException e) {
        }

      case 1:
        try {
          return (Permission) clazz.getConstructor(ARGS_NAME).newInstance(name);
        } catch (NoSuchMethodException e) {
        }

      case 2:
        return (Permission) clazz.getConstructor(ARGS_NAME_ACTIONS).newInstance(name, actions);
    }

    assert false;
    return null;
  }
Example #5
1
 /**
  * Factory method, equivalent to a "fromXML" for step creation. Looks for a class with the same
  * name as the XML tag, with the first letter capitalized. For example, &lt;call /&gt; is
  * abbot.script.Call.
  */
 public static Step createStep(Resolver resolver, Element el) throws InvalidScriptException {
   String tag = el.getName();
   Map attributes = createAttributeMap(el);
   String name = tag.substring(0, 1).toUpperCase() + tag.substring(1);
   if (tag.equals(TAG_WAIT)) {
     attributes.put(TAG_WAIT, "true");
     name = "Assert";
   }
   try {
     name = "abbot.script." + name;
     Log.debug("Instantiating " + name);
     Class cls = Class.forName(name);
     try {
       // Steps with contents require access to the XML element
       Class[] argTypes = new Class[] {Resolver.class, Element.class, Map.class};
       Constructor ctor = cls.getConstructor(argTypes);
       return (Step) ctor.newInstance(new Object[] {resolver, el, attributes});
     } catch (NoSuchMethodException nsm) {
       // All steps must support this ctor
       Class[] argTypes = new Class[] {Resolver.class, Map.class};
       Constructor ctor = cls.getConstructor(argTypes);
       return (Step) ctor.newInstance(new Object[] {resolver, attributes});
     }
   } catch (ClassNotFoundException cnf) {
     String msg = Strings.get("step.unknown_tag", new Object[] {tag});
     throw new InvalidScriptException(msg);
   } catch (InvocationTargetException ite) {
     Log.warn(ite);
     throw new InvalidScriptException(ite.getTargetException().getMessage());
   } catch (Exception exc) {
     Log.warn(exc);
     throw new InvalidScriptException(exc.getMessage());
   }
 }
Example #6
1
 public <T> T createProxy(
     ModelElementState state,
     StructSchema<T> viewSchema,
     @Nullable StructSchema<? extends T> delegateSchema,
     TypeConverter typeConverter) {
   try {
     Class<? extends T> generatedClass = getGeneratedImplementation(viewSchema, delegateSchema);
     if (generatedClass == null) {
       throw new IllegalStateException(
           "No managed implementation class available for: " + viewSchema.getType());
     }
     if (delegateSchema == null) {
       Constructor<? extends T> constructor =
           generatedClass.getConstructor(ModelElementState.class, TypeConverter.class);
       return constructor.newInstance(state, typeConverter);
     } else {
       ModelType<? extends T> delegateType = delegateSchema.getType();
       Object delegate = state.getBackingNode().getPrivateData(delegateType);
       Constructor<? extends T> constructor =
           generatedClass.getConstructor(
               ModelElementState.class, TypeConverter.class, delegateType.getConcreteClass());
       return constructor.newInstance(state, typeConverter, delegate);
     }
   } catch (InvocationTargetException e) {
     throw UncheckedException.throwAsUncheckedException(e.getTargetException());
   } catch (Exception e) {
     throw UncheckedException.throwAsUncheckedException(e);
   }
 }
Example #7
0
 public Bean(String classPackage, String clazz, ClassLoaderStrategy cls, Bean topLevelBean)
     throws Exception {
   // Get the no-arg constructor and create the bean
   try {
     Class classOfBean = ObjectXml.getClassOfBean((ClassLoader) cls, classPackage + "." + clazz);
     Constructor ct = null;
     // check whether this class is an inner class
     if (classOfBean.getEnclosingClass() != null) {
       ct = classOfBean.getConstructor(new Class[] {classOfBean.getEnclosingClass()});
       beanObject = ct.newInstance(new Object[] {topLevelBean.getBeanObject()});
     } else {
       ct = classOfBean.getConstructor((Class[]) null);
       beanObject = ct.newInstance((Object[]) null);
     }
     // Get an array of property descriptors
     beanInfo = Introspector.getBeanInfo(classOfBean);
     PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
     // load property descriptors into hashtable
     propDesc = new Properties();
     for (int i = 0; i < pds.length; i++) {
       propDesc.put(pds[i].getName(), pds[i]);
     }
   } catch (Exception e) {
     System.err.println("Exception creating bean: " + e.getMessage());
     e.printStackTrace();
     throw e;
   }
 }
  private BrowserLauncher createBrowserLauncher(
      Class c, String browserStartCommand, String sessionId, SeleneseQueue queue) {
    try {
      BrowserLauncher browserLauncher;
      if (null == browserStartCommand) {
        Constructor ctor = c.getConstructor(new Class[] {int.class, String.class});
        Object[] args = new Object[] {new Integer(server.getPort()), sessionId};
        browserLauncher = (BrowserLauncher) ctor.newInstance(args);
      } else {
        Constructor ctor = c.getConstructor(new Class[] {int.class, String.class, String.class});
        Object[] args =
            new Object[] {
              new Integer(SeleniumServer.getPortDriversShouldContact()),
              sessionId,
              browserStartCommand
            };
        browserLauncher = (BrowserLauncher) ctor.newInstance(args);
      }

      if (browserLauncher instanceof SeleneseQueueAware) {
        ((SeleneseQueueAware) browserLauncher).setSeleneseQueue(queue);
      }

      return browserLauncher;
    } catch (InvocationTargetException e) {
      throw new RuntimeException(
          "failed to contruct launcher for "
              + browserStartCommand
              + "for"
              + e.getTargetException());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  private Object constructEnvEntry(String type, String value) {
    try {
      Class<?> clazz = Class.forName(type);
      Constructor<?> c = null;
      try {
        c = clazz.getConstructor(String.class);
        return c.newInstance(value);
      } catch (NoSuchMethodException e) {
        // Ignore
      }

      if (value.length() != 1) {
        return null;
      }

      try {
        c = clazz.getConstructor(char.class);
        return c.newInstance(Character.valueOf(value.charAt(0)));
      } catch (NoSuchMethodException e) {
        // Ignore
      }
    } catch (Exception e) {
      // Ignore
    }
    return null;
  }
Example #10
0
  public static void main(String[] args) throws Exception {
    Game game = new Game();
    String player2Start = System.getProperty("tris.player2.start", "false");
    String player1Name = System.getProperty("tris.player1.name", "Player1");
    String player2Name = System.getProperty("tris.player2.name", "Player2");

    String player1ClassName = System.getProperty("tris.player1.class", DEFAULT_USER_PLAYER_CLASS);
    String player2ClassName = System.getProperty("tris.player2.class", DEFAULT_AI_PLAYER_CLASS);

    @SuppressWarnings("unchecked")
    Class<Player> player1Class = (Class<Player>) Class.forName(player1ClassName);
    @SuppressWarnings("unchecked")
    Class<Player> player2Class = (Class<Player>) Class.forName(player2ClassName);

    Player player1 =
        player1Class
            .getConstructor(String.class, Signs.class)
            .newInstance(player1Name, Signs.Cross);
    Player player2 =
        player2Class
            .getConstructor(String.class, Signs.class)
            .newInstance(player2Name, Signs.Circle);

    if ("false".equals(player2Start)) {
      game.start(player1, player2);
    } else {
      game.start(player2, player1);
    }
  }
 @SuppressWarnings("unchecked")
 CustomAuthenticationProviderImpl(HiveConf conf) throws AuthenticationException {
   this.customHandlerClass =
       (Class<? extends PasswdAuthenticationProvider>)
           conf.getClass(
               HiveConf.ConfVars.HIVE_SERVER2_CUSTOM_AUTHENTICATION_CLASS.varname,
               PasswdAuthenticationProvider.class);
   // Try initializing the class with non-default and default constructors
   try {
     this.customProvider = customHandlerClass.getConstructor(HiveConf.class).newInstance(conf);
   } catch (NoSuchMethodException e) {
     try {
       this.customProvider = customHandlerClass.getConstructor().newInstance();
       // in java6, these four extend directly from Exception. So have to handle separately. In
       // java7,
       // the common subclass is ReflectiveOperationException
     } catch (NoSuchMethodException e1) {
       throw new AuthenticationException(
           "Can't instantiate custom authentication provider class. "
               + "Either provide a constructor with HiveConf as argument or a default constructor.",
           e);
     } catch (Exception e1) {
       throw new AuthenticationException(e.getMessage(), e);
     }
   } catch (Exception e) {
     throw new AuthenticationException(e.getMessage(), e);
   }
 }
Example #12
0
 private MetaClass createWithCustomLookup(Class theClass, MetaClassRegistry registry) {
   try {
     final Class customMetaClass =
         Class.forName("groovy.runtime.metaclass." + theClass.getName() + "MetaClass");
     if (DelegatingMetaClass.class.isAssignableFrom(customMetaClass)) {
       final Constructor customMetaClassConstructor =
           customMetaClass.getConstructor(MetaClass.class);
       MetaClass normalMetaClass = createNormalMetaClass(theClass, registry);
       return (MetaClass) customMetaClassConstructor.newInstance(normalMetaClass);
     } else {
       final Constructor customMetaClassConstructor =
           customMetaClass.getConstructor(MetaClassRegistry.class, Class.class);
       return (MetaClass) customMetaClassConstructor.newInstance(registry, theClass);
     }
   } catch (final ClassNotFoundException e) {
     return createNormalMetaClass(theClass, registry);
   } catch (final Exception e) {
     throw new GroovyRuntimeException(
         "Could not instantiate custom Metaclass for class: "
             + theClass.getName()
             + ". Reason: "
             + e,
         e);
   }
 }
Example #13
0
  protected QuercusServletImpl getQuercusServlet(boolean isResin) {
    QuercusServletImpl impl = null;

    if (isResin) {
      try {
        Class<?> cls = Class.forName("com.caucho.quercus.servlet.ProResinQuercusServlet");
        Constructor<?> cons = cls.getConstructor(File.class);

        impl = (QuercusServletImpl) cons.newInstance(_licenseDirectory);
      } catch (Exception e) {
        log.log(Level.FINEST, e.getMessage(), e);
      }
    }

    if (impl == null) {
      try {
        Class<?> cls = Class.forName("com.caucho.quercus.servlet.ProQuercusServlet");
        Constructor<?> cons = cls.getConstructor(File.class);

        impl = (QuercusServletImpl) cons.newInstance(_licenseDirectory);
      } catch (Exception e) {
        log.log(Level.FINEST, e.getMessage(), e);
      }
    }

    if (impl == null) {
      impl = new QuercusServletImpl();
    }

    return impl;
  }
Example #14
0
 public static void main(String[] args) throws Exception {
   // 直接获取类
   // Class<?> classType = InvokeTester.class;
   // 通过完整的类型路径获取类
   Class<?> classType = Class.forName("reflect.invokeTester.InvokeTester");
   // 使用newInstance创建对象
   // Object invokeTester = classType.newInstance();
   // 使用默认构造函数获取对象
   Object invokeTester = classType.getConstructor(new Class[] {}).newInstance(new Object[] {});
   // 获取InvokeTester类的add()方法
   Method addMethod = classType.getMethod("add", new Class[] {int.class, int.class});
   // 调用invokeTester对象上的add()方法
   Object result =
       addMethod.invoke(invokeTester, new Object[] {new Integer(100), new Integer(200)});
   System.out.println((Integer) result);
   // 获取InvokeTester类的echo()方法
   Method echoMethod = classType.getMethod("echo", new Class[] {String.class});
   // 调用invokeTester对象的echo()方法
   result = echoMethod.invoke(invokeTester, new Object[] {"Hello"});
   System.out.println((String) result);
   // 创建有参构造函数的类对象
   Object invokeTester1 =
       classType
           .getConstructor(new Class[] {String.class})
           .newInstance(new Object[] {new String("测试一个带参数的构造调用")});
   // 获取方法方式相同
   Method getStrMethod = classType.getMethod("getStr");
   Object str = getStrMethod.invoke(invokeTester1);
   System.out.println(str);
 }
Example #15
0
  @Override
  public void init() throws ServletException {
    ServletContextFactory.setServletContext(getServletContext());
    IConfiguration configuration = null;
    try {
      String className = getServletConfig().getInitParameter("configuration");
      if (className != null) {
        Class<?> clazz = Class.forName(className);

        if (clazz.getConstructor(ServletConfig.class) != null) {
          configuration =
              (IConfiguration)
                  clazz.getConstructor(ServletConfig.class).newInstance(getServletConfig());

        } else {
          configuration = (IConfiguration) clazz.newInstance();
        }
      } else {
        configuration = new Configuration(getServletConfig());
      }
    } catch (Exception e) {
      configuration = new Configuration(getServletConfig());
    }
    try {
      configuration.init();
      AccessControlUtil.getInstance(configuration).loadACLConfig();
    } catch (Exception e) {
      if (Boolean.valueOf(getServletConfig().getInitParameter("debug"))) {
        e.printStackTrace();
      }
      this.startException = e;
      configuration = null;
    }
    ConfigurationFactory.getInstace().setConfiguration(configuration);
  }
 /**
  * Constructs an instance of BitPostingIndexInputStream.
  *
  * @param _index
  * @param _structureName
  * @param _pointerList
  * @param _postingIteratorClass
  * @throws IOException
  */
 public BitPostingIndexInputStream(
     IndexOnDisk _index,
     String _structureName,
     Iterator<? extends BitIndexPointer> _pointerList,
     Class<? extends IterablePosting> _postingIteratorClass)
     throws IOException {
   this.index = _index;
   this.doi = _index.getDocumentIndex();
   this.structureName = _structureName;
   fileCount =
       Byte.parseByte(_index.getIndexProperty("index." + structureName + ".data-files", "1"));
   file = new BitInputStream(getFilename(_index, structureName, fileCount, (byte) 0));
   if (DEBUG) file = new DebuggingBitIn(file);
   pointerList = _pointerList;
   postingIteratorClass = _postingIteratorClass;
   fieldCount =
       _index.getIntIndexProperty("index." + structureName + ".fields.count", currentFile = 0);
   try {
     postingConstructor =
         fieldCount > 0
             ? postingIteratorClass.getConstructor(
                 BitIn.class, Integer.TYPE, DocumentIndex.class, Integer.TYPE)
             : postingIteratorClass.getConstructor(BitIn.class, Integer.TYPE, DocumentIndex.class);
   } catch (Exception e) {
     throw new WrappedIOException(e);
   }
 }
Example #17
0
 public static <K, V> Map<K, V> getMapFromString(
     String s, Class<K> keyClass, Class<V> valueClass, MapFactory<K, V> mapFactory)
     throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
         InvocationTargetException, InstantiationException {
   Constructor<K> keyC = keyClass.getConstructor(new Class[] {Class.forName("java.lang.String")});
   Constructor<V> valueC =
       valueClass.getConstructor(new Class[] {Class.forName("java.lang.String")});
   if (s.charAt(0) != '{') throw new RuntimeException("");
   s = s.substring(1); // get rid of first brace
   String[] fields = s.split("\\s+");
   Map<K, V> m = mapFactory.newMap();
   // populate m
   for (int i = 0; i < fields.length; i++) {
     // System.err.println("Parsing " + fields[i]);
     fields[i] = fields[i].substring(0, fields[i].length() - 1); // get rid of
     // following
     // comma or
     // brace
     String[] a = fields[i].split("=");
     K key = keyC.newInstance(a[0]);
     V value;
     if (a.length > 1) {
       value = valueC.newInstance(a[1]);
     } else {
       value = valueC.newInstance("");
     }
     m.put(key, value);
   }
   return m;
 }
  public static ScaleGestureDetectorProxy create(Context context, TouchImageView view) {
    if (android.os.Build.VERSION.SDK_INT >= 8) {
      try {
        // Construct the listener object
        Class<?> clazz =
            Class.forName("com.adamrosenfield.wordswithcrosses.view.TouchImageView$ScaleListener");
        Constructor<?> constructor = clazz.getConstructor(TouchImageView.class);
        Object listener = constructor.newInstance(view);

        // Construct the detector proxy
        clazz =
            Class.forName(
                "com.adamrosenfield.wordswithcrosses.view.ScaleGestureDetectorProxy$ScaleGestureDetectorProxyFroyo");
        constructor =
            clazz.getConstructor(
                Context.class,
                Class.forName("android.view.ScaleGestureDetector$OnScaleGestureListener"));
        return (ScaleGestureDetectorProxy) constructor.newInstance(context, listener);
      } catch (ClassNotFoundException
          | NoSuchMethodException
          | SecurityException
          | InstantiationException
          | IllegalAccessException
          | InvocationTargetException e) {
        e.printStackTrace();
      }
    }

    return new ScaleGestureDetectorProxyDefault();
  }
Example #19
0
  public void init(IndexUpdater indexUpdater, IndexRebuilder indexRebuilder, XWikiContext context) {
    super.init(context);

    try {
      @SuppressWarnings("unchecked")
      Class<? extends Analyzer> clazz =
          (Class<? extends Analyzer>)
              Class.forName(context.getWiki().Param(PROP_ANALYZER, DEFAULT_ANALYZER));
      this.analyzer = clazz.getConstructor(Version.class).newInstance(Version.LUCENE_36);
    } catch (Exception e) {
      LOGGER.error("Error instantiating analyzer: {}", e.getMessage());
      LOGGER.warn("Using default analyzer class: " + DEFAULT_ANALYZER);
      try {
        @SuppressWarnings("unchecked")
        Class<? extends Analyzer> clazz =
            (Class<? extends Analyzer>) Class.forName(DEFAULT_ANALYZER);
        this.analyzer = clazz.getConstructor(Version.class).newInstance(Version.LUCENE_36);
      } catch (Exception e1) {
        throw new RuntimeException(
            "Instantiation of default analyzer " + DEFAULT_ANALYZER + " failed", e1);
      }
    }
    Map<String, Analyzer> specialAnalyzers = new HashMap<String, Analyzer>();
    Analyzer preserve = new KeywordAnalyzer();
    specialAnalyzers.put(IndexFields.DOCUMENT_EXACTSPACE, preserve);
    specialAnalyzers.put(IndexFields.DOCUMENT_WIKI, preserve);
    specialAnalyzers.put(IndexFields.DOCUMENT_TYPE, preserve);
    specialAnalyzers.put(IndexFields.DOCUMENT_LANGUAGE, preserve);
    this.analyzer = new PerFieldAnalyzerWrapper(this.analyzer, specialAnalyzers);

    LOGGER.debug("Assigning index updater: {}", indexUpdater);

    if (this.indexDirs == null) {
      this.indexDirs = context.getWiki().Param(PROP_INDEX_DIR);
      if (StringUtils.isEmpty(this.indexDirs)) {
        File workDir = getLuceneWorkDirectory();
        this.indexDirs = workDir.getAbsolutePath();
      }
    }

    this.indexUpdater = indexUpdater;
    this.indexUpdater.setAnalyzer(this.analyzer);
    this.indexUpdaterThread = new Thread(indexUpdater, "Lucene Index Updater");
    this.indexUpdaterThread.start();
    this.indexRebuilder = indexRebuilder;

    openIndexReaders(context);

    // Register the Index Updater as an Event Listener so that modified documents/attachments are
    // added to the
    // Lucene indexing queue.
    // If the Index Updater is already registered don't do anything.
    ObservationManager observationManager = Utils.getComponent(ObservationManager.class);
    if (observationManager.getListener(indexUpdater.getName()) == null) {
      observationManager.addListener(indexUpdater);
    }

    LOGGER.debug("Lucene plugin initialized.");
  }
Example #20
0
  public PersistManager(URI iceRoot) {
    I = new Persist[MAX_BACKENDS];
    stats = new PersistStatsEntry[MAX_BACKENDS];
    for (int i = 0; i < stats.length; i++) {
      stats[i] = new PersistStatsEntry();
    }

    if (iceRoot == null) {
      Log.err("ice_root must be specified.  Exiting.");
      H2O.exit(1);
    }

    Persist ice = null;
    boolean windowsPath = iceRoot.toString().matches("^[a-zA-Z]:.*");

    if (windowsPath) {
      ice = new PersistFS(new File(iceRoot.toString()));
    } else if ((iceRoot.getScheme() == null) || Schemes.FILE.equals(iceRoot.getScheme())) {
      ice = new PersistFS(new File(iceRoot.getPath()));
    } else if (Schemes.HDFS.equals(iceRoot.getScheme())) {
      Log.err("HDFS ice_root not yet supported.  Exiting.");
      H2O.exit(1);

      // I am not sure anyone actually ever does this.
      // H2O on Hadoop launches use local disk for ice root.
      // This has a chance to work, but turn if off until it gets tested.
      //
      //      try {
      //        Class klass = Class.forName("water.persist.PersistHdfs");
      //        java.lang.reflect.Constructor constructor = klass.getConstructor(new
      // Class[]{URI.class});
      //        ice = (Persist) constructor.newInstance(iceRoot);
      //      } catch (Exception e) {
      //        Log.err("Could not initialize HDFS");
      //        throw new RuntimeException(e);
      //      }
    }

    I[Value.ICE] = ice;
    I[Value.NFS] = new PersistNFS();

    try {
      Class klass = Class.forName("water.persist.PersistHdfs");
      java.lang.reflect.Constructor constructor = klass.getConstructor();
      I[Value.HDFS] = (Persist) constructor.newInstance();
      Log.info("HDFS subsystem successfully initialized");
    } catch (Throwable ignore) {
      Log.info("HDFS subsystem not available");
    }

    try {
      Class klass = Class.forName("water.persist.PersistS3");
      java.lang.reflect.Constructor constructor = klass.getConstructor();
      I[Value.S3] = (Persist) constructor.newInstance();
      Log.info("S3 subsystem successfully initialized");
    } catch (Throwable ignore) {
      Log.info("S3 subsystem not available");
    }
  }
Example #21
0
  public NodeIoHandler createNodeHandler(String configItem, Uri uri, String parameterString) {
    Class ioHandlerClass = null;
    String className = "com.mediatek.MediatekDM.Dm" + configItem + "NodeIoHandler";
    Log.d(TAG.NodeIOHandler, "[NodeHandlerFactory]loading cls:" + className);
    try {
      ioHandlerClass = Class.forName(className);
    } catch (ClassNotFoundException e1) {
      Log.e(TAG.NodeIOHandler, "[NodeHandlerFactory]cls not found:" + className);
      return null;
    }
    Constructor conWith3Args = null;
    Constructor conWith2Args = null;
    try {
      conWith3Args = ioHandlerClass.getConstructor(Context.class, Uri.class, String.class);
    } catch (SecurityException e) {

      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      try {
        conWith2Args = ioHandlerClass.getConstructor(Context.class, Uri.class);
      } catch (SecurityException e1) {
        e1.printStackTrace();
        Log.e(TAG.NodeIOHandler, "constructor with 2 args security exception");
        return null;
      } catch (NoSuchMethodException e1) {
        e1.printStackTrace();
        Log.e(TAG.NodeIOHandler, "constructor with 2 args no such method");
        return null;
      }
    }
    try {
      if (conWith3Args != null) {
        Log.d(
            TAG.NodeIOHandler,
            "[NodeHandlerFactory]created: " + configItem + "(" + uri + "," + parameterString + ")");
        return (NodeIoHandler) (conWith3Args.newInstance(mContext, uri, parameterString));
      } else {
        if (conWith2Args != null) {
          Log.d(TAG.NodeIOHandler, "[NodeHandlerFactory]created: " + configItem + "(" + uri + ")");
          return (NodeIoHandler) (conWith2Args.newInstance(mContext, uri));
        }
      }
    } catch (IllegalArgumentException e) {

      e.printStackTrace();
    } catch (InstantiationException e) {

      e.printStackTrace();
    } catch (IllegalAccessException e) {

      e.printStackTrace();
    } catch (InvocationTargetException e) {

      e.printStackTrace();
    }
    // fatal error, not found corresponding IoHandler class;
    Log.w(TAG.NodeIOHandler, "[NodeHandlerFactory]creating IoHandler failed.");
    return null;
  }
Example #22
0
  /**
   * Visits the {@link BOp} hierarchy and verify that all {@link BOp}s declare the required public
   * constructors (shallow copy and deep copy). A list of all bad {@link BOp}s is collected. If that
   * list is not empty, then the list is reported as a test failure.
   */
  public void test_ctors() {

    // all bad bops.
    final Map<Class<?>, String /*cause*/> bad = new LinkedHashMap<Class<?>, String>();

    // all discovered bops.
    final List<Class<?>> found = new LinkedList<Class<?>>();

    for (Class<?> cls : all) {

      if (cls.isInterface()) {
        // skip interfaces.
        //                System.out.println("Skipping interface: "+cls.getName());
        continue;
      }

      final int mod = cls.getModifiers();
      if (Modifier.isAbstract(mod)) {
        // skip abstract classes since we can't get their ctors.
        //                System.err.println("Skipping abstract classes: "+cls.getName());
        continue;
      }

      found.add(cls);
      //            System.err.println(cls.getName());

    }

    for (Class<?> cls : found) {

      // test for shallow copy constructor.
      if (!noShallowCopy.contains(cls)) {
        try {
          cls.getConstructor(new Class[] {BOp[].class, Map.class});
        } catch (NoSuchMethodException e) {
          bad.put(cls, cause_shallow);
          log.error(cause_shallow + " : " + cls); // , e);
        }
      }

      // test for deep copy constructor.
      if (!noDeepCopy.contains(cls)) {
        try {
          cls.getConstructor(new Class[] {cls});
        } catch (NoSuchMethodException e) {
          bad.put(cls, cause_deep);
          log.error(cause_deep + " : " + cls); // , e);
        }
      }
    }

    if (!bad.isEmpty()) {

      System.err.println("Errors: " + bad.keySet());

      fail(bad.toString());
    }
  }
Example #23
0
  public static VendorCompat getVendorCompat(Context context) {
    if (cachedCompat != null) return cachedCompat;

    // Application-wide configuration
    Context appContext = context.getApplicationContext();

    // PlayHaven specific configuration for this Application
    SharedPreferences pref = appContext.getSharedPreferences(SHARED_PREF_NAME, SHARED_PREF_MODE);

    String pluginType =
        pref.getString(Config.PluginType.toString(), VendorCompat.class.getCanonicalName());
    String pluginId = pref.getString(Config.PluginIdentifer.toString(), "android");

    if (pluginId == null || pluginType == null) {
      d("getVendorCompat: using default");
      return createDefaultVendorCompat(context);
    }

    VendorCompat compat = null;
    Class cls = null;

    // Class to load
    try {
      cls = Class.forName(pluginType);
    } catch (ClassNotFoundException e) {
      d(e, "getVendorCompat: failed to find: %s/%s", pluginType, pluginId);
      compat = createDefaultVendorCompat(context);
    }

    // Attempt two-argument constructor
    if (compat == null) {
      try {
        @SuppressWarnings("unchecked")
        Constructor con = cls.getConstructor(Context.class, String.class);
        compat = (VendorCompat) con.newInstance(context, pluginId);
        d("getVendorCompat: instantiated #1: %s/%s", pluginType, pluginId);
      } catch (Exception e) {
        d(e, "getVendorCompat: failed to instantiate #1: %s/%s", pluginType, pluginId);
      }
    }

    // Attempt one-argument constructor
    if (compat == null) {
      try {
        @SuppressWarnings("unchecked")
        Constructor con = cls.getConstructor(String.class);
        compat = (VendorCompat) con.newInstance(pluginId);
        d("getVendorCompat: instantiated #2: %s/%s", pluginType, pluginId);
      } catch (Exception e) {
        d(e, "getVendorCompat: failed to instantiate #2: %s/%s", pluginType, pluginId);
      }
    }

    if (compat == null) compat = createDefaultVendorCompat(context);

    setVendorCompat(context, compat);
    return compat;
  }
  @SuppressWarnings("unchecked")
  public VolatileCode_Unknown() throws Exception {
    String versionString =
        Bukkit.getServer()
            .getClass()
            .getName()
            .replace("org.bukkit.craftbukkit.", "")
            .replace("CraftServer", "");
    String nmsPackageString = "net.minecraft.server." + versionString;
    String obcPackageString = "org.bukkit.craftbukkit." + versionString;

    classWorld = Class.forName(nmsPackageString + "World");

    classEntityVillager = Class.forName(nmsPackageString + "EntityVillager");
    classEntityVillagerConstructor = classEntityVillager.getConstructor(classWorld);
    Field[] fields = classEntityVillager.getDeclaredFields();
    for (Field field : fields) {
      if (field.getType().getName().endsWith("MerchantRecipeList")) {
        recipeListField = field;
        break;
      }
    }
    recipeListField.setAccessible(true);
    Method[] methods = classEntityVillager.getDeclaredMethods();
    for (Method method : methods) {
      if (method.getReturnType() == boolean.class
          && method.getParameterTypes().length == 1
          && method.getParameterTypes()[0].getName().endsWith("EntityHuman")) {
        openTradeMethod = method;
        break;
      }
    }
    openTradeMethod.setAccessible(true);

    classEntityInsentient = Class.forName(nmsPackageString + "EntityInsentient");
    setCustomNameMethod = classEntityInsentient.getDeclaredMethod("setCustomName", String.class);

    classNMSItemStack = Class.forName(nmsPackageString + "ItemStack");

    classCraftItemStack = Class.forName(obcPackageString + "inventory.CraftItemStack");
    asNMSCopyMethod = classCraftItemStack.getDeclaredMethod("asNMSCopy", ItemStack.class);

    classMerchantRecipe = Class.forName(nmsPackageString + "MerchantRecipe");
    merchantRecipeConstructor =
        classMerchantRecipe.getConstructor(classNMSItemStack, classNMSItemStack, classNMSItemStack);
    maxUsesField = classMerchantRecipe.getDeclaredField("maxUses");
    maxUsesField.setAccessible(true);

    classMerchantRecipeList = Class.forName(nmsPackageString + "MerchantRecipeList");
    // clearMethod = classMerchantRecipeList.getMethod("clear");
    // addMethod = classMerchantRecipeList.getMethod("add", Object.class);

    classCraftPlayer = Class.forName(obcPackageString + "entity.CraftPlayer");
    craftPlayerGetHandle = classCraftPlayer.getDeclaredMethod("getHandle");

    classEntity = Class.forName(nmsPackageString + "Entity");
    worldField = classEntity.getDeclaredField("world");
  }
Example #25
0
 /** Gets a constructor which takes a single String as its argument or a no arg constructor. */
 public static Constructor getTestConstructor(Class theClass) throws NoSuchMethodException {
   Class[] args = {String.class};
   try {
     return theClass.getConstructor(args);
   } catch (NoSuchMethodException e) {
     // fall through
   }
   return theClass.getConstructor(new Class[0]);
 }
Example #26
0
 Log getLog() throws Exception {
   File f = new File(getDirectory(), this.fileName);
   if (logClass == (Class<?>) RollingLog.class) {
     // For testing purpose, set the rolling size to be very small.
     return logClass.getConstructor(File.class, Long.TYPE).newInstance(f, 128);
   } else {
     return logClass.getConstructor(File.class).newInstance(f);
   }
 }
  private static Set parseLookupBindingXml(
      UimaContext annotCtx, Map dictMap, Element lookupBindingsEl) throws Exception {

    Set lsSet = new HashSet();
    Iterator itr = lookupBindingsEl.getChildren().iterator();
    while (itr.hasNext()) {
      Element bindingEl = (Element) itr.next();

      Element dictEl = bindingEl.getChild("dictionaryRef");
      String dictID = dictEl.getAttributeValue("idRef");
      DictionaryEngine dictEngine = (DictionaryEngine) dictMap.get(dictID);
      if (dictEngine == null) {
        throw new Exception("Dictionary undefined: " + dictID);
      }

      Class[] constrArgs = {UimaContext.class, Properties.class};
      Class[] constrArgsConsum = {
        UimaContext.class, Properties.class, int.class
      }; // ohnlp-Bugs-3296301
      Class[] constrArgsConsumB = {UimaContext.class, Properties.class};

      Element lookupInitEl = bindingEl.getChild("lookupInitializer");
      String liClassName = lookupInitEl.getAttributeValue("className");
      Element liPropertiesEl = lookupInitEl.getChild("properties");
      Properties liProps = parsePropertiesXml(liPropertiesEl);
      Class liClass = Class.forName(liClassName);
      Constructor liConstr = liClass.getConstructor(constrArgs);
      Object[] liArgs = {annotCtx, liProps};
      LookupInitializer li = (LookupInitializer) liConstr.newInstance(liArgs);

      Element lookupConsumerEl = bindingEl.getChild("lookupConsumer");
      String lcClassName = lookupConsumerEl.getAttributeValue("className");
      Element lcPropertiesEl = lookupConsumerEl.getChild("properties");
      Properties lcProps = parsePropertiesXml(lcPropertiesEl);
      Class lcClass = Class.forName(lcClassName);
      Constructor[] consts = lcClass.getConstructors();
      Constructor lcConstr = null;
      Object[] lcArgs = null;
      for (int i = 0; i < consts.length; i++) {
        lcConstr = consts[i];
        if (Arrays.equals(constrArgsConsum, lcConstr.getParameterTypes())) {
          lcConstr = lcClass.getConstructor(constrArgsConsum);
          lcArgs = new Object[] {annotCtx, lcProps, maxSizeList}; // ohnlp-Bugs-3296301
        } else if (Arrays.equals(constrArgsConsumB, lcConstr.getParameterTypes())) {
          lcConstr = lcClass.getConstructor(constrArgsConsumB);
          lcArgs = new Object[] {annotCtx, lcProps};
        }
      }

      LookupConsumer lc = (LookupConsumer) lcConstr.newInstance(lcArgs);
      LookupAlgorithm la = li.getLookupAlgorithm(dictEngine);
      LookupSpec ls = new LookupSpec(la, li, lc);

      lsSet.add(ls);
    }
    return lsSet;
  }
Example #28
0
 static {
   String vString = getVersion().replace("v", "");
   double v = 0;
   if (!vString.isEmpty()) {
     String[] array = vString.split("_");
     v = Double.parseDouble(array[0] + "." + array[1]);
   }
   try {
     Bukkit.getLogger().info("[ParticleLib] Server major/minor version: " + v);
     if (v < 1.7) {
       Bukkit.getLogger().info("[ParticleLib] Hooking into pre-Netty NMS classes");
       netty = false;
       packetClass = getNmsClass("Packet63WorldParticles");
       packetConstructor = packetClass.getConstructor();
       fields = packetClass.getDeclaredFields();
     } else {
       Bukkit.getLogger().info("[ParticleLib] Hooking into Netty NMS classes");
       packetClass = getNmsClass("PacketPlayOutWorldParticles");
       if (v < 1.8) {
         Bukkit.getLogger().info("[ParticleLib] Version is < 1.8 - using old packet constructor");
         packetConstructor =
             packetClass.getConstructor(
                 String.class,
                 float.class,
                 float.class,
                 float.class,
                 float.class,
                 float.class,
                 float.class,
                 float.class,
                 int.class);
       } else { // use the new constructor for 1.8
         Bukkit.getLogger().info("[ParticleLib] Version is >= 1.8 - using new packet constructor");
         newParticlePacketConstructor = true;
         enumParticle = (Class<Enum>) getNmsClass("EnumParticle");
         packetConstructor =
             packetClass.getDeclaredConstructor(
                 enumParticle,
                 boolean.class,
                 float.class,
                 float.class,
                 float.class,
                 float.class,
                 float.class,
                 float.class,
                 float.class,
                 int.class,
                 int[].class);
       }
     }
   } catch (Exception ex) {
     ex.printStackTrace();
     Bukkit.getLogger().severe("[ParticleLib] Failed to initialize NMS components!");
     compatible = false;
   }
 }
Example #29
0
    @Override
    Parser createComposite(
        Class<? extends Parser> parserClass,
        List<Parser> childParsers,
        Set<Class<? extends Parser>> excludeParsers,
        MimeTypes mimeTypes,
        ServiceLoader loader)
        throws InvocationTargetException, IllegalAccessException, InstantiationException {
      Parser parser = null;
      Constructor<? extends Parser> c = null;
      MediaTypeRegistry registry = mimeTypes.getMediaTypeRegistry();

      // Try the possible default and composite parser constructors
      if (parser == null) {
        try {
          c =
              parserClass.getConstructor(
                  MediaTypeRegistry.class, ServiceLoader.class, Collection.class);
          parser = c.newInstance(registry, loader, excludeParsers);
        } catch (NoSuchMethodException me) {
        }
      }
      if (parser == null) {
        try {
          c = parserClass.getConstructor(MediaTypeRegistry.class, List.class, Collection.class);
          parser = c.newInstance(registry, childParsers, excludeParsers);
        } catch (NoSuchMethodException me) {
        }
      }
      if (parser == null) {
        try {
          c = parserClass.getConstructor(MediaTypeRegistry.class, List.class);
          parser = c.newInstance(registry, childParsers);
        } catch (NoSuchMethodException me) {
        }
      }

      // Create as a Parser Decorator
      if (parser == null && ParserDecorator.class.isAssignableFrom(parserClass)) {
        try {
          CompositeParser cp = null;
          if (childParsers.size() == 1
              && excludeParsers.size() == 0
              && childParsers.get(0) instanceof CompositeParser) {
            cp = (CompositeParser) childParsers.get(0);
          } else {
            cp = new CompositeParser(registry, childParsers, excludeParsers);
          }
          c = parserClass.getConstructor(Parser.class);
          parser = c.newInstance(cp);
        } catch (NoSuchMethodException me) {
        }
      }
      return parser;
    }
Example #30
0
  private final void loadExtension(Extension ext) {
    final String id = ext.getDeclaringPluginDescriptor().getId();
    final URL url;
    try {
      // note: ".../-" match everything starting with "plugin:" + id + "!/"
      url = new URL("plugin:" + id + "!/-");
      final ClassLoader cl = ext.getDeclaringPluginDescriptor().getPluginClassLoader();
      final CodeSource cs = new CodeSource(url, (Certificate[]) null);
      final Permissions perms = new Permissions();
      codeSource2Permissions.put(cs, perms);
      // BootLogInstance.get().debug("Adding permissions for " + cs);
      final ConfigurationElement[] elems = ext.getConfigurationElements();
      final int count = elems.length;
      for (int i = 0; i < count; i++) {
        final ConfigurationElement elem = elems[i];
        final String type = elem.getAttribute("class");
        final String name = elem.getAttribute("name");
        final String actions = elem.getAttribute("actions");

        if (type != null) {
          final Object perm;
          try {
            final Class permClass = cl.loadClass(type);
            if ((name != null) && (actions != null)) {
              final Constructor c = permClass.getConstructor(NAME_ACTIONS_ARGS);
              perm = c.newInstance(new Object[] {name, actions});
            } else if (name != null) {
              final Constructor c = permClass.getConstructor(NAME_ARGS);
              perm = c.newInstance(new Object[] {name});
            } else {
              perm = permClass.newInstance();
            }
            final Permission p = (Permission) perm;
            perms.add(p);
          } catch (ClassNotFoundException ex) {
            BootLogInstance.get().error("Permission class " + type + " not found");
          } catch (InstantiationException ex) {
            BootLogInstance.get().error("Cannot instantiate permission class " + type);
          } catch (IllegalAccessException ex) {
            BootLogInstance.get().error("Illegal access to permission class " + type);
          } catch (NoSuchMethodException ex) {
            BootLogInstance.get()
                .error("Constructor not found on permission class " + type + " in plugin " + id);
          } catch (InvocationTargetException ex) {
            BootLogInstance.get().error("Error constructing permission class " + type, ex);
          } catch (ClassCastException ex) {
            BootLogInstance.get().error("Permission class " + type + " not instance of Permission");
          }
        }
      }
    } catch (MalformedURLException ex) {
      BootLogInstance.get().error("Cannot create plugin codesource", ex);
    }
  }