Ejemplo n.º 1
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, <call /> 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());
   }
 }
Ejemplo n.º 2
0
 static Method get_sigaction_method(String cls, String meth)
     throws ClassNotFoundException, NoSuchMethodException {
   return Class.forName(cls)
       .getMethod(
           meth,
           new Class[] {Integer.TYPE, Class.forName("jtux.UProcess$siginfo_t"), Long.TYPE});
 }
Ejemplo n.º 3
0
  void enableLionFS() {
    try {
      String version = System.getProperty("os.version");
      String[] tokens = version.split("\\.");
      int major = Integer.parseInt(tokens[0]), minor = 0;
      if (tokens.length > 1) minor = Integer.parseInt(tokens[1]);
      if (major < 10 || (major == 10 && minor < 7))
        throw new Exception("Operating system version is " + version);

      Class fsuClass = Class.forName("com.apple.eawt.FullScreenUtilities");
      Class argClasses[] = new Class[] {Window.class, Boolean.TYPE};
      Method setWindowCanFullScreen = fsuClass.getMethod("setWindowCanFullScreen", argClasses);
      setWindowCanFullScreen.invoke(fsuClass, this, true);

      Class fsListenerClass = Class.forName("com.apple.eawt.FullScreenListener");
      InvocationHandler fsHandler = new MyInvocationHandler(cc);
      Object proxy =
          Proxy.newProxyInstance(
              fsListenerClass.getClassLoader(), new Class[] {fsListenerClass}, fsHandler);
      argClasses = new Class[] {Window.class, fsListenerClass};
      Method addFullScreenListenerTo = fsuClass.getMethod("addFullScreenListenerTo", argClasses);
      addFullScreenListenerTo.invoke(fsuClass, this, proxy);

      canDoLionFS = true;
    } catch (Exception e) {
      vlog.debug("Could not enable OS X 10.7+ full-screen mode:");
      vlog.debug("  " + e.toString());
    }
  }
Ejemplo n.º 4
0
 // setHandler creates a Proxy object from the passed OSXAdapter and adds it as an
 // ApplicationListener
 public static void setHandler(OSXAdapter adapter) {
   try {
     Class applicationClass = Class.forName("com.apple.eawt.Application");
     if (macOSXApplication == null) {
       macOSXApplication =
           applicationClass.getConstructor((Class[]) null).newInstance((Object[]) null);
     }
     Class applicationListenerClass = Class.forName("com.apple.eawt.ApplicationListener");
     Method addListenerMethod =
         applicationClass.getDeclaredMethod(
             "addApplicationListener", new Class[] {applicationListenerClass});
     // Create a proxy object around this handler that can be reflectively added as an Apple
     // ApplicationListener
     Object osxAdapterProxy =
         Proxy.newProxyInstance(
             OSXAdapter.class.getClassLoader(), new Class[] {applicationListenerClass}, adapter);
     addListenerMethod.invoke(macOSXApplication, new Object[] {osxAdapterProxy});
   } catch (ClassNotFoundException cnfe) {
     System.err.println(
         "This version of Mac OS X does not support the Apple EAWT.  ApplicationEvent handling has been disabled ("
             + cnfe
             + ")");
   } catch (
       Exception
           ex) { // Likely a NoSuchMethodException or an IllegalAccessException loading/invoking
                 // eawt.Application methods
     System.err.println("Mac OS X Adapter could not talk to EAWT:");
     ex.printStackTrace();
   }
 }
Ejemplo n.º 5
0
 private static Class<?> getClassObject(Object o) throws ClassNotFoundException {
   if (o == null) {
     System.out.println("null");
   }
   // 基本データ型の場合
   if (o instanceof Boolean) {
     return boolean.class;
   } else if (o instanceof Integer) {
     return int.class;
   } else if (o instanceof Double) {
     return double.class;
   } else if (o instanceof Long) {
     return long.class;
   } else if (o instanceof Short) {
     return short.class;
   } else if (o instanceof Character) {
     return char.class;
   } else if (o instanceof Byte) {
     return byte.class;
   } else if (o instanceof Float) {
     return float.class;
   }
   // 基本データ型以外の場合:forName()でクラスオブジェクトを取得
   else {
     System.out.println(Class.forName(strip(o.getClass().toString(), "class ")));
     return Class.forName(strip(o.getClass().toString(), "class "));
   }
 }
