示例#1
0
  public String toString() {
    String s = "[" + helper_type + ";";
    for (Enumeration e = seq.elements(); e.hasMoreElements(); ) {
      try {
        Class c = (Class) e.nextElement();
        s += c.getName() + ",";
      } catch (NoSuchElementException ee) {
        s += "???" + ",";
      }
    }

    return s + "]";
  }
示例#2
0
文件: Util.java 项目: ngrstad/basex
  /**
   * Starts the specified class in a separate process.
   *
   * @param clz class to start
   * @param args command-line arguments
   * @return reference to a {@link Process} instance representing the started process
   */
  public static Process start(final Class<?> clz, final String... args) {
    final String[] largs = {
      "java",
      "-Xmx" + Runtime.getRuntime().maxMemory(),
      "-cp",
      System.getProperty("java.class.path"),
      clz.getName(),
      "-D",
    };
    final StringList sl = new StringList().add(largs).add(args);

    try {
      return new ProcessBuilder(sl.toArray()).start();
    } catch (final IOException ex) {
      notexpected(ex);
      return null;
    }
  }
示例#3
0
 private static InputSource getConfigSource(Class pAppClass) throws DataNotFoundException {
   URL resource = pAppClass.getResource(CONFIG_FILE_NAME);
   String resourceFileName = resource.toExternalForm();
   File resourceFile = new File(resourceFileName);
   InputStream configResourceStream = pAppClass.getResourceAsStream(CONFIG_FILE_NAME);
   if (null == configResourceStream) {
     throw new DataNotFoundException(
         "unable to find XML configuration file resource: "
             + CONFIG_FILE_NAME
             + " for class: "
             + pAppClass.getName());
   }
   InputSource inputSource = new InputSource(configResourceStream);
   if (!resourceFile.exists()) {
     inputSource.setSystemId(resourceFileName);
   }
   return (inputSource);
 }
 public JSONObject describeClass(Class<?> clazz) throws Exception {
   JSONObject desc = new JSONObject();
   desc.put("name", clazz.getName());
   if (clazz.isEnum()) {
     @SuppressWarnings("unchecked")
     Class<Enum<?>> enumClass = (Class<Enum<?>>) clazz;
     ArrayList<String> enumNames = Lists.newArrayList();
     for (Enum<?> e : enumClass.getEnumConstants()) {
       enumNames.add(e.name());
     }
     desc.put("enum", enumNames);
   }
   UI_TYPE ui_type = UI_TYPE.getEnumFor(clazz);
   if (ui_type != null) {
     desc.put("uiType", ui_type.getName());
   }
   desc.put("properties", getClassProperties(clazz, 0));
   return desc;
 }
示例#5
0
 private static boolean checkType(
     String what, Object object, Class wrongClass, boolean isException) {
   final String type = isException ? "exception" : "object";
   final String rendered = isException ? "thrown" : "returned";
   System.out.println("For " + type + " " + rendered + " by " + what + ":");
   if (wrongClass.isInstance(object)) {
     System.out.println("TEST FAILS: " + type + " loaded by test " + "classloader");
     return false;
   }
   String className = object.getClass().getName();
   if (!className.equals(wrongClass.getName())) {
     System.out.println(
         "TEST FAILS: " + rendered + " " + type + " has wrong class name: " + className);
     return false;
   }
   System.out.println(
       "Test passes: " + rendered + " " + type + " has same class name but is not same class");
   return true;
 }
 protected synchronized Class loadClass(String name, boolean resolve)
     throws ClassNotFoundException {
   if (_excludedNames.contains(name)) {
     print("EXCLUDED: " + name);
     throw new ClassNotFoundException(name);
   }
   if (_cache.containsKey(name)) {
     print("CACHED: " + name);
     return (Class) _cache.get(name);
   }
   if (mustDelegate(name)) {
     print("NATIVE: " + name);
     return super.loadClass(name, resolve);
   }
   Class clazz = findRawClass(name);
   if (resolve) {
     resolveClass(clazz);
   }
   _cache.put(clazz.getName(), clazz);
   print("LOADED: " + name);
   return clazz;
 }
  private Class doParseClass(GroovyCodeSource codeSource) {
    validate(codeSource);
    Class answer; // Was neither already loaded nor compiling, so compile and add to cache.
    CompilationUnit unit = createCompilationUnit(config, codeSource.getCodeSource());
    if (recompile != null && recompile || recompile == null && config.getRecompileGroovySource()) {
      unit.addFirstPhaseOperation(
          TimestampAdder.INSTANCE, CompilePhase.CLASS_GENERATION.getPhaseNumber());
    }
    SourceUnit su = null;
    File file = codeSource.getFile();
    if (file != null) {
      su = unit.addSource(file);
    } else {
      URL url = codeSource.getURL();
      if (url != null) {
        su = unit.addSource(url);
      } else {
        su = unit.addSource(codeSource.getName(), codeSource.getScriptText());
      }
    }

    ClassCollector collector = createCollector(unit, su);
    unit.setClassgenCallback(collector);
    int goalPhase = Phases.CLASS_GENERATION;
    if (config != null && config.getTargetDirectory() != null) goalPhase = Phases.OUTPUT;
    unit.compile(goalPhase);

    answer = collector.generatedClass;
    String mainClass = su.getAST().getMainClassName();
    for (Object o : collector.getLoadedClasses()) {
      Class clazz = (Class) o;
      String clazzName = clazz.getName();
      definePackage(clazzName);
      setClassCacheEntry(clazz);
      if (clazzName.equals(mainClass)) answer = clazz;
    }
    return answer;
  }
