Example #1
0
  public static void invokeSetMethod(Object obj, String prop, String value)
      throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Class cl = obj.getClass();
    // change first letter to uppercase
    String setMeth = "set" + prop.substring(0, 1).toUpperCase() + prop.substring(1);

    // try string method
    try {
      Class[] cldef = {String.class};
      Method meth = cl.getMethod(setMeth, cldef);
      Object[] params = {value};
      meth.invoke(obj, params);
      return;
    } catch (NoSuchMethodException ex) {
      try {
        // try int method
        Class[] cldef = {Integer.TYPE};
        Method meth = cl.getMethod(setMeth, cldef);
        Object[] params = {Integer.valueOf(value)};
        meth.invoke(obj, params);
        return;
      } catch (NoSuchMethodException nsmex) {
        // try boolean method
        Class[] cldef = {Boolean.TYPE};
        Method meth = cl.getMethod(setMeth, cldef);
        Object[] params = {Boolean.valueOf(value)};
        meth.invoke(obj, params);
        return;
      }
    }
  }
Example #2
0
 /**
  * Should parse a string to select, initialize, and return the user interface selected
  *
  * @param optionValue the string to parse
  * @return the user interface to use
  */
 private void selectUI(String optionValue) {
   try {
     Class<?> cls = Class.forName("com.kpro.ui." + optionValue);
     userInterface = (UserIO) cls.newInstance();
   } catch (Exception e) {
     System.err.println("Selected UserIO not found");
   }
 }
Example #3
0
 private void guessClassReference(TypedValues list, String name) {
   try {
     Class<?> type = Class.forName(fixPotentialArrayName(name));
     list.add(new TypedValue(type.getClass(), type));
   } catch (ClassNotFoundException y) {
     _logger.fine(name + " looked like a class reference but is not");
   }
 }
Example #4
0
 private static final <T> T getInstance(final String className, final T defaultValue) {
   try {
     final Class aClass = ClassLoader.getSystemClassLoader().loadClass(className);
     return (T) aClass.newInstance();
   } catch (final Exception e) {
     return defaultValue;
   }
 }
Example #5
0
 protected Object instantiate() throws Exception {
   try {
     if (_constructor != null) return _constructor.newInstance(_constructorArgs);
     else return _type.newInstance();
   } catch (Exception e) {
     throw new HessianProtocolException("'" + _type.getName() + "' could not be instantiated", e);
   }
 }
Example #6
0
 protected static Object newInstance(String name) {
   try {
     Class clazz = Class.forName(name);
     return clazz.newInstance();
   } catch (Exception e) {
     Logger().severe("Cannot extatiate class " + name + ": " + e.getMessage());
     return null;
   }
 }
Example #7
0
  /** Creates a map of the classes fields. */
  protected HashMap getFieldMap(Class cl) {
    HashMap fieldMap = new HashMap();

    for (; cl != null; cl = cl.getSuperclass()) {
      Field[] fields = cl.getDeclaredFields();
      for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];

        if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers()))
          continue;
        else if (fieldMap.get(field.getName()) != null) continue;

        // XXX: could parameterize the handler to only deal with public
        try {
          field.setAccessible(true);
        } catch (Throwable e) {
          e.printStackTrace();
        }

        Class type = field.getType();
        FieldDeserializer deser;

        if (String.class.equals(type)) deser = new StringFieldDeserializer(field);
        else if (byte.class.equals(type)) {
          deser = new ByteFieldDeserializer(field);
        } else if (short.class.equals(type)) {
          deser = new ShortFieldDeserializer(field);
        } else if (int.class.equals(type)) {
          deser = new IntFieldDeserializer(field);
        } else if (long.class.equals(type)) {
          deser = new LongFieldDeserializer(field);
        } else if (float.class.equals(type)) {
          deser = new FloatFieldDeserializer(field);
        } else if (double.class.equals(type)) {
          deser = new DoubleFieldDeserializer(field);
        } else if (boolean.class.equals(type)) {
          deser = new BooleanFieldDeserializer(field);
        } else if (java.sql.Date.class.equals(type)) {
          deser = new SqlDateFieldDeserializer(field);
        } else if (java.sql.Timestamp.class.equals(type)) {
          deser = new SqlTimestampFieldDeserializer(field);
        } else if (java.sql.Time.class.equals(type)) {
          deser = new SqlTimeFieldDeserializer(field);
        } else {
          deser = new ObjectFieldDeserializer(field);
        }

        fieldMap.put(field.getName(), deser);
      }
    }

    return fieldMap;
  }