Ejemplo n.º 6
0
  /**
   * Search a wiring method in the specified class.
   *
   * @param cl the class where to find the method
   * @param methodName the method to be searched
   * @return the requested method, if it fully conforms to the definition of the wiring methods.
   */
  private static Method getMethod(Class cl, String methodName)
      throws NoSuchMethodException, ClassNotFoundException {

    // Search methods
    Method[] methods = cl.getMethods();
    ArrayList<Method> list = new ArrayList<Method>();
    for (Method m : methods) {
      if (m.getName().equals(methodName)) {
        list.add(m);
      }
    }

    if (list.size() == 0) {
      throw new NoSuchMethodException(
          "No method " + methodName + " in class " + cl.getSimpleName());
    } else if (list.size() > 1) {
      throw new NoSuchMethodException(
          "Multiple methods called " + methodName + " in class " + cl.getSimpleName());
    }

    // Found a single method with the right name; check if
    // it is a setter.
    final Class graphClass = Class.forName("peersim.graph.Graph");
    final Class randomClass = Class.forName("java.util.Random");
    Method method = list.get(0);
    Class[] pars = method.getParameterTypes();
    if (pars.length < 1 || !pars[0].isAssignableFrom(graphClass))
      throw new NoSuchMethodException(
          method.getName()
              + " of class "
              + cl.getSimpleName()
              + " is not a valid graph wiring method,"
              + " it has to have peersim.graph.Graph as first argument type");
    for (int i = 1; i < pars.length; ++i)
      if (!(pars[i] == int.class
          || pars[i] == long.class
          || pars[i] == double.class
          || (i == pars.length - 1 && pars[i].isAssignableFrom(randomClass))))
        throw new NoSuchMethodException(
            method.getName()
                + " of class "
                + cl.getSimpleName()
                + " is not a valid graph wiring method");

    if (method.toString().indexOf("static") < 0)
      throw new NoSuchMethodException(
          method.getName()
              + " of class "
              + cl.getSimpleName()
              + " is not a valid graph wiring method; it is not static");

    return method;
  }
Ejemplo n.º 7
0
  int[] init(int... dimensions) {
    int size = dimensions.length > 0 ? dimensions[0] : 0;
    if (___subrecord___ == null) {
      final String[] indexPrefixes = {
        "", "s", "_", "Index", "Length", "Ref", "Header", "Info", "Table"
      };
      for (String indexPrefix : indexPrefixes) {
        try {
          ___subrecord___ =
              (Class<? extends Enum>)
                  Class.forName(getClass().getPackage().getName() + '.' + name() + indexPrefix);
          try {
            size = ___subrecord___.getField("___recordlen___").getInt(null);
          } catch (Exception e) {
          }
          break;
        } catch (ClassNotFoundException e) {
        }
      }
    }

    for (String vPrefixe1 :
        new String[] {
          "_", "", "$", "Value",
        }) {
      if (___valueclass___ != null) break;
      String suffix = vPrefixe1;
      for (String name1 :
          new String[] {
            name().toLowerCase(), name(),
          }) {
        if (___valueclass___ != null) break;
        final String trailName = name1;
        if (trailName.endsWith(suffix)) {
          for (String aPackage1 :
              new String[] {
                "", getClass().getPackage().getName() + ".", "java.lang.", "java.util.",
              })
            if (___valueclass___ == null) break;
            else
              try {
                ___valueclass___ = Class.forName(aPackage1 + name().replace(suffix, ""));
              } catch (ClassNotFoundException e) {
              }
        }
      }
    }

    int seek = dimensions.length > 1 ? dimensions[1] : ___recordlen___;
    ___recordlen___ = Math.max(___recordlen___, seek + size);
    return new int[] {size, seek};
  }
  /**
   * Returns the class this method was called 'framesToSkip' frames up the caller hierarchy. JDK
   * used to have {@link sun.reflect.Reflection#getCallerClass(int)} until jdk 1.8 build 87. So we
   * have to resort to slow stack unwinding.
   *
   * <p>NOTE: <b>Extremely expensive! Please consider not using it. These aren't the droids you're
   * looking for!</b>
   */
  @SuppressWarnings("JavadocReference")
  @Nullable
  public static Class getCallerClass(int framesToSkip) {
    int frames = framesToSkip;

    StackTraceElement[] stackTrace = new Throwable().getStackTrace();
    String className = null;
    for (int i = 1; i <= frames; i++) {
      if (i >= stackTrace.length) {
        break;
      }
      StackTraceElement element = stackTrace[i];
      className = element.getClassName();
      if (className.equals("java.lang.reflect.Method")
          || className.equals("sun.reflect.NativeMethodAccessorImpl")
          || className.equals("sun.reflect.DelegatingMethodAccessorImpl")) {
        frames++;
        continue;
      }
      if (i == frames) {
        break;
      }
    }

    if (className == null) {
      // some plugins incorrectly expect not-null class too far up the caller chain,
      // so provide some not-null class for them
      className = ReflectionUtil.class.getName();
    }

    try {
      return Class.forName(className);
    } catch (ClassNotFoundException ignored) {
    }
    ClassLoader pluginClassLoader = PLUGIN_CLASS_LOADER_DETECTOR.fun(className);
    if (pluginClassLoader != null) {
      try {
        return Class.forName(className, false, pluginClassLoader);
      } catch (ClassNotFoundException ignored) {
      }
    }
    LOG.error(
        "Could not load class '"
            + className
            + "' using classLoader "
            + ReflectionUtil.class.getClassLoader()
            + "."
            + (stackTrace[1].getClassName().equals("com.intellij.openapi.util.IconLoader")
                ? " Use getIcon(String, Class) instead."
                : ""));
    return null;
  }