示例#8
0
  /** 获取类的class文件位置的URL。这个方法是本类最基础的方法,供其它方法调用。 */
  public URL getClassLocationURL(final Class cls) {
    if (cls == null) {
      throw new IllegalArgumentException("class that input is null");
    }
    URL result = null;
    final String clsAsResource = cls.getName().replace('.', '/').concat(".class");
    final ProtectionDomain pd = cls.getProtectionDomain();
    if (pd != null) {
      final CodeSource cs = pd.getCodeSource();
      if (cs != null) {
        result = cs.getLocation();
      }
      if (result != null) {
        if ("file".equals(result.getProtocol())) {
          try {
            if (result.toExternalForm().endsWith(".jar")
                || result.toExternalForm().endsWith(".zip")) {
              result =
                  new URL(
                      "jar:".concat(result.toExternalForm()).concat("!/").concat(clsAsResource));
            } else if (new File(result.getFile()).isDirectory()) {
              result = new URL(result, clsAsResource);
            }
          } catch (MalformedURLException ignore) {
          }
        }
      }
    }

    if (result == null) {
      final ClassLoader clsLoader = cls.getClassLoader();
      result =
          clsLoader != null
              ? clsLoader.getResource(clsAsResource)
              : ClassLoader.getSystemResource(clsAsResource);
    }
    return result;
  }
 /**
  * sets an entry in the class cache.
  *
  * @param cls the class
  * @see #removeClassCacheEntry(String)
  * @see #getClassCacheEntry(String)
  * @see #clearCache()
  */
 protected void setClassCacheEntry(Class cls) {
   synchronized (classCache) {
     classCache.put(cls.getName(), cls);
   }
 }
示例#10
0
 public static String classNameAsPath(Class clazz) {
   return clazz.getName().replace('.', '/') + ".class";
 }