Example #8
0
 /**
  * Starts the NetworkR specificied by the configuration settings.
  *
  * @throws ClassNotFoundException
  * @throws InvocationTargetException
  * @throws IllegalAccessException
  * @throws InstantiationException
  * @throws SecurityException
  * @throws IllegalArgumentException
  */
 private void startNetwork()
     throws ClassNotFoundException, IllegalArgumentException, SecurityException,
         InstantiationException, IllegalAccessException, InvocationTargetException {
   // System.err.println("startnetwork called");
   Class<?> cls = Class.forName("com.kpro.datastorage." + genProps.getProperty("NetworkRType"));
   if (cls == null) {
     System.err.println("NetworkRType incorrect- null in Gio.startNetwork()");
   }
   nr =
       (NetworkR)
           cls.getDeclaredConstructors()[0].newInstance(genProps.getProperty("NetworkROptions"));
   // System.err.println("nr in startNetwork="+nr);
 }
Example #9
0
 /**
  * ************************************************************************ Start Java Process
  * Class. instanciate the class implementing the interface ProcessCall. The class can be a
  * Server/Client class (when in Package org compiere.process or org.compiere.model) or a client
  * only class (e.g. in org.compiere.report)
  *
  * @return true if success
  */
 private boolean startProcess() {
   log.fine(m_pi.toString());
   boolean started = false;
   if (DB.isRemoteProcess()) {
     Server server = CConnection.get().getServer();
     try {
       if (server != null) { // 	See ServerBean
         m_pi = server.process(m_wscctx, m_pi);
         log.finest("server => " + m_pi);
         started = true;
       }
     } catch (UndeclaredThrowableException ex) {
       Throwable cause = ex.getCause();
       if (cause != null) {
         if (cause instanceof InvalidClassException)
           log.log(
               Level.SEVERE, "Version Server <> Client: " + cause.toString() + " - " + m_pi, ex);
         else
           log.log(Level.SEVERE, "AppsServer error(1b): " + cause.toString() + " - " + m_pi, ex);
       } else log.log(Level.SEVERE, " AppsServer error(1) - " + m_pi, ex);
       started = false;
     } catch (Exception ex) {
       Throwable cause = ex.getCause();
       if (cause == null) cause = ex;
       log.log(Level.SEVERE, "AppsServer error - " + m_pi, cause);
       started = false;
     }
   }
   //	Run locally
   if (!started && !m_IsServerProcess) {
     ProcessCall myObject = null;
     try {
       Class myClass = Class.forName(m_pi.getClassName());
       myObject = (ProcessCall) myClass.newInstance();
       if (myObject == null) m_pi.setSummary("No Instance for " + m_pi.getClassName(), true);
       else myObject.startProcess(m_wscctx, m_pi, m_trx);
       if (m_trx != null) {
         m_trx.commit();
         m_trx.close();
       }
     } catch (Exception e) {
       if (m_trx != null) {
         m_trx.rollback();
         m_trx.close();
       }
       m_pi.setSummary("Error starting Class " + m_pi.getClassName(), true);
       log.log(Level.SEVERE, m_pi.getClassName(), e);
     }
   }
   return !m_pi.isError();
 } //  startProcess
Example #10
0
  /** Returns the readResolve method */
  protected Method getReadResolve(Class cl) {
    for (; cl != null; cl = cl.getSuperclass()) {
      Method[] methods = cl.getDeclaredMethods();

      for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];

        if (method.getName().equals("readResolve") && method.getParameterTypes().length == 0)
          return method;
      }
    }

    return null;
  }