Ejemplo n.º 9
0
 private static void netxsurgery() throws Exception {
   /* Force off NetX codebase classloading. */
   Class<?> nxc;
   try {
     nxc = Class.forName("net.sourceforge.jnlp.runtime.JNLPClassLoader");
   } catch (ClassNotFoundException e1) {
     try {
       nxc = Class.forName("netx.jnlp.runtime.JNLPClassLoader");
     } catch (ClassNotFoundException e2) {
       throw (new Exception("No known NetX on classpath"));
     }
   }
   ClassLoader cl = MainFrame.class.getClassLoader();
   if (!nxc.isInstance(cl)) {
     throw (new Exception("Not running from a NetX classloader"));
   }
   Field cblf, lf;
   try {
     cblf = nxc.getDeclaredField("codeBaseLoader");
     lf = nxc.getDeclaredField("loaders");
   } catch (NoSuchFieldException e) {
     throw (new Exception("JNLPClassLoader does not conform to its known structure"));
   }
   cblf.setAccessible(true);
   lf.setAccessible(true);
   Set<Object> loaders = new HashSet<Object>();
   Stack<Object> open = new Stack<Object>();
   open.push(cl);
   while (!open.empty()) {
     Object cur = open.pop();
     if (loaders.contains(cur)) continue;
     loaders.add(cur);
     Object curl;
     try {
       curl = lf.get(cur);
     } catch (IllegalAccessException e) {
       throw (new Exception("Reflection accessibility not available even though set"));
     }
     for (int i = 0; i < Array.getLength(curl); i++) {
       Object other = Array.get(curl, i);
       if (nxc.isInstance(other)) open.push(other);
     }
   }
   for (Object cur : loaders) {
     try {
       cblf.set(cur, null);
     } catch (IllegalAccessException e) {
       throw (new Exception("Reflection accessibility not available even though set"));
     }
   }
 }
  private static void check(String what, MBeanNotificationInfo[] mbnis) {
    System.out.print(what + ": checking notification info: ");

    if (mbnis.length == 0) {
      System.out.println("NONE (suspicious)");
      suspicious.add(what);
      return;
    }

    // Each MBeanNotificationInfo.getName() should be an existent
    // Java class that is Notification or a subclass of it
    for (int j = 0; j < mbnis.length; j++) {
      String notifClassName = mbnis[j].getName();
      Class notifClass;
      try {
        notifClass = Class.forName(notifClassName);
      } catch (Exception e) {
        System.out.print("FAILED(" + notifClassName + ": " + e + ") ");
        failed.add(what);
        continue;
      }
      if (!Notification.class.isAssignableFrom(notifClass)) {
        System.out.print("FAILED(" + notifClassName + ": not a Notification) ");
        failed.add(what);
        continue;
      }
      System.out.print("OK(" + notifClassName + ") ");
    }
    System.out.println();
  }
 Document parseDocument(String filename) throws Exception {
   FileReader reader = new FileReader(filename);
   String firstLine = new BufferedReader(reader).readLine();
   reader.close();
   Document document = null;
   if (firstLine.startsWith("<?xml")) {
     System.err.println("XML detected; using default XML parser.");
   } else {
     try {
       Class nekoParserClass = Class.forName("org.cyberneko.html.parsers.DOMParser");
       Object parser = nekoParserClass.newInstance();
       Method parse = nekoParserClass.getMethod("parse", new Class[] {String.class});
       Method getDocument = nekoParserClass.getMethod("getDocument", new Class[0]);
       parse.invoke(parser, filename);
       document = (Document) getDocument.invoke(parser);
     } catch (Exception e) {
       System.err.println("NekoHTML HTML parser not found; HTML4 support disabled.");
     }
   }
   if (document == null) {
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     try { // http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic
       factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
     } catch (ParserConfigurationException e) {
       System.err.println("Warning: Could not disable external DTD loading");
     }
     DocumentBuilder builder = factory.newDocumentBuilder();
     document = builder.parse(filename);
   }
   return document;
 }
