Example #1
0
 Object createGuiElement(Class cls, EntityPlayer player, World world, int x, int y, int z) {
   try {
     try {
       if (debugGui)
         System.out.printf(
             "BaseMod.createGuiElement: Invoking create method of %s for %s in %s\n",
             cls, player, world);
       return cls.getMethod(
               "create", EntityPlayer.class, World.class, int.class, int.class, int.class)
           .invoke(null, player, world, x, y, z);
     } catch (NoSuchMethodException e) {
       if (debugGui)
         System.out.printf("BaseMod.createGuiElement: Invoking constructor of %s\n", cls);
       return cls.getConstructor(EntityPlayer.class, World.class, int.class, int.class, int.class)
           .newInstance(player, world, x, y, z);
     }
   } catch (Exception e) {
     Throwable cause = e.getCause();
     System.out.printf("BaseMod.createGuiElement: %s: %s\n", e, cause);
     if (cause != null) cause.printStackTrace();
     else e.printStackTrace();
     // throw new RuntimeException(e);
     return null;
   }
 }
  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();
  }
 private String readVersionFromManifest(Class<?> api) throws IOException {
   String className = api.getSimpleName() + ".class";
   URL resource = api.getResource(className);
   log.trace("get resource for {} -> {} -> {}", new Object[] {className, pathOf(api), resource});
   if (resource == null) return null;
   String version = null;
   String classPath = resource.toString();
   if (classPath.startsWith("jar:"))
     version = version(classPath.substring(0, classPath.lastIndexOf("!") + 1));
   if (version == null && classPath.endsWith(pathOf(api) + ".class"))
     version = version(classPath.substring(0, classPath.length() - pathOf(api).length() - 7));
   if (version == null && classPath.contains("/WEB-INF/"))
     version = version(classPath.substring(0, classPath.lastIndexOf("/WEB-INF/")));
   log.debug("version {} for {} from {}.", version, api, classPath);
   return version;
 }