Example #11
0
  static {
    if (enableInstructionDecodeViewer
        && ((instructionListenerClassName == null) || instructionListenerClassName.equals(""))) {
      instructionListenerClassName = InstructionViewer.class.getName();
    }

    if ((instructionListenerClassName != null) && !instructionListenerClassName.equals("")) {
      try {
        final Class<?> instructionListenerClass = Class.forName(instructionListenerClassName);
        instructionListener = (InstructionListener) instructionListenerClass.newInstance();
      } catch (final ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (final InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (final IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    if (dumpFlags) {
      System.out.println(propPkgName + ".executionMode{GPU|ACC|CPU|JTP|SEQ}=" + executionMode);
      System.out.println(
          propPkgName + ".logLevel{OFF|FINEST|FINER|FINE|WARNING|SEVERE|ALL}=" + logger.getLevel());
      System.out.println(propPkgName + ".enableProfiling{true|false}=" + enableProfiling);
      System.out.println(propPkgName + ".enableProfilingCSV{true|false}=" + enableProfilingCSV);
      System.out.println(propPkgName + ".enableVerboseJNI{true|false}=" + enableVerboseJNI);
      System.out.println(
          propPkgName
              + ".enableVerboseJNIOpenCLResourceTracking{true|false}="
              + enableVerboseJNIOpenCLResourceTracking);
      System.out.println(
          propPkgName + ".enableShowGeneratedOpenCL{true|false}=" + enableShowGeneratedOpenCL);
      System.out.println(
          propPkgName
              + ".enableExecutionModeReporting{true|false}="
              + enableExecutionModeReporting);
      System.out.println(
          propPkgName
              + ".enableInstructionDecodeViewer{true|false}="
              + enableInstructionDecodeViewer);
      System.out.println(
          propPkgName
              + ".instructionListenerClassName{<class name which extends com.amd.aparapi.Config.InstructionListener>}="
              + instructionListenerClassName);
    }
  }
Example #12
0
 public static void executeMethodClass(
     String pathToJar,
     String pkg,
     String classToGet,
     String methodName,
     String pathToFile,
     long logIdSyncMin,
     long logIdSyncMax)
     throws IOException, ClassNotFoundException, SecurityException, InstantiationException,
         IllegalAccessException, NoSuchMethodException, IllegalArgumentException,
         InvocationTargetException {
   Class<?> c = getClassFromJar(pathToJar, pkg, classToGet);
   Method method = c.getDeclaredMethod(methodName, String.class, long.class, long.class);
   method.invoke(null, pathToFile, logIdSyncMin, logIdSyncMax);
 }
  private void initDriverList() {
    try {
      Thread thread = Thread.currentThread();
      ClassLoader loader = thread.getContextClassLoader();

      Enumeration iter = loader.getResources("META-INF/services/java.sql.Driver");
      while (iter.hasMoreElements()) {
        URL url = (URL) iter.nextElement();

        ReadStream is = null;
        try {
          is = Vfs.lookup(url.toString()).openRead();

          String filename;

          while ((filename = is.readLine()) != null) {
            int p = filename.indexOf('#');

            if (p >= 0) filename = filename.substring(0, p);

            filename = filename.trim();
            if (filename.length() == 0) continue;

            try {
              Class cl = Class.forName(filename, false, loader);
              Driver driver = null;

              if (Driver.class.isAssignableFrom(cl)) driver = (Driver) cl.newInstance();

              if (driver != null) {
                log.fine(L.l("DatabaseManager adding driver '{0}'", driver.getClass().getName()));

                _driverList.add(driver);
              }
            } catch (Exception e) {
              log.log(Level.FINE, e.toString(), e);
            }
          }
        } catch (Exception e) {
          log.log(Level.FINE, e.toString(), e);
        } finally {
          if (is != null) is.close();
        }
      }
    } catch (Exception e) {
      log.log(Level.FINE, e.toString(), e);
    }
  }
Example #14
0
  private void injectProperty(
      Object bean, Class<?> type, Object property, String alias, TypedValueGroup arguments)
      throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    NoSuchMethodException nsme = null;

    if (arguments != null && arguments.size() > 0) {
      Object[] props = new Object[arguments.size() + 1];
      props[0] = property;
      Class<?>[] types = new Class<?>[arguments.size() + 1];
      types[0] = type;

      arguments.reset();
      while (arguments.load(props, 1)) {
        try {
          addSetProperty(bean, types, alias, props);
          return;
        } catch (NoSuchMethodException x) {
          // not a problem
          nsme = x;
        }
      }
    } else {
      try {
        addSetProperty(bean, new Class<?>[] {type}, alias, property);
        return;
      } catch (NoSuchMethodException x) {
        // not a problem
        nsme = x;
      }
    }

    // now try the super classes
    Class<?>[] interfaces = type.getInterfaces();
    for (Class<?> face : interfaces) {
      try {
        injectProperty(bean, face, property, alias, arguments);
        return;
      } catch (NoSuchMethodException x) {
        continue;
      }
    }
    Class<?> supertype = type.getSuperclass();
    if (supertype != null) {
      injectProperty(bean, supertype, property, alias, arguments);
    } else {
      throw nsme;
    }
  }
Example #15
0
 public void write(JmeExporter e) throws IOException {
   try {
     e.getCapsule(this).write((Type) myclass.newInstance(), "myclass", new Type());
   } catch (Exception ee) {
   }
   e.getCapsule(this).writeSavableArrayList(new ArrayList(instances), "instances", null);
 }
  /** Looks up the local database, creating if necessary. */
  private DataSource findDatabaseImpl(String url, String driverName) throws SQLException {
    try {
      synchronized (_databaseMap) {
        DBPool db = _databaseMap.get(url);

        if (db == null) {
          db = new DBPool();

          db.setVar(url + "-" + _gId++);

          DriverConfig driver = db.createDriver();

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

          Class driverClass = Class.forName(driverName, false, loader);

          driver.setType(driverClass);
          driver.setURL(url);

          db.init();

          _databaseMap.put(url, db);
        }

        return db;
      }
    } catch (RuntimeException e) {
      throw e;
    } catch (SQLException e) {
      throw e;
    } catch (Exception e) {
      throw ConfigException.create(e);
    }
  }
Example #17
0
 public String toString() {
   return "type="
       + type.getSimpleName()
       + ",data="
       + data.getClass().getSimpleName()
       + ':'
       + data;
 }
Example #18
0
  public static void invokeSetMethodCaseInsensitive(Object obj, String prop, String value)
      throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    String alternateMethodName = null;
    Class cl = obj.getClass();

    String setMeth = "set" + prop;

    Method[] methodsList = cl.getMethods();
    boolean methodFound = false;
    int i = 0;
    for (i = 0; i < methodsList.length; ++i) {
      if (methodsList[i].getName().equalsIgnoreCase(setMeth) == true) {
        Class[] parameterTypes = methodsList[i].getParameterTypes();
        if (parameterTypes.length == 1) {
          if (parameterTypes[0].getName().equals("java.lang.String")) {
            methodFound = true;
            break;
          } else alternateMethodName = methodsList[i].getName();
        }
      }
    }
    if (methodFound == true) {
      Object[] params = {value};
      methodsList[i].invoke(obj, params);
      return;
    }
    if (alternateMethodName != null) {
      try {
        // try int method
        Class[] cldef = {Integer.TYPE};
        Method meth = cl.getMethod(alternateMethodName, cldef);
        Object[] params = {Integer.valueOf(value)};
        meth.invoke(obj, params);
        return;
      } catch (NoSuchMethodException nsmex) {
        // try boolean method
        Class[] cldef = {Boolean.TYPE};
        Method meth = cl.getMethod(alternateMethodName, cldef);
        Object[] params = {Boolean.valueOf(value)};
        meth.invoke(obj, params);
        return;
      }

    } else throw new NoSuchMethodException(setMeth);
  }
Example #19
0
  /** Set up reflection methods required by the loader */
  @SuppressWarnings("unchecked")
  private boolean prepareLoader() {
    try {
      // addURL method is used by the class loader to
      mAddUrl = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
      mAddUrl.setAccessible(true);

      Formatter minecraftLogFormatter = null;

      try {
        Class<? extends Formatter> formatterClass =
            (Class<? extends Formatter>)
                Minecraft.class
                    .getClassLoader()
                    .loadClass(
                        ModUtilities.getObfuscatedFieldName(
                            "net.minecraft.src.ConsoleLogFormatter", "em"));
        Constructor<? extends Formatter> defaultConstructor =
            formatterClass.getDeclaredConstructor();
        defaultConstructor.setAccessible(true);
        minecraftLogFormatter = defaultConstructor.newInstance();
      } catch (Exception ex) {
        ConsoleLogManager.init();
        minecraftLogFormatter = ConsoleLogManager.loggerLogManager.getHandlers()[0].getFormatter();
      }

      logger.setUseParentHandlers(false);

      StreamHandler consoleHandler = new ConsoleHandler();
      if (minecraftLogFormatter != null) consoleHandler.setFormatter(minecraftLogFormatter);
      logger.addHandler(consoleHandler);

      FileHandler logFileHandler =
          new FileHandler(
              new File(Minecraft.getMinecraftDir(), "LiteLoader.txt").getAbsolutePath());
      if (minecraftLogFormatter != null) logFileHandler.setFormatter(minecraftLogFormatter);
      logger.addHandler(logFileHandler);
    } catch (Throwable th) {
      logger.log(Level.SEVERE, "Error initialising LiteLoader", th);
      return false;
    }

    return true;
  }
Example #20
0
  /**
   * @param classloader
   * @param superClass
   * @param classes
   * @param className
   */
  @SuppressWarnings("unchecked")
  private static void checkAndAddClass(
      ClassLoader classloader, Class superClass, LinkedList<Class> classes, String className) {
    if (className.indexOf('$') > -1) return;

    try {
      Class subClass = classloader.loadClass(className);

      if (subClass != null
          && !superClass.equals(subClass)
          && superClass.isAssignableFrom(subClass)
          && !subClass.isInterface()
          && !classes.contains(subClass)) {
        classes.add(subClass);
      }
    } catch (Throwable th) {
      logger.log(Level.WARNING, "checkAndAddClass error", th);
    }
  }
Example #21
0
 public boolean update()
     throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException,
         IllegalAccessException {
   ClassLoader newLoader = updater.update();
   Class<?> cl = newLoader.loadClass(Main.class.getName());
   if (Main.class.equals(cl)) return false; // Not a new class
   Object newMain;
   Method
       init =
           cl.getMethod("init", InputStream.class, PipeOutputStream.class, PipeInputStream.class),
       start = cl.getMethod("start");
   try {
     newMain = cl.newInstance();
     init.invoke(newMain, oldStdin, stdinPipe, stdoutPipe);
     stop();
     start.invoke(newMain);
     return true;
   } catch (InstantiationException ignored) {
   }
   return false;
 }
Example #22
0
 /** Creates a map of the classes fields. */
 protected static Object getParamArg(Class cl) {
   if (!cl.isPrimitive()) return null;
   else if (boolean.class.equals(cl)) return Boolean.FALSE;
   else if (byte.class.equals(cl)) return new Byte((byte) 0);
   else if (short.class.equals(cl)) return new Short((short) 0);
   else if (char.class.equals(cl)) return new Character((char) 0);
   else if (int.class.equals(cl)) return Integer.valueOf(0);
   else if (long.class.equals(cl)) return Long.valueOf(0);
   else if (float.class.equals(cl)) return Float.valueOf(0);
   else if (double.class.equals(cl)) return Double.valueOf(0);
   else throw new UnsupportedOperationException();
 }
Example #23
0
  /**
   * Should parse a string to select, initialize, and return one of the policy databases coded
   *
   * @param optionValue the string to parse
   * @return the policy database being used
   */
  private void selectPDB(String optionValue) {
    try {
      Class<?> cls = Class.forName("com.kpro.datastorage." + optionValue);

      @SuppressWarnings("rawtypes")
      Class[] params = new Class[2];
      params[0] = String.class;
      params[1] = String.class;
      Method m = cls.getDeclaredMethod("getInstance", params);

      Object[] argslist = new Object[2];
      argslist[0] = genProps.getProperty("inDBLoc");
      argslist[1] = genProps.getProperty("outDBLoc", genProps.getProperty("inDBLoc"));
      pdb = (PolicyDatabase) m.invoke(null, argslist);
    } catch (Exception e) {
      System.err.println("Selected PolicyDatabase not found");
    }

    if (pdb == null) {
      System.err.println("pdb null in selectPDB");
    }
  }
Example #24
0
  public Object readObject(AbstractHessianInput in, String[] fieldNames) throws IOException {
    try {
      Object obj = instantiate();

      return readObject(in, obj, fieldNames);
    } catch (IOException e) {
      throw e;
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new IOExceptionWrapper(_type.getName() + ":" + e.getMessage(), e);
    }
  }
Example #25
0
  /**
   * Find mod classes in the class path and enumerated mod files list
   *
   * @param classPathEntries Java class path split into string entries
   * @return map of classes to load
   */
  private HashMap<String, Class> findModClasses(
      String[] classPathEntries, LinkedList<File> modFiles) {
    // To try to avoid loading the same mod multiple times if it appears in more than one entry in
    // the class path, we index
    // the mods by name and hopefully match only a single instance of a particular mod
    HashMap<String, Class> modsToLoad = new HashMap<String, Class>();

    try {
      logger.info("Searching protection domain code source...");

      File packagePath =
          new File(LiteLoader.class.getProtectionDomain().getCodeSource().getLocation().toURI());
      LinkedList<Class> modClasses =
          getSubclassesFor(packagePath, Minecraft.class.getClassLoader(), LiteMod.class, "LiteMod");

      for (Class mod : modClasses) {
        modsToLoad.put(mod.getSimpleName(), mod);
      }

      if (modClasses.size() > 0)
        logger.info(String.format("Found %s potential matches", modClasses.size()));
    } catch (Throwable th) {
      logger.warning("Error loading from local class path: " + th.getMessage());
    }

    // Search through the class path and find mod classes
    for (String classPathPart : classPathEntries) {
      logger.info(String.format("Searching %s...", classPathPart));

      File packagePath = new File(classPathPart);
      LinkedList<Class> modClasses =
          getSubclassesFor(packagePath, Minecraft.class.getClassLoader(), LiteMod.class, "LiteMod");

      for (Class mod : modClasses) {
        modsToLoad.put(mod.getSimpleName(), mod);
      }

      if (modClasses.size() > 0)
        logger.info(String.format("Found %s potential matches", modClasses.size()));
    }

    // Search through mod files and find mod classes
    for (File modFile : modFiles) {
      logger.info(String.format("Searching %s...", modFile.getAbsolutePath()));

      LinkedList<Class> modClasses =
          getSubclassesFor(modFile, Minecraft.class.getClassLoader(), LiteMod.class, "LiteMod");

      for (Class mod : modClasses) {
        modsToLoad.put(mod.getSimpleName(), mod);
      }

      if (modClasses.size() > 0)
        logger.info(String.format("Found %s potential matches", modClasses.size()));
    }

    return modsToLoad;
  }
Example #26
0
  /**
   * Create mod instances from the enumerated classes
   *
   * @param modsToLoad List of mods to load
   */
  private void loadMods(HashMap<String, Class> modsToLoad) {
    if (modsToLoad == null) {
      logger.info("Mod class discovery failed. Not loading any mods!");
      return;
    }

    logger.info("Discovered " + modsToLoad.size() + " total mod(s)");

    for (Class mod : modsToLoad.values()) {
      try {
        logger.info("Loading mod from " + mod.getName());

        LiteMod newMod = (LiteMod) mod.newInstance();
        mods.add(newMod);

        logger.info(
            "Successfully added mod " + newMod.getName() + " version " + newMod.getVersion());
      } catch (Throwable th) {
        logger.warning(th.toString());
        th.printStackTrace();
      }
    }
  }
Example #27
0
  private static Class<?> getClassFromJar(String pathToJar, String pkg, String classToGet)
      throws IOException, ClassNotFoundException, SecurityException, InstantiationException,
          IllegalAccessException, NoSuchMethodException, IllegalArgumentException,
          InvocationTargetException {

    JarFile jarFile = new JarFile(pathToJar);
    Enumeration e = jarFile.entries();

    URL[] urls = {new URL("jar:file:" + pathToJar + "!/")};
    ClassLoader cl = URLClassLoader.newInstance(urls);

    Class<?> c = Class.forName(pkg + "." + classToGet, true, cl);

    return c;
  }
Example #28
0
  public JavaDeserializer(Class cl) {
    _type = cl;
    _fieldMap = getFieldMap(cl);

    _readResolve = getReadResolve(cl);

    if (_readResolve != null) {
      _readResolve.setAccessible(true);
    }

    Constructor[] constructors = cl.getDeclaredConstructors();
    long bestCost = Long.MAX_VALUE;

    for (int i = 0; i < constructors.length; i++) {
      Class[] param = constructors[i].getParameterTypes();
      long cost = 0;

      for (int j = 0; j < param.length; j++) {
        cost = 4 * cost;

        if (Object.class.equals(param[j])) cost += 1;
        else if (String.class.equals(param[j])) cost += 2;
        else if (int.class.equals(param[j])) cost += 3;
        else if (long.class.equals(param[j])) cost += 4;
        else if (param[j].isPrimitive()) cost += 5;
        else cost += 6;
      }

      if (cost < 0 || cost > (1 << 48)) cost = 1 << 48;

      cost += (long) param.length << 48;

      if (cost < bestCost) {
        _constructor = constructors[i];
        bestCost = cost;
      }
    }

    if (_constructor != null) {
      _constructor.setAccessible(true);
      Class[] params = _constructor.getParameterTypes();
      _constructorArgs = new Object[params.length];
      for (int i = 0; i < params.length; i++) {
        _constructorArgs[i] = getParamArg(params[i]);
      }
    }
  }
Example #29
0
  /** Verify and invoke main if present in the specified class. */
  public static void invokeApplicationMain(Class mainClass, String[] args)
      throws InvocationTargetException, IllegalAccessException, ClassNotFoundException {
    String err = localStrings.getLocalString("utility.no.main", "", new Object[] {mainClass});

    // determine the main method using reflection
    // verify that it is public static void and takes
    // String[] as the only argument
    Method mainMethod = null;
    try {
      mainMethod = mainClass.getMethod("main", new Class[] {String[].class});
    } catch (NoSuchMethodException msme) {
      _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility", msme);
      throw new ClassNotFoundException(err);
    }

    // check modifiers: public static
    int modifiers = mainMethod.getModifiers();
    if (!Modifier.isPublic(modifiers) || !Modifier.isStatic(modifiers)) {
      err =
          localStrings.getLocalString(
              "utility.main.notpublicorstatic",
              "The main method is either not public or not static");
      _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility_main.notpublicorstatic");
      throw new ClassNotFoundException(err);
    }

    // check return type and exceptions
    if (!mainMethod.getReturnType().equals(Void.TYPE)) {
      err =
          localStrings.getLocalString(
              "utility.main.notvoid", "The main method's return type is not void ");
      _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility_main.notvoid");
      throw new ClassNotFoundException(err);
    }

    // build args to the main and call it
    Object params[] = new Object[1];
    params[0] = args;
    mainMethod.invoke(null, params);
  }
Example #30
0
 /**
  * The instance is stored in a place directly accessible through the Java SE API, so that it can
  * be recovered from any class loader.
  */
 protected MockingBridge(Class<? extends MockingBridge> subclass) {
   super("mockit." + subclass.hashCode(), null);
   LogManager.getLogManager().addLogger(this);
 }