Ejemplo n.º 12
0
  private void callMethodForMultiPart(HttpServletRequest req, HttpServletResponse resp)
      throws Exception {
    String pinfo = req.getPathInfo();
    int pos = pinfo.indexOf('.');
    String cname = pinfo.substring(1, pos).replace('/', '.');
    String mname = pinfo.substring(pos + 1);

    MultiPartMap map = new MultiPartMap();
    FileItemIterator ite = new FileUpload().getItemIterator(req);
    while (ite.hasNext()) {
      FileItemStream item = ite.next();
      if (item.isFormField()) {
        map.put(item.getFieldName(), IOUtil.streamToString(item.openStream(), "UTF-8"));
      } else {
        FileItem val =
            new FileItem(
                item.getFileName(), item.getContentType(), IOUtil.streamToBytes(item.openStream()));
        map.put(item.getFieldName(), val);
      }
    }

    Class clazz = Class.forName(cname);
    Class[] types = new Class[] {MultiPartMap.class};
    Method method = clazz.getMethod(mname, types);
    if (method == null) {
      throw new RuntimeException("Not found method " + mname + "(Map)");
    }

    Object result = method.invoke(null, map);

    resp.setContentType(MIME_HTML + ";charset=utf-8");
    resp.getWriter().write(result.toString());
  }
Ejemplo n.º 13
0
 public static void setEnv(Map<String, String> newenv) {
   try {
     Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
     Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
     theEnvironmentField.setAccessible(true);
     Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
     env.putAll(newenv);
     Field theCaseInsensitiveEnvironmentField =
         processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
     theCaseInsensitiveEnvironmentField.setAccessible(true);
     Map<String, String> cienv =
         (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
     cienv.putAll(newenv);
   } catch (NoSuchFieldException e) {
     try {
       Class[] classes = Collections.class.getDeclaredClasses();
       Map<String, String> env = System.getenv();
       for (Class cl : classes) {
         if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
           Field field = cl.getDeclaredField("m");
           field.setAccessible(true);
           Object obj = field.get(env);
           Map<String, String> map = (Map<String, String>) obj;
           map.clear();
           map.putAll(newenv);
         }
       }
     } catch (Exception e2) {
       e2.printStackTrace();
     }
   } catch (Exception e1) {
     e1.printStackTrace();
   }
 }