Example #4
0
 public <BLOCK extends Block> BLOCK newBlock(
     String name, Class<BLOCK> cls, Class itemClass, String title) {
   try {
     int id = config.getBlock(name, 4095).getInt();
     Constructor<BLOCK> ctor = cls.getConstructor(int.class);
     BLOCK block = ctor.newInstance(id);
     String qualName = assetKey + ":" + name;
     block.setUnlocalizedName(qualName);
     // block.func_111022_d(qualName.toLowerCase()); // Set default icon name
     // block.func_111022_d(qualName); // Set default icon name
     block.setTextureName(qualName); // Set default icon name
     GameRegistry.registerBlock(block, itemClass);
     if (title != null) {
       LanguageRegistry.addName(block, title);
       if (clientSide) {
         // System.out.printf("%s: BaseMod.newBlock: %s: creative tab = %s\n",
         //	this, block.getUnlocalizedName(), block.getCreativeTabToDisplayOn());
         if (block.getCreativeTabToDisplayOn() == null && !title.startsWith("["))
           block.setCreativeTab(CreativeTabs.tabMisc);
       }
     }
     if (block instanceof IBlock) registeredBlocks.add((IBlock) block);
     return block;
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
 public static void initializeClass(final Class<?> theClass) {
   final Constructor<?>[] cons = theClass.getDeclaredConstructors();
   if (cons != null && cons.length > 0 && cons[0] != null) {
     final String[] strs = new String[256];
     try {
       cons[0].newInstance((Object[]) strs);
     } catch (Exception ex) {
     }
   }
 }
Example #6
0
 public void registerEntity(
     Class<? extends Entity> cls,
     String name,
     int id,
     int updateFrequency,
     boolean sendVelocityUpdates) {
   System.out.printf(
       "%s: BaseMod.registerEntity: %s, \"%s\", %s\n",
       getClass().getSimpleName(), cls.getSimpleName(), name, id);
   EntityRegistry.registerModEntity(
       cls, name, id, /*base*/ this, 256, updateFrequency, sendVelocityUpdates);
 }
 static {
   FILE_UTILS = FileUtils.getFileUtils();
   AntClassLoader.pathMap = Collections.synchronizedMap(new HashMap<String, String>());
   AntClassLoader.subClassToLoad = null;
   CONSTRUCTOR_ARGS = new Class[] {ClassLoader.class, Project.class, Path.class, Boolean.TYPE};
   if (JavaEnvUtils.isAtLeastJavaVersion("1.5")) {
     try {
       AntClassLoader.subClassToLoad =
           Class.forName("org.apache.tools.ant.loader.AntClassLoader5");
     } catch (ClassNotFoundException ex) {
     }
   }
 }
  private static List<Module> runDefineModules(String moduleFile, ClassFileFactory factory) {
    File stdlibJar = CompilerPathUtil.getRuntimePath();
    GeneratedClassLoader loader;
    if (stdlibJar != null) {
      try {
        loader =
            new GeneratedClassLoader(
                factory,
                new URLClassLoader(
                    new URL[] {stdlibJar.toURI().toURL()}, AllModules.class.getClassLoader()));
      } catch (MalformedURLException e) {
        throw new RuntimeException(e);
      }
    } else {
      loader =
          new GeneratedClassLoader(
              factory, K2JVMCompileEnvironmentConfiguration.class.getClassLoader());
    }
    try {
      Class namespaceClass = loader.loadClass(JvmAbi.PACKAGE_CLASS);
      final Method method = namespaceClass.getDeclaredMethod("project");
      if (method == null) {
        throw new CompileEnvironmentException(
            "Module script " + moduleFile + " must define project() function");
      }

      method.setAccessible(true);
      method.invoke(null);

      ArrayList<Module> answer = new ArrayList<Module>(AllModules.modules.get());
      AllModules.modules.get().clear();
      return answer;
    } catch (Exception e) {
      throw new ModuleExecutionException(e);
    } finally {
      loader.dispose();
    }
  }
 public String getVersion(Class<?> api) {
   log.trace("getVersion for {}", api);
   Package pkg = api.getPackage();
   log.trace("    -> {}/{}", pkg.getImplementationVersion(), pkg.getSpecificationVersion());
   String version = pkg.getSpecificationVersion();
   if (version == null) version = pkg.getImplementationVersion();
   if (version == null) {
     try {
       version = readVersionFromManifest(api);
     } catch (IOException e) {
       log.error("Could not extract version for " + api, e);
       return null;
     }
   }
   return version;
 }
Example #10
0
  public static void premain(String args, Instrumentation inst) throws Exception {
    try {
      String[] agentArgs;
      if (args == null) agentArgs = new String[] {""};
      else agentArgs = args.split(",");
      if (!agentArgs[0].equals("instrumenting")) jarFileName = agentArgs[0];
      BaseClassTransformer rct = null;
      rct = new BaseClassTransformer();
      if (agentArgs[0].equals("instrumenting")) {
        initVMClasses = new HashSet<String>();
        for (Class<?> c : inst.getAllLoadedClasses()) {
          ((Set<String>) initVMClasses).add(c.getName());
        }
      }
      if (!agentArgs[0].equals("instrumenting")) {

        inst.addTransformer(rct);
        Tracer.setLocals(new CounterThreadLocal());
        Tracer.overrideAll(true);
        for (Class<?> c : inst.getAllLoadedClasses()) {
          try {
            if (c.isInterface()) continue;
            if (c.isArray()) continue;
            byte[] bytes = rct.getBytes(c.getName());
            if (bytes == null) {
              continue;
            }
            inst.redefineClasses(new ClassDefinition[] {new ClassDefinition(c, bytes)});
          } catch (Throwable e) {
            synchronized (System.err) {
              System.err.println("" + c + " failed...");
              e.printStackTrace();
            }
          }
        }
        Runtime.getRuntime()
            .addShutdownHook(
                new Thread() {
                  public void run() {
                    Tracer.mark();
                    try {
                      PrintStream ps = new PrintStream("bailout.txt");
                      ps.println("Bailouts: " + Tracer.getBailoutCount());
                      ps.close();
                    } catch (Exception e) {
                    }
                    Tracer.unmark();
                  }
                });
        if ("true".equals(System.getProperty("bci.observerOn"))) Tracer.overrideAll(false);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #11
0
  /** Loads internal services */
  private void loadInternalServices() {
    try {
      Iterator services;
      String servicename;
      String baseURL = System.getProperty("user.dir") + "/" + APPLICATIONS_DIRECTORY;

      LucaneClassLoader loader = LucaneClassLoader.getInstance();
      services = store.getServiceStore().getAllServices();

      while (services.hasNext()) {
        ServiceConcept service = (ServiceConcept) services.next();
        servicename = service.getName();
        try {
          loader.addUrl(new URL("jar:file:///" + baseURL + servicename + ".jar!/"));
          String className =
              (new JarFile(baseURL + servicename + ".jar"))
                  .getManifest()
                  .getMainAttributes()
                  .getValue("Service-Class");

          if (className == null) continue;

          Service serv = (Service) Class.forName(className, true, loader).newInstance();
          this.services.add(serv);
          serv.init(this);

          if (!service.isInstalled()) {
            serv.install();
            service.setInstalled();
            store.getServiceStore().updateService(service);
          }

          Logging.getLogger().info("Service '" + servicename + "' loaded.");
          this.connections.add(
              new ConnectInfo(servicename, serverIp, serverIp, port, "nokey", "service"));
        } catch (Exception e) {
          Logging.getLogger().warning("Unable to load service '" + servicename);
        }
      }
    } catch (Exception e) {
      Logging.getLogger().warning("Unable to load internal services : " + e);
      e.printStackTrace();
    }
  }
Example #12
0
 public <ITEM extends Item> ITEM newItem(String name, Class<ITEM> cls, String title) {
   try {
     int id = config.getItem(name, 31743).getInt();
     Constructor<ITEM> ctor = cls.getConstructor(int.class);
     ITEM item = ctor.newInstance(id);
     String qualName = assetKey + ":" + name;
     item.setUnlocalizedName(qualName);
     // item.func_111206_d(qualName.toLowerCase()); // Set default icon name
     // item.func_111206_d(qualName); // Set default icon name
     item.setTextureName(qualName); // Set default icon name
     LanguageRegistry.addName(item, title);
     if (clientSide) {
       if (item.getCreativeTab() == null) item.setCreativeTab(CreativeTabs.tabMisc);
     }
     // System.out.printf("BaseMod.newItem: %s unlocalizedName = %s title = %s\n",
     //	item, item.getUnlocalizedName(), title);
     return item;
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Example #13
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);
 }
Example #14
0
  public static void preventEventualClassLoadingConflicts() {
    // Pre-load certain JMockit classes to avoid NoClassDefFoundError's or re-entrancy loops during
    // class loading
    // when certain JRE classes are mocked, such as ArrayList or Thread.
    try {
      Class.forName("mockit.Capturing");
      Class.forName("mockit.Delegate");
      Class.forName("mockit.Invocation");
      Class.forName("mockit.internal.RedefinitionEngine");
      Class.forName("mockit.internal.util.GeneratedClasses");
      Class.forName("mockit.internal.util.MethodReflection");
      Class.forName("mockit.internal.util.ObjectMethods");
      Class.forName("mockit.internal.util.TypeDescriptor");
      Class.forName("mockit.internal.expectations.RecordAndReplayExecution");
      Class.forName("mockit.internal.expectations.invocation.InvocationResults");
      Class.forName("mockit.internal.expectations.invocation.MockedTypeCascade");
      Class.forName("mockit.internal.expectations.mocking.BaseTypeRedefinition$MockedClass");
      Class.forName("mockit.internal.expectations.mocking.SharedFieldTypeRedefinitions");
      Class.forName("mockit.internal.expectations.mocking.TestedClasses");
      Class.forName("mockit.internal.expectations.argumentMatching.EqualityMatcher");
    } catch (ClassNotFoundException ignore) {
    }

    wasCalledDuringClassLoading();
    DefaultValues.computeForReturnType("()J");
  }
  public static void main(String[] args) throws Exception {
    System.out.println(
        "Checking that all known MBeans that are "
            + "NotificationBroadcasters have sane "
            + "MBeanInfo.getNotifications()");

    System.out.println("Checking platform MBeans...");
    checkPlatformMBeans();

    URL codeBase = ClassLoader.getSystemResource("javax/management/MBeanServer.class");
    if (codeBase == null) {
      throw new Exception("Could not determine codeBase for " + MBeanServer.class);
    }

    System.out.println();
    System.out.println("Looking for standard MBeans...");
    String[] classes = findStandardMBeans(codeBase);

    System.out.println("Testing standard MBeans...");
    for (int i = 0; i < classes.length; i++) {
      String name = classes[i];
      Class<?> c;
      try {
        c = Class.forName(name);
      } catch (Throwable e) {
        System.out.println(name + ": cannot load (not public?): " + e);
        continue;
      }
      if (!NotificationBroadcaster.class.isAssignableFrom(c)) {
        System.out.println(name + ": not a NotificationBroadcaster");
        continue;
      }
      if (Modifier.isAbstract(c.getModifiers())) {
        System.out.println(name + ": abstract class");
        continue;
      }

      NotificationBroadcaster mbean;
      Constructor<?> constr;
      try {
        constr = c.getConstructor();
      } catch (Exception e) {
        System.out.println(name + ": no public no-arg constructor: " + e);
        continue;
      }
      try {
        mbean = (NotificationBroadcaster) constr.newInstance();
      } catch (Exception e) {
        System.out.println(name + ": no-arg constructor failed: " + e);
        continue;
      }

      check(mbean);
    }

    System.out.println();
    System.out.println("Testing some explicit cases...");

    check(new RelationService(false));
    /*
      We can't do this:
        check(new RequiredModelMBean());
      because the Model MBean spec more or less forces us to use the
      names GENERIC and ATTRIBUTE_CHANGE for its standard notifs.
    */
    checkRMIConnectorServer();

    System.out.println();
    if (!suspicious.isEmpty()) System.out.println("SUSPICIOUS CLASSES: " + suspicious);

    if (failed.isEmpty()) System.out.println("TEST PASSED");
    else {
      System.out.println("TEST FAILED: " + failed);
      System.exit(1);
    }
  }
 private String pathOf(Class<?> api) {
   return api.getCanonicalName().replace('.', '/');
 }