示例#11
0
 private static String simpleName(Class clazz) {
   String clazzName = clazz.getName();
   int dotIdx = clazzName.lastIndexOf('.');
   return clazzName.substring(dotIdx + 1);
 }
    @Override
    public void run() {
      try {
        processTime = System.currentTimeMillis();
        myPack = (Pack) ois.readObject();
        functionName = myPack.getfunctionName();
        paramTypes = myPack.getparamTypes();
        paramValues = myPack.getparamValues();
        state = myPack.getstate();
        stateDType = myPack.getstateType();
        timestamps = myPack.getTimeStamps();

        if (functionName != null && functionName.length() > 0) {
          try {

            System.out.println("Trying to load and execute");
            Class cls = Class.forName(stateDType.getName());

            timestamps.add(processTime + ",server1");

            /*System.out.println(""+stateDType.getName());

            System.out.println("functionsName: " + functionName.toLowerCase());
            System.out.println("paramTypes: " + paramTypes.toString());*/

            Method method = cls.getDeclaredMethod(functionName, paramTypes);

            try {

              /** support for caching results */

              /** cache using the parameters as key of the result can be possible */
              // boolean processed = TreeManager.getInstance().exists(paramValues[0]);

              // System.out.println("param1:" + (int[]) paramValues[0]);
              // System.out.println("param1:" + paramValues[1]);
              // System.out.println("param1:" +  paramValues[2]);

              oos.flush();
              Object result = method.invoke(state, paramValues);
              ResultPack rp = new ResultPack(result, state);

              rp.setTimeStamps(timestamps);

              // System.out.println("Size in bytes: " + sizeInBytes(rp));
              oos.flush();
              oos.writeObject(rp);
              // System.out.println("Object wrote it");
              oos.flush();
              // System.out.println("Object executed and flushed: " + (System.currentTimeMillis() -
              // processTime));

              System.out.println("Object executed and flushed:");

              // System.out.println("Object executed and flushed: " + (System.currentTimeMillis() -
              // processTime));

            } catch (IllegalAccessException ex1) {
              returnnull(oos);
              System.out.println("Hubo problema 1: " + ex1.getMessage());
            } catch (InvocationTargetException ex2) {
              returnnull(oos);
              System.out.println("Hubo problema 2: " + ex2.getCause());
            } catch (Exception ex3) {
              ResultPack rp = new ResultPack(null, state);
              oos.writeObject(rp);
              oos.flush();
              System.out.println("Hubo problema 3" + ex3.getCause());
            }

          } catch (ClassNotFoundException ex) {
            returnnull(oos);
            System.out.println("Hubo problema 4");
          } catch (IllegalArgumentException ex) {
            returnnull(oos);
            System.out.println("Hubo problema 5");
          } catch (NoSuchMethodException ex) {
            returnnull(oos);
            System.out.println("Hubo problema 6");
          } catch (SecurityException ex) {
            returnnull(oos);
            System.out.println("Hubo problema 7");
          } finally {

            oos.close();
            ois.close();

            in.close();
            out.close();

            mysocket.close();

            oos = null;
            ois = null;

            in = null;
            out = null;
            mysocket = null;
          }
        } else {
          returnnull(oos);
        }
      } catch (IOException ex) {
        returnnull(oos);
        System.out.println("Hubo problema 8");
      } catch (ClassNotFoundException ex) {
        returnnull(oos);
        System.out.println("Hubo problema 9");
        ex.printStackTrace();
      } finally {
        makeconnection();
      }
    }
  private JSONArray getClassProperties(Class<?> clazz, int level) throws IntrospectionException {
    JSONArray arr = new JSONArray();
    TypeDiscoverer td = new TypeDiscoverer();
    try {
      for (PropertyDescriptor pd : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) {
        Method readMethod = pd.getReadMethod();
        if (readMethod != null) {
          if (readMethod.getDeclaringClass() == java.lang.Enum.class) {
            // skip getDeclaringClass
            continue;
          } else if ("class".equals(pd.getName())) {
            // skip getClass
            continue;
          }
        } else {
          // yields com.datatorrent.api.Context on JDK6 and
          // com.datatorrent.api.Context.OperatorContext with JDK7
          if ("up".equals(pd.getName())
              && com.datatorrent.api.Context.class.isAssignableFrom(pd.getPropertyType())) {
            continue;
          }
        }
        // LOG.info("name: " + pd.getName() + " type: " + pd.getPropertyType());

        Class<?> propertyType = pd.getPropertyType();
        if (propertyType != null) {
          JSONObject propertyObj = new JSONObject();
          propertyObj.put("name", pd.getName());
          propertyObj.put("canGet", readMethod != null);
          propertyObj.put("canSet", pd.getWriteMethod() != null);
          if (readMethod != null) {
            for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
              OperatorClassInfo oci = classInfo.get(c.getName());
              if (oci != null) {
                MethodInfo getMethodInfo = oci.getMethods.get(readMethod.getName());
                if (getMethodInfo != null) {
                  addTagsToProperties(getMethodInfo, propertyObj);
                  break;
                }
              }
            }
            // type can be a type symbol or parameterized type
            td.setTypeArguments(clazz, readMethod.getGenericReturnType(), propertyObj);
          } else {
            if (pd.getWriteMethod() != null) {
              td.setTypeArguments(
                  clazz, pd.getWriteMethod().getGenericParameterTypes()[0], propertyObj);
            }
          }
          // if (!propertyType.isPrimitive() && !propertyType.isEnum() && !propertyType.isArray() &&
          // !propertyType.getName().startsWith("java.lang") && level < MAX_PROPERTY_LEVELS) {
          //  propertyObj.put("properties", getClassProperties(propertyType, level + 1));
          // }
          arr.put(propertyObj);
        }
      }
    } catch (JSONException ex) {
      throw new RuntimeException(ex);
    }
    return arr;
  }
    @Override
    public void run() {
      try {
        myPack = (Pack) ois.readObject();
        functionName = myPack.getfunctionName();
        paramTypes = myPack.getparamTypes();
        paramValues = myPack.getparamValues();
        state = myPack.getstate();
        stateDType = myPack.getstateType();
        if (functionName != null && functionName.length() > 0) {
          try {

            Class cls = Class.forName(stateDType.getName());

            Method method = cls.getDeclaredMethod(functionName, paramTypes);

            try {
              Object result = method.invoke(state, paramValues);
              ResultPack rp = new ResultPack(result, state);
              oos.writeObject(rp);
              oos.flush();
            } catch (IllegalAccessException ex) {
              returnnull(oos);
            } catch (InvocationTargetException ex) {
              returnnull(oos);
            } catch (Exception ex) {
              ResultPack rp = new ResultPack(null, state);
              oos.writeObject(rp);
              oos.flush();
            }

          } catch (ClassNotFoundException ex) {
            returnnull(oos);
          } catch (IllegalArgumentException ex) {
            returnnull(oos);
          } catch (NoSuchMethodException ex) {
            returnnull(oos);
          } catch (SecurityException ex) {
            returnnull(oos);
          } finally {

            oos.close();
            ois.close();

            in.close();
            out.close();

            mysocket.close();

            oos = null;
            ois = null;

            in = null;
            out = null;
            mysocket = null;
          }
        } else {
          returnnull(oos);
        }
      } catch (IOException ex) {
        returnnull(oos);
      } catch (ClassNotFoundException ex) {
        returnnull(oos);
      } finally {
        makeconnection();
      }
    }