Ejemplo n.º 14
0
  /**
   * Loads configuration. It verifies the constraints defined in {@link WireByMethod}.
   *
   * @param prefix the configuration prefix for this class
   */
  public WireByMethod(String prefix) {
    super(prefix);

    // get the method
    try {
      final Class wire =
          Configuration.getClass(
              prefix + "." + PAR_CLASS, Class.forName("peersim.graph.GraphFactory"));
      method =
          WireByMethod.getMethod(wire, Configuration.getString(prefix + "." + PAR_METHOD, "wire"));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    // set the constant args (those other than 0th)
    Class[] argt = method.getParameterTypes();
    args = new Object[argt.length];
    for (int i = 1; i < args.length; ++i) {

      if (argt[i] == int.class) args[i] = Configuration.getInt(prefix + "." + PAR_ARG + i);
      else if (argt[i] == long.class) args[i] = Configuration.getLong(prefix + "." + PAR_ARG + i);
      else if (argt[i] == double.class)
        args[i] = Configuration.getDouble(prefix + "." + PAR_ARG + i);
      else if (i == args.length - 1 && argt[i].isInstance(CommonState.r)) args[i] = CommonState.r;
      else {
        // we should neve get here
        throw new RuntimeException(
            "Unexpected error, please " + "report this problem to the peersim team");
      }
    }
  }
  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();

    isAdapter = in.readBoolean();
    if (isAdapter) {
      if (adapter_readAdapterObject == null) throw new ClassNotFoundException();
      Object[] args = {this, in};
      try {
        javaObject = adapter_readAdapterObject.invoke(null, args);
      } catch (Exception ex) {
        throw new IOException();
      }
    } else {
      javaObject = in.readObject();
    }

    String className = (String) in.readObject();
    if (className != null) {
      staticType = Class.forName(className);
    } else {
      staticType = null;
    }

    initMembers();
  }
 public static void main(String[] args) {
   if (args.length < 1) {
     print(usage);
     System.exit(0);
   }
   int lines = 0;
   try {
     Class<?> c = Class.forName(args[0]);
     Method[] methods = c.getMethods();
     Constructor[] ctors = c.getConstructors();
     if (args.length == 1) {
       for (Method method : methods) print(p.matcher(method.toString()).replaceAll(""));
       for (Constructor ctor : ctors) print(p.matcher(ctor.toString()).replaceAll(""));
       lines = methods.length + ctors.length;
     } else {
       for (Method method : methods)
         if (method.toString().indexOf(args[1]) != -1) {
           print(p.matcher(method.toString()).replaceAll(""));
           lines++;
         }
       for (Constructor ctor : ctors)
         if (ctor.toString().indexOf(args[1]) != -1) {
           print(p.matcher(ctor.toString()).replaceAll(""));
           lines++;
         }
     }
   } catch (ClassNotFoundException e) {
     print("No such class: " + e);
   }
 }
Ejemplo n.º 17
0
  /**
   * Returns the correct implementation instance for the interface <code>type</code>. For convention
   * the implentation is named <code>InterfaceName + Impl</code>.
   *
   * @param type The interface type
   * @return The correct ModelProxy subclass (if exists), a ModelProxy instance otherwise
   * @throws MalformedModelException is the interface or the implementation are not well formed
   *     (they don't respect the conventions).
   * @throws ModelRuntimeException is any error occurs during the instantiation
   */
  protected ModelProxy createInstance(Class type) {
    Class backClass;
    if (implementations.containsKey(type)) backClass = implementations.get(type);
    else {
      /* type never seen */

      try {
        Package pkg = type.getPackage();
        String pkgN = pkg == null ? "" : pkg.getName();

        backClass = Class.forName(pkgN + tableName(type) + CommonStatic.getImplementationSuffix());

      } catch (Exception e) {
        backClass = ModelProxy.class;
      }

      Validator.validateModel(type, backClass);

      initFieldsTypes(type);
      implementations.put(type, backClass);
    }

    ModelProxy impl = null;
    try {
      impl = (ModelProxy) backClass.newInstance();
    } catch (Exception e) {
      throw new ModelRuntimeException(e.getMessage());
    }

    return impl;
  }
Ejemplo n.º 18
0
  /** JNDI object factory so the proxy can be used as a resource. */
  public Object getObjectInstance(
      Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
    Reference ref = (Reference) obj;

    String api = null;
    String url = null;
    String user = null;
    String password = null;

    for (int i = 0; i < ref.size(); i++) {
      RefAddr addr = ref.get(i);

      String type = addr.getType();
      String value = (String) addr.getContent();

      if (type.equals("type")) api = value;
      else if (type.equals("url")) url = value;
      else if (type.equals("user")) setUser(value);
      else if (type.equals("password")) setPassword(value);
    }

    if (url == null) throw new NamingException("`url' must be configured for HessianProxyFactory.");
    // XXX: could use meta protocol to grab this
    if (api == null)
      throw new NamingException("`type' must be configured for HessianProxyFactory.");

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Class apiClass = Class.forName(api, false, loader);

    return create(apiClass, url);
  }
