Пример #1
1
  private Module[] getModules(Guice guice, Class<?> testClass) {
    List<Module> result = Lists.newArrayList();
    for (Class<? extends Module> moduleClass : guice.modules()) {
      try {
        result.add(moduleClass.newInstance());
      } catch (InstantiationException e) {
        throw new TestNGException(e);
      } catch (IllegalAccessException e) {
        throw new TestNGException(e);
      }
    }
    Class<? extends IModuleFactory> factory = guice.moduleFactory();
    if (factory != IModuleFactory.class) {
      try {
        IModuleFactory factoryInstance = factory.newInstance();
        Module moduleClass = factoryInstance.createModule(m_testContext, testClass);
        if (moduleClass != null) {
          result.add(moduleClass);
        }
      } catch (InstantiationException e) {
        throw new TestNGException(e);
      } catch (IllegalAccessException e) {
        throw new TestNGException(e);
      }
    }

    return result.toArray(new Module[result.size()]);
  }
Пример #2
1
  private void showFragment(Class<?> paramClass, String paramString, boolean addToBackStack) {
    Log.d(TAG, "showFragment for " + paramClass);

    FragmentManager localFragmentManager = getSupportFragmentManager();

    Fragment localFragment = localFragmentManager.findFragmentById(R.id.fragment_container);

    if ((localFragment == null) || (!paramClass.isInstance(localFragment))) {
      try {
        Log.d(TAG, "replacing fragments");

        if (addToBackStack) {

          localFragment = (Fragment) paramClass.newInstance();
          localFragmentManager
              .beginTransaction()
              .add(R.id.fragment_container, localFragment)
              .addToBackStack("growth_stack")
              .commit();

        } else {
          localFragment = (Fragment) paramClass.newInstance();
          localFragmentManager
              .beginTransaction()
              .replace(R.id.fragment_container, localFragment)
              .commitAllowingStateLoss();
        }

      } catch (InstantiationException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
    }
  }
Пример #3
1
 public void testExtractionAndMetric()
     throws IOException, IllegalAccessException, InstantiationException {
   for (Class c : featureClasses) {
     LireFeature lireFeature = (LireFeature) c.newInstance();
     LireFeature tmpLireFeature = (LireFeature) c.newInstance();
     for (String file : testFiles) {
       System.out.println(c.getName() + ": " + file);
       BufferedImage image = ImageIO.read(new FileInputStream(testFilesPath + file));
       //                image = ImageUtils.trimWhiteSpace(image);
       lireFeature.extract(image);
       float delta = 0.0000f;
       assertEquals(lireFeature.getDistance(lireFeature), 0, delta);
       //
       // tmpLireFeature.setStringRepresentation(lireFeature.getStringRepresentation());
       //                assertEquals(lireFeature.getDistance(tmpLireFeature), 0, delta);
       tmpLireFeature.setByteArrayRepresentation(lireFeature.getByteArrayRepresentation());
       assertEquals(lireFeature.getDistance(tmpLireFeature), 0, delta);
       tmpLireFeature.setByteArrayRepresentation(
           lireFeature.getByteArrayRepresentation(),
           0,
           lireFeature.getByteArrayRepresentation().length);
       assertEquals(lireFeature.getDistance(tmpLireFeature), 0, delta);
     }
   }
 }
 @Override
 protected DATA convert(@NonNull JSONObject jsonObject) throws ConvertException {
   try {
     DATA data = null;
     if (mSingler != null) {
       String key = mSingler.primary();
       Field field = mAnnotationMap.get(key);
       if (field == null) {
         throw new RuntimeException("Primary key must be existed and be annotated by Property.");
       }
       Object index = ReflectUtils.getValueFromField(jsonObject, key, field);
       data = SingleData.obtain(mDataClazz, index);
       if (data == null) {
         data = mDataClazz.newInstance();
         SingleData.updateData(mDataClazz, index, data);
       }
     }
     if (data == null) {
       data = mDataClazz.newInstance();
     }
     for (Map.Entry<String, Field> entry : mAnnotationMap.entrySet()) {
       Field field = entry.getValue();
       String key = entry.getKey();
       Object value = ReflectUtils.getValueFromField(jsonObject, key, field);
       if (value != null) {
         ReflectUtils.setValue(data, field, value);
       }
     }
     return data;
   } catch (InstantiationException e) {
     throw new ConvertException(e);
   } catch (IllegalAccessException e) {
     throw new ConvertException(e);
   }
 }
 private void process(FixtureConfig fixtureConfig) {
   log.debug("Processing " + fixtureConfig);
   String sourceClassStr = fixtureConfig.getSourceClass();
   String sourceProcessorClassStr = fixtureConfig.getSourceProcessorClass();
   try {
     Class<?> sourceClassInst = Class.forName(sourceClassStr);
     IStatsSource source = (IStatsSource) sourceClassInst.newInstance();
     Class<?> sourceProcClassInst = Class.forName(sourceProcessorClassStr);
     IStatsProcessor sourceProcessor = (IStatsProcessor) sourceProcClassInst.newInstance();
     sourceProcessor.process(source);
     List<FixtureDTO> fixtures = sourceProcessor.getFixtures();
     Collections.sort(fixtures, new FootballAPIComparator());
     for (FixtureDTO fixtureDTO : fixtures) {
       Fixture match = fixtureRepo.findByMatchId(fixtureDTO.getMatchId());
       if (match != null) {
         log.debug("Found same match. Updating the match id : [ " + match.getId() + " ]");
         fixtureDTO.setId(match.getId());
       } else {
         log.debug("Found new fixture. Creating a new match [ " + fixtureDTO + " ]");
       }
       fixtureRepo.save(fixtureMapper.fixtureDTOToFixture(fixtureDTO));
     }
   } catch (Exception e) {
     log.error("Error.. ", e);
   }
 }
Пример #6
1
 public T instance() {
   T singletonInstancePerThread = null;
   // use weak reference to prevent cyclic reference during GC
   WeakReference<T> ref = (WeakReference<T>) perThreadCache.get();
   // singletonInstancePerThread=perThreadCache.get();
   // if (singletonInstancePerThread==null) {
   if (ref == null || ref.get() == null) {
     Class<T> clazz = null;
     try {
       clazz =
           (Class<T>) Thread.currentThread().getContextClassLoader().loadClass(singletonClassName);
       singletonInstancePerThread = clazz.newInstance();
     } catch (Exception ignore) {
       try {
         clazz = (Class<T>) Class.forName(singletonClassName);
         singletonInstancePerThread = clazz.newInstance();
       } catch (Exception ignore2) {
       }
     }
     perThreadCache.set(new WeakReference<T>(singletonInstancePerThread));
   } else {
     singletonInstancePerThread = ref.get();
   }
   return singletonInstancePerThread;
 }
Пример #7
0
  public static synchronized List<AgentSelector> getAvailableAgentSelectors() {
    List<AgentSelector> answer = new ArrayList<AgentSelector>();
    // First, add in built-in list of algorithms.
    for (Class newClass : getBuiltInAgentSelectorClasses()) {
      try {
        AgentSelector algorithm = (AgentSelector) newClass.newInstance();
        answer.add(algorithm);
      } catch (Exception e) {
        Log.error(e.getMessage(), e);
      }
    }

    // Now get custom algorithms.
    List<String> classNames = JiveGlobals.getProperties("agentSelector.classes");
    for (String className : classNames) {
      install_algorithm:
      try {
        Class algorithmClass = loadClass(className);
        // Make sure that the intercepter isn't already installed.
        for (AgentSelector agentSelector : answer) {
          if (algorithmClass.equals(agentSelector.getClass())) {
            break install_algorithm;
          }
        }
        AgentSelector algorithm = (AgentSelector) algorithmClass.newInstance();
        answer.add(algorithm);
      } catch (Exception e) {
        Log.error(e.getMessage(), e);
      }
    }
    return answer;
  }
  public ClassLoaderTestDAO(SessionFactory factory, TransactionManager tm) throws Exception {
    this.sessionFactory = factory;
    this.tm = tm;

    acctClass =
        Thread.currentThread()
            .getContextClassLoader()
            .loadClass(getClass().getPackage().getName() + ".Account");
    holderClass =
        Thread.currentThread()
            .getContextClassLoader()
            .loadClass(getClass().getPackage().getName() + ".AccountHolder");
    setId = acctClass.getMethod("setId", Integer.class);
    setBalance = acctClass.getMethod("setBalance", Integer.class);
    setBranch = acctClass.getMethod("setBranch", String.class);
    setHolder = acctClass.getMethod("setAccountHolder", holderClass);

    setName = holderClass.getMethod("setLastName", String.class);
    setSsn = holderClass.getMethod("setSsn", String.class);

    smith = holderClass.newInstance();
    setName.invoke(smith, "Smith");
    setSsn.invoke(smith, "1000");

    jones = holderClass.newInstance();
    setName.invoke(jones, "Jones");
    setSsn.invoke(jones, "2000");

    barney = holderClass.newInstance();
    setName.invoke(barney, "Barney");
    setSsn.invoke(barney, "3000");
  }
Пример #9
0
  /**
   * Returns an action instance to be used with this request. Mentawai creates a new action instance
   * for each request. You can extend ActionConfig and override this class to integrate Mentawai
   * with other IoC containers, that may want to create the action themselves.
   *
   * @return The action instance to use for the request.
   */
  public Action getAction() {

    Container container = ApplicationManager.getContainer();

    if (Action.class.isAssignableFrom(actionClass)) {

      // first try to get action from container...

      try {

        Action a = container.construct(actionClass);

        if (a != null) return a;

      } catch (Exception e) {
        // ignore and try below...
      }

      try {

        return (Action) actionClass.newInstance();

      } catch (Exception e) {

        e.printStackTrace();
      }

    } else {

      try {

        // first try to get action from container...

        Object pojo = null;

        try {

          pojo = container.construct(actionClass);

        } catch (Exception e) {
          // ignore and try below...
        }

        if (pojo == null) {

          pojo = actionClass.newInstance();
        }

        PojoAction pojoAction = new PojoAction(pojo);

        return pojoAction;

      } catch (Exception e) {

        e.printStackTrace();
      }
    }

    return null;
  }
Пример #10
0
  @SuppressWarnings("unchecked")
  private static void initPartitioners() {
    String groupPartClass =
        System.getProperty(
            "tribu.distributed.GroupPartitionerClass",
            "org.deuce.distribution.replication.partitioner.group.RandomGroupPartitioner");
    String dataPartClass =
        System.getProperty(
            "tribu.distributed.DataPartitionerClass",
            "org.deuce.distribution.replication.partitioner.data.SimpleDataPartitioner");
    String gClass =
        System.getProperty(
            "tribu.distributed.GroupClass",
            "org.deuce.distribution.replication.group.PartialReplicationGroup");

    try {
      Class<? extends GroupPartitioner> groupPart =
          (Class<? extends GroupPartitioner>) Class.forName(groupPartClass);
      groupPartitioner = groupPart.newInstance();

      Class<? extends DataPartitioner> dataPart =
          (Class<? extends DataPartitioner>) Class.forName(dataPartClass);
      dataPartitioner = dataPart.newInstance();

      groupClass = (Class<? extends Group>) Class.forName(gClass);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(-1);
    }
  }
 private static LanguageSupport tryInstantiate(String className) {
   LanguageSupport instance = null;
   if (className != null && className.length() > 0) {
     try {
       int separator = className.indexOf(':');
       Bundle bundle = null;
       if (separator == -1) {
         JavaCore javaCore = JavaCore.getJavaCore();
         if (javaCore == null) {
           Class clazz = Class.forName(className);
           return (LanguageSupport) clazz.newInstance();
         } else {
           bundle = javaCore.getBundle();
         }
       } else {
         String bundleName = className.substring(0, separator);
         className = className.substring(separator + 1);
         bundle = Platform.getBundle(bundleName);
       }
       Class c = bundle.loadClass(className);
       instance = (LanguageSupport) c.newInstance();
     } catch (ClassNotFoundException e) {
       log(e);
     } catch (InstantiationException e) {
       log(e);
     } catch (IllegalAccessException e) {
       log(e);
     } catch (ClassCastException e) {
       log(e);
     }
   }
   return instance;
 }
  /* goodB2G2() - use badsource and goodsink by reversing statements in second if  */
  private void goodB2G2() throws Throwable {
    String data;
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (IO.static_t) {
      Logger log_bad = Logger.getLogger("local-logger");
      data = ""; /* init data */
      File f = new File("C:\\data.txt");
      BufferedReader buffread = null;
      FileReader fread = null;
      try {
        /* read string from file into data */
        fread = new FileReader(f);
        buffread = new BufferedReader(fread);
        data = buffread.readLine(); // This will be reading the first "line" of the file, which
        // could be very long if there are little or no newlines in the file\
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } catch (NumberFormatException nfe) {
        log_bad.warning("Error with number parsing");
      } finally {
        /* clean up stream reading objects */
        try {
          if (buffread != null) {
            buffread.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        } finally {
          try {
            if (fread != null) {
              fread.close();
            }
          } catch (IOException ioe) {
            log_bad.warning("Error closing fread");
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      data = "Testing.test";
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (IO.static_t) {
      if (!data.equals("Testing.test")
          && /* FIX: classname must be one of 2 values */ !data.equals("Test.test")) {
        return;
      }
      Class<?> c = Class.forName(data);
      Object instance = c.newInstance();
      IO.writeLine(instance.toString());
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      Class<?> c = Class.forName(data); /* FLAW: loading arbitrary class */
      Object instance = c.newInstance();

      IO.writeLine(instance.toString());
    }
  }
  // this GwtCreateHandler has been introduced to make possible the
  // instanciation of abstract classes
  // that gwt-test-utils doesn't patch right now
  public Object create(Class<?> classLiteral) throws Exception {
    if (classLiteral.isAnnotation()
        || classLiteral.isArray()
        || classLiteral.isEnum()
        || classLiteral.isInterface()
        || !Modifier.isAbstract(classLiteral.getModifiers())) {
      return null;
    }

    Class<?> newClass = cache.get(classLiteral);

    if (newClass != null) {
      return newClass.newInstance();
    }

    CtClass ctClass = GwtClassPool.getCtClass(classLiteral);
    CtClass subClass = GwtClassPool.get().makeClass(classLiteral.getCanonicalName() + "SubClass");

    subClass.setSuperclass(ctClass);

    for (CtMethod m : ctClass.getDeclaredMethods()) {
      if (javassist.Modifier.isAbstract(m.getModifiers())) {
        CtMethod copy = new CtMethod(m, subClass, null);
        subClass.addMethod(copy);
      }
    }

    GwtPatcherUtils.patch(subClass, null);

    newClass = subClass.toClass(GwtClassLoader.get(), null);
    cache.put(classLiteral, newClass);

    return newClass.newInstance();
  }
Пример #14
0
  /**
   * Adds the value to the collection specified by the key. If there is not a collection for the
   * given key, a new collection is created and added to the hash.
   *
   * @param key The key whose collection we will add value to.
   * @param value The value to be added.
   * @return the collection containing value and all other items associated with the key.
   */
  @SuppressWarnings("unchecked")
  public Collection<V> put(K key, V value) {
    Pair<Collection<V>, O> objectPair = map.get(key);
    if (objectPair == null) {
      try {
        Collection<V> items;
        if (isSynchronized) {
          items = Collections.synchronizedCollection(collectionType.newInstance());
        } else {
          items = collectionType.newInstance();
        }

        objectPair = new Pair(items, plusProvider.newObject());
        map.put(key, objectPair);
      } catch (InstantiationException ex) {
        ex.printStackTrace();
        return null;
      } catch (IllegalAccessException ex) {
        ex.printStackTrace();
        return null;
      }
    }
    objectPair.getFirst().add(value);
    return objectPair.getFirst();
  }
  static VoldemortFilter getFilterFromRequest(
      VAdminProto.VoldemortFilter request,
      VoldemortConfig voldemortConfig,
      NetworkClassLoader networkClassLoader) {
    VoldemortFilter filter = null;

    byte[] classBytes = ProtoUtils.decodeBytes(request.getData()).get();
    String className = request.getName();
    logger.debug("Attempt to load VoldemortFilter class:" + className);

    try {
      if (voldemortConfig.isNetworkClassLoaderEnabled()) {
        // TODO: network class loader was throwing NoClassDefFound for
        // voldemort.server package classes, Need testing and fixes
        logger.warn("NetworkLoader is experimental and should not be used for now.");

        Class<?> cl = networkClassLoader.loadClass(className, classBytes, 0, classBytes.length);
        filter = (VoldemortFilter) cl.newInstance();
      } else {
        Class<?> cl = Thread.currentThread().getContextClassLoader().loadClass(className);
        filter = (VoldemortFilter) cl.newInstance();
      }
    } catch (Exception e) {
      throw new VoldemortException("Failed to load and instantiate the filter class", e);
    }

    return filter;
  }
Пример #16
0
  /**
   * Returns a new instance of the property editor for the specified class.
   *
   * @param editedClass the class that the property editor will edit.
   * @return a PropertyEditor instance that can edit the specified class.
   */
  public static PropertyEditor findEditor(Class<?> editedClass) {
    try {
      Class found = (Class) editors.get(editedClass);
      if (found != null) {
        return (PropertyEditor) found.newInstance();
      }

      ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

      try {
        found = Class.forName(editedClass.getName() + "Editor", true, contextClassLoader);
        registerEditor(editedClass, found);
        return (PropertyEditor) found.newInstance();
      } catch (ClassNotFoundException E) {
      }

      String appendName = "." + ClassHelper.getTruncatedClassName(editedClass) + "Editor";
      synchronized (editorSearchPath) {
        for (int i = 0; i < editorSearchPath.length; i++) {
          try {
            found = Class.forName(editorSearchPath[i] + appendName, true, contextClassLoader);
            registerEditor(editedClass, found);
            return (PropertyEditor) found.newInstance();
          } catch (ClassNotFoundException E) {
          }
        }
      }
    } catch (InstantiationException E) {
    } catch (IllegalAccessException E) {
    }

    return null;
  }
Пример #17
0
  protected static void loadAllPlugins(final ThresHolder thresholds) {
    for (Class<?> stat : new PluginManager<LocusMetric>(LocusMetric.class).getPlugins()) {
      try {
        final LocusMetric stats = (LocusMetric) stat.newInstance();
        stats.initialize(thresholds);
        thresholds.locusMetricList.add(stats);
      } catch (Exception e) {
        throw new DynamicClassResolutionException(stat, e);
      }
    }

    for (Class<?> stat : new PluginManager<SampleMetric>(SampleMetric.class).getPlugins()) {
      try {
        final SampleMetric stats = (SampleMetric) stat.newInstance();
        stats.initialize(thresholds);
        thresholds.sampleMetricList.add(stats);
      } catch (Exception e) {
        throw new DynamicClassResolutionException(stat, e);
      }
    }

    for (Class<?> stat : new PluginManager<IntervalMetric>(IntervalMetric.class).getPlugins()) {
      try {
        final IntervalMetric stats = (IntervalMetric) stat.newInstance();
        stats.initialize(thresholds);
        thresholds.intervalMetricList.add(stats);
      } catch (Exception e) {
        throw new DynamicClassResolutionException(stat, e);
      }
    }
  }
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "loadClass",
      args = {java.lang.String.class, boolean.class})
  public void test_loadClassLjava_lang_StringLZ()
      throws IllegalAccessException, InstantiationException, ClassNotFoundException {
    PackageClassLoader pcl = new PackageClassLoader(getClass().getClassLoader());
    String className = getClass().getPackage().getName() + ".A";

    Class<?> clazz = pcl.loadClass(className, false);
    assertEquals(className, clazz.getName());
    assertNotNull(clazz.newInstance());

    clazz = pcl.loadClass(className, true);
    assertEquals(className, clazz.getName());
    assertNotNull(clazz.newInstance());

    try {
      clazz = pcl.loadClass("UnknownClass", false);
      assertEquals("TestClass", clazz.getName());
      fail("ClassNotFoundException was not thrown.");
    } catch (ClassNotFoundException e) {
      // expected
    }
  }
Пример #19
0
  public void testLocalExtract(ArrayList<String> images)
      throws IOException, IllegalAccessException, InstantiationException {
    LocalFeatureExtractor localFeatureExtractor = localFeatureClass.newInstance();
    LocalDocumentBuilder localDocumentBuilder = new LocalDocumentBuilder();
    AbstractAggregator aggregator = aggregatorClass.newInstance();

    Cluster[] codebook32 = Cluster.readClusters(codebookPath + "CvSURF32");
    Cluster[] codebook128 = Cluster.readClusters(codebookPath + "CvSURF128");

    BufferedImage image;
    double[] featureVector;
    long ms, totalTime = 0;
    for (String path : images) {
      image = ImageIO.read(new FileInputStream(path));
      ms = System.currentTimeMillis();
      localDocumentBuilder.extractLocalFeatures(image, localFeatureExtractor);
      aggregator.createVectorRepresentation(localFeatureExtractor.getFeatures(), codebook32);
      ms = System.currentTimeMillis() - ms;
      totalTime += ms;
      featureVector = aggregator.getVectorRepresentation();

      System.out.println(
          String.format("%.2f", (double) ms)
              + " ms. ~ "
              + path.substring(path.lastIndexOf('\\') + 1)
              + " ~ "
              + Arrays.toString(featureVector));
    }
    System.out.println(
        localFeatureExtractor.getClassOfFeatures().newInstance().getFeatureName()
            + " "
            + String.format("%.2f", totalTime / (double) images.size())
            + " ms each.");
    System.out.println();
  }
 /**
  * Return all instances of an entity that match the given criteria. Use whereClause to specify
  * condition, using reqular SQL syntax for WHERE clause.
  *
  * <p>For example selecting all JOHNs born in 2001 from USERS table may look like:
  *
  * <pre>
  * users.find(Users.class, "NAME='?' and YEAR=?", new String[] {"John", "2001"});
  * </pre>
  *
  * @param <T> Any ActiveRecordBase class.
  * @param type The class of the entities to return.
  * @param whereClause The condition to match (Don't include "where").
  * @param whereArgs The arguments to replace "?" with.
  * @return A generic list of all matching entities.
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  * @throws InstantiationException
  */
 public <T extends ActiveRecordBase> List<T> find(
     Class<T> type, String whereClause, String[] whereArgs) throws ActiveRecordException {
   if (m_Database == null) throw new ActiveRecordException("Set database first");
   T entity = null;
   try {
     entity = type.newInstance();
   } catch (IllegalAccessException e1) {
     throw new ActiveRecordException(e1.getLocalizedMessage());
   } catch (InstantiationException e1) {
     throw new ActiveRecordException(e1.getLocalizedMessage());
   }
   List<T> toRet = new ArrayList<T>();
   Cursor c = m_Database.query(entity.getTableName(), null, whereClause, whereArgs);
   try {
     while (c.moveToNext()) {
       entity = s_EntitiesMap.get(type, c.getLong(c.getColumnIndex("_id")));
       if (entity == null) {
         entity = type.newInstance();
         entity.m_Database = m_Database;
         entity.m_NeedsInsert = false;
         entity.inflate(c);
       }
       toRet.add(entity);
     }
   } catch (IllegalAccessException e) {
     throw new ActiveRecordException(e.getLocalizedMessage());
   } catch (InstantiationException e) {
     throw new ActiveRecordException(e.getLocalizedMessage());
   } finally {
     c.close();
   }
   return toRet;
 }
 /**
  * Abre el Caso de Uso e inicia su ejecución para las ventanas
  * VentanaActualizarTiposGenericoContable y VentanaActualizarTiposGenerico
  *
  * @param nombreClaseVentana Nombre de la Clase de la Ventana que se va a mostrar.
  * @param nombreClaseGenerica Nombre de la Clase que se va a actualizar.
  * @param titulo Nombre de la parte del título que indica actividad (no poner todo completo, solo
  *     lo que se está actualizando). La ventana mostrará: "Actualizar " + titulo.
  * @return Referencia a la ventana creada.
  */
 public JInternalFrame iniciarCUGenerico(Class claseVentana, Class claseGenerica, String titulo) {
   JInternalFrame ventana = null;
   try {
     // Instanciar el CU.
     ventana = (JInternalFrame) claseVentana.newInstance();
     VentanaMenuPrincipal.getInstancia().getPanelPrincipal().add(ventana);
     // Establece la posicion de la ventana.
     generarPosicionVentana();
     ventana.setLocation(getPosicionXVentana(), getPosicionYVentana());
     // Muestra la ventana.
     ventana.setVisible(true);
     // Intenta establecer a la ventana como seleccionada,
     // Si no puede, lanza imprime la excepcion en la salida estandar.
     try {
       ventana.setSelected(true);
     } catch (java.beans.PropertyVetoException e) {
       log.warn("Error al establecer ventana como seleccionada.", e);
     }
     InterfazTipoGenerico tg = (InterfazTipoGenerico) claseGenerica.newInstance();
     ((VentanaActualizarTipos) ventana).opcionActualizarTipos(titulo, tg);
     log.debug(
         "Iniciado CU Genérico: "
             + claseVentana.getName()
             + " - Para la Clase: "
             + claseGenerica.getName());
   } catch (InstantiationException ex) {
     log.error("No se pudo instanciar la clase", ex);
   } catch (IllegalAccessException ex) {
     log.error("No se pudo instanciar la clase", ex);
   }
   return ventana;
 }
Пример #22
0
  private void startStores(Properties properties) {
    String definitionStoreClassName = properties.getProperty(DEFINITION_STORE_CLASS);
    String contentStoreClassName = properties.getProperty(CONTENT_STORE_CLASS);

    // start definition store
    try {
      Class<?> definitionStoreClass = Class.forName(definitionStoreClassName);

      definitionStore = (MeemStoreDefinitionStore) definitionStoreClass.newInstance();
    } catch (Exception e) {
      logger.log(Level.INFO, "Exception while starting MeemStoreDefinitionStore", e);
    }

    if (definitionStore != null) definitionStore.configure(this, properties);

    //	start content store
    try {
      Class<?> contentStoreClass = Class.forName(contentStoreClassName);

      contentStore = (MeemStoreContentStore) contentStoreClass.newInstance();
    } catch (Exception e) {
      logger.log(Level.INFO, "Exception while starting MeemStoreContentStore", e);
    }

    if (contentStore != null) contentStore.configure(this, properties);
  }
Пример #23
0
  private Collection createList() throws IOException {
    Collection list = null;

    if (_type == null) list = new ArrayList();
    else if (!_type.isInterface()) {
      try {
        list = (Collection) _type.newInstance();
      } catch (Exception e) {
      }
    }

    if (list != null) {
    } else if (SortedSet.class.isAssignableFrom(_type)) list = new TreeSet();
    else if (Set.class.isAssignableFrom(_type)) list = new HashSet();
    else if (List.class.isAssignableFrom(_type)) list = new ArrayList();
    else if (Collection.class.isAssignableFrom(_type)) list = new ArrayList();
    else {
      try {
        list = (Collection) _type.newInstance();
      } catch (Exception e) {
        throw new IOExceptionWrapper(e);
      }
    }

    return list;
  }
Пример #24
0
    // Generic type safety...
    private final <Z extends UDTRecord<?>> void addAddressValue(StoreQuery<?> q, Field<Z> field) throws Exception {
        Class<? extends Z> addressType = field.getType();
        Class<?> countryType = addressType.getMethod("getCountry").getReturnType();
        Class<?> streetType = addressType.getMethod("getStreet").getReturnType();

        Object country = null;
        try {
            countryType.getMethod("valueOf", String.class).invoke(countryType, "Germany");
        }
        catch (NoSuchMethodException e) {
            country = "Germany";
        }

        Object street = streetType.newInstance();
        Z address = addressType.newInstance();

        streetType.getMethod("setStreet", String.class).invoke(street, "Bahnhofstrasse");
        streetType.getMethod("setNo", String.class).invoke(street, "1");

        addressType.getMethod("setCountry", countryType).invoke(address, country);
        addressType.getMethod("setCity", String.class).invoke(address, "Calw");
        addressType.getMethod("setStreet", streetType).invoke(address, street);

        q.addValue(field, address);
    }
Пример #25
0
  private void runTest(Class<? extends Lookup> lookupClass, boolean supportsExactWeights)
      throws Exception {

    // Add all input keys.
    Lookup lookup = lookupClass.newInstance();
    TermFreq[] keys = new TermFreq[this.keys.length];
    for (int i = 0; i < keys.length; i++) keys[i] = new TermFreq(this.keys[i], i);
    lookup.build(new TermFreqArrayIterator(keys));

    // Store the suggester.
    File storeDir = TEMP_DIR;
    lookup.store(new FileOutputStream(new File(storeDir, "lookup.dat")));

    // Re-read it from disk.
    lookup = lookupClass.newInstance();
    lookup.load(new FileInputStream(new File(storeDir, "lookup.dat")));

    // Assert validity.
    Random random = random();
    long previous = Long.MIN_VALUE;
    for (TermFreq k : keys) {
      List<LookupResult> list =
          lookup.lookup(_TestUtil.bytesToCharSequence(k.term, random), false, 1);
      assertEquals(1, list.size());
      LookupResult lookupResult = list.get(0);
      assertNotNull(k.term.utf8ToString(), lookupResult.key);

      if (supportsExactWeights) {
        assertEquals(k.term.utf8ToString(), k.v, lookupResult.value);
      } else {
        assertTrue(lookupResult.value + ">=" + previous, lookupResult.value >= previous);
        previous = lookupResult.value;
      }
    }
  }
  public static void test(
      Class<? extends Uploader> uploaderClass, Class<? extends Account> accountsClass) {
    try {
      Account account = accountsClass == null ? null : accountsClass.newInstance();
      Uploader uploader;
      String name;

      SmallModule sm = uploaderClass.getAnnotation(SmallModule.class);

      Utils.init(sm.name(), account, /*username*/ null, /*password*/ null);
      if (account != null) account.login();
      else {
        System.out.println("account is null");
      }
      uploader = uploaderClass.newInstance();

      JFileChooser fileChooser = new JFileChooser();
      fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
      int result = fileChooser.showOpenDialog(fileChooser);
      File selectedFile = null;
      if (result == JFileChooser.APPROVE_OPTION) {
        selectedFile = fileChooser.getSelectedFile();
        uploader.setFile(selectedFile);
      } else {
        uploader.setFile(Utils.getMeATestFile());
      }

      uploader.run();
    } catch (Exception a) {
      throw new RuntimeException(a);
    }
  }
Пример #27
0
  /**
   * Creates a Scriptella Driver using specified class.
   *
   * <p>If class is a {@link Driver} {@link GenericDriver JDBC Bridge} is used.
   *
   * <p>To be successfully instantiated the driver class must implement {@link ScriptellaDriver}
   * class and has no-arg public constructor.
   *
   * @param drvClass driver class.
   * @return Scriptella Driver
   */
  @SuppressWarnings("unchecked")
  public static ScriptellaDriver getDriver(Class drvClass) {
    if (Driver.class.isAssignableFrom(drvClass)) {
      // We must load JDBC driver using the same classloader as drvClass
      try {

        ClassLoader drvClassLoader = drvClass.getClassLoader();
        if (drvClassLoader == null) { // if boot classloader is used,
          // load scriptella driver using the class loader for this class.
          drvClassLoader = DriverFactory.class.getClassLoader();
        }
        Class<?> cl = Class.forName("scriptella.jdbc.GenericDriver", true, drvClassLoader);
        return (ScriptellaDriver) cl.newInstance();
      } catch (Exception e) {
        throw new IllegalStateException("Unable to instantiate JDBC driver for " + drvClass, e);
      }
    } else if (ScriptellaDriver.class.isAssignableFrom(drvClass)) {
      try {
        return (ScriptellaDriver) drvClass.newInstance();
      } catch (Exception e) {
        throw new IllegalStateException("Unable to instantiate driver for " + drvClass, e);
      }

    } else {
      throw new IllegalArgumentException(
          "Class " + drvClass + " is not a scriptella compatible driver.");
    }
  }
Пример #28
0
  public Action compileAndGetInstance(
      CompilerContext context, String actionName, final CompiledST template) {
    try {
      if (template.code instanceof Compiler.Block
          && ((Compiler.Block) template.code).statements.size() == 0) {
        if (this.noop != null) {
          return this.noop;
        } else {
          Class<Action> action = compile(context, actionName, template);
          // instantiates this compiled expression class...
          this.noop = (Action) action.newInstance();
          return this.noop;
        }
      }

      Class<Action> action = compile(context, actionName, template);
      // instantiates this compiled expression class...
      Action expr = (Action) action.newInstance();
      return expr;
    } catch (InstantiationException e) {
      log.error(e);
      throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
      log.error(e);
      throw new RuntimeException(e);
    }
  }
Пример #29
0
  static {
    // check if we have JAI and or ImageIO

    // if these classes are here, then the runtine environment has
    // access to JAI and the JAI ImageI/O toolbox.
    boolean available = true;
    try {
      Class.forName("javax.media.jai.JAI");
    } catch (Throwable e) {
      if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
      available = false;
    }
    JAIAvailable = available;

    available = true;
    try {
      Class<?> clazz = Class.forName("com.sun.media.imageioimpl.plugins.tiff.TIFFImageReaderSpi");
      readerSpi = (ImageReaderSpi) clazz.newInstance();
      Class<?> clazz1 = Class.forName("com.sun.media.imageioimpl.plugins.tiff.TIFFImageWriterSpi");
      writerSpi = (ImageWriterSpi) clazz1.newInstance();

    } catch (Throwable e) {
      if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
      readerSpi = null;
      writerSpi = null;
      available = false;
    }
    TiffAvailable = available;

    final HashSet<String> tempSet = new HashSet<String>(2);
    tempSet.add(".tfw");
    tempSet.add(".tiffw");
    tempSet.add(".wld");
    TIFF_WORLD_FILE_EXT = Collections.unmodifiableSet(tempSet);
  }
  /** Create onTouchHandler by reflection depending on mulitouch capability of device */
  @SuppressWarnings("unchecked")
  private void InitOnTouchHandler() {
    ClassLoader classLoader = ImageViewZoom.class.getClassLoader();
    Class<OnTouchInterface> dynamicClass;
    // check if there is multitouch
    try {
      Class<?> eventClass = MotionEvent.class;
      eventClass.getMethod("getPointerCount");
      dynamicClass =
          (Class<OnTouchInterface>)
              classLoader.loadClass("com.rogicrew.imagezoom.ontouch.OnTouchMulti");
      onTouchHandler = dynamicClass.newInstance();
      onTouchHandler.init();
    } catch (NoSuchMethodException nsme) { // not exist
    } catch (Exception e) {
    }

    if (onTouchHandler == null) { // if multitouch handler not created create simple one
      try {
        dynamicClass =
            (Class<OnTouchInterface>)
                classLoader.loadClass("com.rogicrew.imagezoom.ontouch.OnTouchSingle");
        onTouchHandler = dynamicClass.newInstance();
        onTouchHandler.init();
      } catch (Exception e) {
      }
    }
  }