示例#15
0
  /**
   * Contact a belief network context, get the helper list, and search the list to see if there's a
   * helper which matches the type sequence specified. If there's more than one helper which
   * matches, find the ``best fit.''
   *
   * <p>The class and count scores of the best-fitting helper class are written into
   * <tt>max_class_score[0]</tt> and <tt>max_count_score[0]</tt>, respectively.
   */
  public static Class find_helper_class0(
      Vector seq, String helper_type, int[] max_class_score, int[] max_count_score)
      throws ClassNotFoundException {
    long t0 = System.currentTimeMillis();
    if (bnc != null) // make sure the reference is still alive
    try {
        bnc.get_name();
      } catch (RemoteException e) {
        bnc = null;
      }

    if (bnc == null) // need to locate a context
    {
      String cb = System.getProperty("java.rmi.server.codebase", "http://localhost");
      long tt0 = System.currentTimeMillis();
      try {
        bnc = BeliefNetworkContext.locate_context(new URL(cb).getHost());
      } catch (Exception e) {
        throw new ClassNotFoundException("nested: " + e);
      }
    }

    String[] helperlist;
    try {
      helperlist = bnc.get_helper_names(helper_type);
    } catch (RemoteException e) {
      throw new ClassNotFoundException("bnc.get_helper_names failed");
    }

    int[] class_score1 = new int[1], count_score1 = new int[1];
    max_class_score[0] = -1;
    max_count_score[0] = -1;
    Class cmax_score = null;

    for (int i = 0; i < helperlist.length; i++) {
      try {
        Class c = RMIClassLoader.loadClass(helperlist[i]);
        SeqTriple[] sm = (SeqTriple[]) invoke_description(c);
        if (sm == null) continue; // apparently not a helper class
        if (MatchClassPattern.matches(sm, seq, class_score1, count_score1)) {
          if (class_score1[0] > max_class_score[0]
              || (class_score1[0] == max_class_score[0] && count_score1[0] > max_count_score[0])) {
            cmax_score = c;
            max_class_score[0] = class_score1[0];
            max_count_score[0] = count_score1[0];
          }
        }
      } catch (Exception e2) {
        System.err.println("PiHelperLoader: attempt to load " + helperlist[i] + " failed; " + e2);
      }
    }

    if (cmax_score == null) {
      System.err.println("find_helper_class0: failed; helper list:");
      for (int i = 0; i < helperlist.length; i++) System.err.println("\t" + helperlist[i]);

      String s = "";
      for (Enumeration e = seq.elements(); e.hasMoreElements(); ) {
        try {
          Class c = (Class) e.nextElement();
          s += c.getName() + ",";
        } catch (NoSuchElementException ee) {
          s += "???" + ",";
        }
      }

      throw new ClassNotFoundException("no " + helper_type + " helper for sequence [" + s + "]");
    }

    // FOR NOW IGNORE THE POSSIBILITY OF TWO OR MORE MATCHES !!!
    return cmax_score;
  }
示例#16
0
 /**
  * Loads a resource relative to a specific class into a byte array.
  *
  * @param c Class (resource must come from same classloader)
  * @param sName Name of resource (relative path to class)
  * @return Byte array containing file in memory
  * @throws IOException If it doesn't exist or there is any other error loading
  */
 public static byte[] loadResource(Class c, String sName) throws IOException {
   return loadResource(
       c.getClassLoader(),
       "/" + c.getName().replace('.', '/').replaceFirst("/[^/]*$", "") + "/" + sName);
 }