Ejemplo n.º 19
0
  public static void writeParam(String xNameFile) {
    //
    // write to file xpar all parameters.....
    //
    IOseq xFile;

    xFile = new IOseq(xNameFile);
    xFile.IOseqOpenW(false);

    try {

      Class c = Class.forName("jneat.Neat");
      Field[] fieldlist = c.getDeclaredFields();

      for (int i = 0; i < fieldlist.length; i++) {
        Field f1 = fieldlist[i];
        String x1 = f1.getName();

        if (x1.startsWith("p_")) {
          Field f2 = c.getField("d_" + Neat.normalizeName(x1));
          Object s1 = f1.get(c);
          Object s2 = f2.get(c);
          //	   String riga = s1 + "  " + s2;
          String riga = x1 + "  " + s1;
          xFile.IOseqWrite(riga);
        }
      }

    } catch (Throwable e) {
      System.err.println(e);
    }

    xFile.IOseqCloseW();
  }
Ejemplo n.º 20
0
  public static void main(String[] args) {
    // read class name from command line args or user input
    String name;
    if (args.length > 0) name = args[0];
    else {
      Scanner in = new Scanner(System.in);
      System.out.println("Enter class name (e.g. java.util.Date): ");
      name = in.next();
    }

    try {
      // print class name and superclass name (if != Object)
      Class cl = Class.forName(name);
      Class supercl = cl.getSuperclass();
      String modifiers = Modifier.toString(cl.getModifiers());
      if (modifiers.length() > 0) System.out.print(modifiers + " ");
      System.out.print("class " + name);
      if (supercl != null && supercl != Object.class)
        System.out.print(" extends " + supercl.getName());

      System.out.print("\n{\n");
      printConstructors(cl);
      System.out.println();
      printMethods(cl);
      System.out.println();
      printFields(cl);
      System.out.println("}");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    System.exit(0);
  }
Ejemplo n.º 21
0
  /** Determine whether the current user has Windows administrator privileges. */
  public static boolean isWinAdmin() {
    if (!isWinPlatform()) return false;
    //    for (String group : new com.sun.security.auth.module.NTSystem().getGroupIDs()) {
    //      if (group.equals("S-1-5-32-544")) return true; // "S-1-5-32-544" is a well-known
    // security identifier in Windows. If the current user has it then he/she/it is an
    // administrator.
    //    }
    //    return false;

    try {
      Class<?> ntsys = Class.forName("com.sun.security.auth.module.NTSystem");
      if (ntsys != null) {
        Object groupObj =
            SystemUtils.invoke(
                ntsys.newInstance(), ntsys.getDeclaredMethod("getGroupIDs"), (Object[]) null);
        if (groupObj instanceof String[]) {
          for (String group : (String[]) groupObj) {
            if (group.equals("S-1-5-32-544"))
              return true; // "S-1-5-32-544" is a well-known security identifier in Windows. If the
                           // current user has it then he/she/it is an administrator.
          }
        }
      }
    } catch (ReflectiveOperationException e) {
      System.err.println(e);
    }
    return false;
  }
Ejemplo n.º 22
0
  private /*synchronized*/ StructureType assignStructureType(String structType)
      throws VisualizerLoadException {

    if (debug) System.out.println("In assignStructureType with " + structType);

    // Handle objects whose constructors require args separately
    if ((structType.toUpperCase().compareTo("BAR") == 0)
        || (structType.toUpperCase().compareTo("SCAT") == 0))
      return (new BarScat(structType.toUpperCase()));
    else if ((structType.toUpperCase().compareTo("GRAPH") == 0)
        || (structType.toUpperCase().compareTo("NETWORK") == 0))
      return (new Graph_Network(structType.toUpperCase()));
    else { // Constructor for object does not require args

      try {
        return ((StructureType)
            ((Class.forName(insure_text_case_correct_for_legacy_scripts(structType)))
                .newInstance()));
      } catch (InstantiationException e) {
        System.out.println(e);
        throw (new VisualizerLoadException(structType + " is invalid structure type"));
      } catch (IllegalAccessException e) {
        System.out.println(e);
        throw (new VisualizerLoadException(structType + " is invalid structure type"));
      } catch (ClassNotFoundException e) {
        System.out.println(e);
        throw (new VisualizerLoadException(structType + " is invalid structure type"));
      }
    }
  }
 public static void main(String[] args) throws Exception {
   Class clazz = Class.forName("com.mtl.spring.aop.helloworld.ArithmeticCalculatorLoggingProxy");
   Object object = clazz.newInstance();
   Method[] methods = clazz.getMethods();
   StringBuffer sb = new StringBuffer();
   sb.append("public class ")
       .append(object.getClass().getCanonicalName())
       .append("{\n")
       .append("Object object ")
       .append("\n");
   Constructor[] constructors = clazz.getConstructors();
   for (Constructor constructor : constructors) {
     sb.append("\npublic ").append(constructor.getName()).append("(");
     Class<?> p[] = constructor.getParameterTypes();
     for (int j = 0; j < p.length; ++j) {
       sb.append(p[j].getName() + " arg" + j);
       if (j < p.length - 1) {
         sb.delete(sb.length() - 1, sb.length());
       }
     }
     sb.append(") {").append("\n\n");
     sb.append("user.role.cotain(\"/admin/add\") {");
     sb.append("\n System.currentTimeMillis();\n");
     sb.append("this.object  = ").append("arg0");
     sb.append("}");
     sb.append(" \nSystem.currentTimeMillis();\n");
     sb.append("\n}");
   }
   sb.append("\n\n}");
   System.out.println(sb);
   for (Method method : methods) {
     System.out.println(method.getName());
   }
 }
Ejemplo n.º 24
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");
   }
 }
Ejemplo n.º 25
0
 static {
   ParticleUtils.version = "";
   try {
     ParticleUtils.version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];
     ParticleUtils.packetType = Class.forName(getPacketPlayOutParticles());
     final Class<?> typeCraftPlayer = Class.forName(getCraftPlayerClasspath());
     final Class<?> typeNMSPlayer = Class.forName(getNMSPlayerClasspath());
     final Class<?> typePlayerConnection = Class.forName(getPlayerConnectionClasspath());
     ParticleUtils.getHandle = typeCraftPlayer.getMethod("getHandle", (Class<?>[]) new Class[0]);
     ParticleUtils.playerConnection = typeNMSPlayer.getField("playerConnection");
     ParticleUtils.sendPacket =
         typePlayerConnection.getMethod("sendPacket", Class.forName(getPacketClasspath()));
   } catch (Exception e) {
     System.out.println("Failed to setup reflection for PacketPlayOutWorldParticles");
     e.printStackTrace();
   }
 }
Ejemplo n.º 26
0
 /**
  * This creates an empty <code>Document</code> object based on a specific parser implementation.
  *
  * @return <code>Document</code> - created DOM Document.
  * @throws JDOMException when errors occur.
  */
 public Document createDocument() throws JDOMException {
   try {
     return (Document) Class.forName("org.apache.xerces.dom.DocumentImpl").newInstance();
   } catch (Exception e) {
     throw new JDOMException(
         e.getClass().getName() + ": " + e.getMessage() + " when creating document", e);
   }
 }
Ejemplo n.º 27
0
 static void javac(String... args) throws Exception {
   Class c = Class.forName("pl.wcislo.sbql4j.tools.javac.Main", true, cl);
   int status =
       (Integer)
           c.getMethod("compile", new Class[] {String[].class})
               .invoke(c.newInstance(), new Object[] {args});
   if (status != 0) throw new Exception("javac failed: status=" + status);
 }
Ejemplo n.º 28
0
 public static boolean isMySubclass(Class other) {
   try {
     return Class.forName(SIP_PACKAGE + ".GenericObject").isAssignableFrom(other);
   } catch (Exception ex) {
     InternalErrorHandler.handleException(ex);
   }
   return false;
 }
Ejemplo n.º 29
0
 public static Class getClassFromName(String className) {
   try {
     return Class.forName(className);
   } catch (Exception ex) {
     InternalErrorHandler.handleException(ex);
     return null;
   }
 }
 /**
  * register a class indicated by name
  *
  * @param kryo
  * @param s name of a class - might not exist
  * @param handled Set of classes already handles
  */
 protected void doRegistration(@Nonnull Kryo kryo, @Nonnull String s) {
   Class c;
   try {
     c = Class.forName(s);
     doRegistration(kryo, c);
   } catch (ClassNotFoundException e) {
     return;
   }
 }