Example #1
0
 public static void setField(Field field, Object object, Object value) {
   try {
     field.setAccessible(true);
     field.set(object, value);
   } catch (IllegalArgumentException e) {
     throw new ActivitiException("Could not set field " + field.toString(), e);
   } catch (IllegalAccessException e) {
     throw new ActivitiException("Could not set field " + field.toString(), e);
   }
 }
Example #2
0
  private static void writeVariables(String _package, String _class, String _object)
      throws Exception {
    // out.printf( "\t//varaibles defined in %s%s (and its super classes/interfaces)\n\n", _package,
    // _class );

    Class gl_class = Class.forName(_package + _class);

    // Field[] fields = gl_class.getDeclaredFields(); // returns private fields

    Field[] fields = gl_class.getFields(); // only public fields

    for (Field f : fields) {
      String s = f.toString();

      int i1 = s.lastIndexOf(".");

      String s1 = s.substring(0, i1);

      int i2 = s1.lastIndexOf(' ');

      String s2 = s1.substring(0, i2);

      s1 = s1.substring(i2 + 1);

      out.printf("\t%s %s = %s.%s;\n", s2, f.getName(), s1, f.getName());
    }
  }
  protected static Class getCollectionType(Field field) {
    if (field.isAnnotationPresent(EDICollectionType.class)) {
      return field.getAnnotation(EDICollectionType.class).value();
    }

    LOG.warn(
        "Ensure the field: " + field.toString() + " contains the @EDICollectionType annotation.");
    return null;
  }
  private void checkFields(Object obj, ObjectStreamClass desc) {
    int numFields;
    try {
      numFields = (Integer) GET_NUM_OBJ_FIELDS_METHOD.invoke(desc, (Object[]) null);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
      throw new RuntimeException(e);
    }

    if (numFields > 0) {
      int numPrimFields;
      ObjectStreamField[] fields = desc.getFields();
      Object[] objVals = new Object[numFields];
      numPrimFields = fields.length - objVals.length;
      try {
        GET_OBJ_FIELD_VALUES_METHOD.invoke(desc, obj, objVals);
      } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
      } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
      }
      for (int i = 0; i < objVals.length; i++) {
        if (objVals[i] instanceof String
            || objVals[i] instanceof Number
            || objVals[i] instanceof Date
            || objVals[i] instanceof Boolean
            || objVals[i] instanceof Class) {
          // filter out common cases
          continue;
        }

        // Check for circular reference.
        if (checked.containsKey(objVals[i])) {
          continue;
        }

        ObjectStreamField fieldDesc = fields[numPrimFields + i];
        Field field;
        try {
          field = (Field) GET_FIELD_METHOD.invoke(fieldDesc, (Object[]) null);
        } catch (IllegalAccessException e) {
          throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
          throw new RuntimeException(e);
        }

        field.getName();
        simpleName = field.getName();
        fieldDescription = field.toString();
        check(objVals[i]);
      }
    }
  }
  private void saniteettitarkastus() throws SecurityException {
    Field[] kentat = ReflectionUtils.findClass(luokanNimi).getDeclaredFields();

    for (Field field : kentat) {
      assertFalse(
          "does not need \"static variables\", remove " + kentta(field.toString()),
          field.toString().contains("static") && !field.toString().contains("final"));
      assertTrue(
          "all the object variables should be private, please change " + kentta(field.toString()),
          field.toString().contains("private"));
    }

    if (kentat.length > 1) {
      int var = 0;
      for (Field field : kentat) {
        if (!field.toString().contains("final")) {
          var++;
        }
      }
      assertTrue(
          "The class "
              + luokanNimi
              + " needs only instance variable for the amount of weightings, remove the extra "
              + "",
          var < 2);
    }
  }
  private void saniteettitarkastus(int n, String m) throws SecurityException {
    Field[] kentat = ReflectionUtils.findClass(luokanNimi).getDeclaredFields();
    for (Field field : kentat) {
      assertFalse(
          "does not need \"static variables\", remove " + kentta(field.toString()),
          field.toString().contains("static") && !field.toString().contains("final"));
      assertTrue(
          "all the object variables should be private, please change " + kentta(field.toString()),
          field.toString().contains("private"));
    }
    if (kentat.length > 1) {
      int var = 0;
      for (Field field : kentat) {
        if (!field.toString().contains("final")) {
          var++;
          System.err.println("JAMO:fields");
        }
      }
      String s = n > 1 ? "s" : "";

      assertTrue(
          "The class "
              + klassName
              + " needs instance variable"
              + s
              + " only for "
              + m
              + ", remove the rest",
          var <= n);
    }
  }
Example #7
0
 private List<Field> buildFieldsList(List<Field> result, Set<String> seen, boolean publicOnly) {
   for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
     for (Field f : c.getClassCache().getDeclaredFields(false, publicOnly)) {
       String s = f.toString();
       if (!seen.contains(s)) {
         result.add(f);
         seen.add(s);
       }
     }
     for (Class<?> intf : c.getInterfaces()) {
       intf.getClassCache().buildFieldsList(result, seen, publicOnly);
     }
   }
   return result;
 }
Example #8
0
 private void sendClassInfo(Class<?> clazz) {
   StringBuilder sb = new StringBuilder();
   sb.append(clazz.getName());
   sb.append("\r\n");
   sb.append("\r\n");
   for (Constructor<?> constructor : clazz.getConstructors()) {
     sb.append(constructor.toString());
     sb.append("\r\n");
   }
   sb.append("\r\n");
   for (Method method : clazz.getDeclaredMethods()) {
     sb.append(method.toString());
     sb.append("\r\n");
   }
   sb.append("\r\n");
   for (Field field : clazz.getDeclaredFields()) {
     sb.append(field.toString());
     sb.append("\r\n");
   }
   sb.append("\r\n");
   sendSupportInfo(sb.toString());
 }
 public String toString() {
   return javaField.toString();
 }
 @Override
 public String toString() {
   return "[ReflectionField: " + field.toString() + "]";
 }
Example #11
0
  /**
   * @param args The arguments you want to launch Minecraft with. New path, Username, Session ID.
   */
  public static void main(String[] args) {
    if (args.length < 3) {
      System.out.println("Not enough arguments.");
      System.exit(-1);
    }

    // Set the OSX application icon first, if we are on OSX.
    Application application = new DefaultApplication();
    if (application.isMac()) {
      try {
        BufferedImage image = ImageIO.read(new File("icon.png"));
        application.setApplicationIconImage(image);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    String userName = args[0];
    String sessionId = args[1];
    String windowtitle = args[2];
    String cwd = System.getProperty("user.dir");
    String encoding = System.getProperty("file.encoding");
    System.out.println("File encoding: " + encoding);

    Dimension winSize = new Dimension(854, 480);
    boolean maximize = false;
    boolean compatMode = false;

    if (args.length >= 4) {
      String windowParams = args[3];
      String[] dimStrings = windowParams.split("x");

      if (windowParams.equalsIgnoreCase("compatmode")) {
        compatMode = true;
      } else if (windowParams.equalsIgnoreCase("max")) {
        maximize = true;
      } else if (dimStrings.length == 2) {
        try {
          winSize = new Dimension(Integer.parseInt(dimStrings[0]), Integer.parseInt(dimStrings[1]));
        } catch (NumberFormatException e) {
          System.out.println("Invalid Window size argument, " + "using default.");
        }
      } else {
        System.out.println("Invalid Window size argument, " + "using default.");
      }
    }

    try {
      System.out.println("Loading jars...");
      String[] jarFiles =
          new String[] {"minecraft.jar", "lwjgl.jar", "lwjgl_util.jar", "jinput.jar"};

      URL[] urls = new URL[jarFiles.length];

      for (int i = 0; i < urls.length; i++) {
        try {
          File f = new File(new File(cwd, "bin"), jarFiles[i]);
          urls[i] = f.toURI().toURL();
          System.out.println("Loading URL: " + urls[i].toString());
        } catch (MalformedURLException e) {
          //					e.printStackTrace();
          System.err.println("MalformedURLException, " + e.toString());
          System.exit(5);
        }
      }

      System.out.println("Loading natives...");
      String nativesDir = new File(new File(cwd, "bin"), "natives").toString();

      System.setProperty("org.lwjgl.librarypath", nativesDir);
      System.setProperty("net.java.games.input.librarypath", nativesDir);

      URLClassLoader cl = new URLClassLoader(urls, MultiMCLauncher.class.getClassLoader());

      // Get the Minecraft Class.
      Class<?> mc = null;
      try {
        mc = cl.loadClass("net.minecraft.client.Minecraft");

        Field f = getMCPathField(mc);

        if (f == null) {
          System.err.println("Could not find Minecraft path field. Launch failed.");
          System.exit(-1);
        }

        f.setAccessible(true);
        f.set(null, new File(cwd));
        // And set it.
        System.out.println("Fixed Minecraft Path: Field was " + f.toString());
      } catch (ClassNotFoundException e) {
        System.err.println("Can't find main class. Searching...");

        // Look for any class that looks like the main class.
        File mcJar = new File(new File(cwd, "bin"), "minecraft.jar");
        ZipFile zip = null;
        try {
          zip = new ZipFile(mcJar);
        } catch (ZipException e1) {
          e1.printStackTrace();
          System.err.println("Search failed.");
          System.exit(-1);
        } catch (IOException e1) {
          e1.printStackTrace();
          System.err.println("Search failed.");
          System.exit(-1);
        }

        Enumeration<? extends ZipEntry> entries = zip.entries();
        ArrayList<String> classes = new ArrayList<String>();

        while (entries.hasMoreElements()) {
          ZipEntry entry = entries.nextElement();
          if (entry.getName().endsWith(".class")) {
            String entryName = entry.getName().substring(0, entry.getName().lastIndexOf('.'));
            entryName = entryName.replace('/', '.');
            System.out.println("Found class: " + entryName);
            classes.add(entryName);
          }
        }

        for (String clsName : classes) {
          try {
            Class<?> cls = cl.loadClass(clsName);
            if (!Runnable.class.isAssignableFrom(cls)) {
              continue;
            } else {
              System.out.println("Found class implementing runnable: " + cls.getName());
            }

            if (getMCPathField(cls) == null) {
              continue;
            } else {
              System.out.println(
                  "Found class implementing runnable " + "with mcpath field: " + cls.getName());
            }

            mc = cls;
            break;
          } catch (ClassNotFoundException e1) {
            // Ignore
            continue;
          }
        }

        if (mc == null) {
          System.err.println("Failed to find Minecraft main class.");
          System.exit(-1);
        } else {
          System.out.println("Found main class: " + mc.getName());
        }
      }

      System.setProperty("minecraft.applet.TargetDirectory", cwd);

      String[] mcArgs = new String[2];
      mcArgs[0] = userName;
      mcArgs[1] = sessionId;

      // this is bogus, the method is never used for anything after we set the field
      /*
      String mcDir = 	mc.getMethod("a", String.class).invoke(null, (Object) "minecraft").toString();

      System.out.println("MCDIR: " + mcDir);
      */

      if (compatMode) {
        System.out.println("Launching in compatibility mode...");
        mc.getMethod("main", String[].class).invoke(null, (Object) mcArgs);
      } else {
        System.out.println("Launching with applet wrapper...");
        try {
          Class<?> MCAppletClass = cl.loadClass("net.minecraft.client.MinecraftApplet");
          Applet mcappl = (Applet) MCAppletClass.newInstance();
          MCFrame mcWindow = new MCFrame(windowtitle);
          mcWindow.start(mcappl, userName, sessionId, winSize, maximize);
        } catch (InstantiationException e) {
          System.out.println("Applet wrapper failed! Falling back " + "to compatibility mode.");
          mc.getMethod("main", String[].class).invoke(null, (Object) mcArgs);
        }
      }
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
      System.exit(1);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      System.exit(2);
    } catch (IllegalAccessException e) {
      e.printStackTrace();
      System.exit(2);
    } catch (InvocationTargetException e) {
      e.printStackTrace();
      System.exit(3);
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
      System.exit(3);
    } catch (SecurityException e) {
      e.printStackTrace();
      System.exit(4);
    }
  }
 @Override
 public String toString() {
   return field.toString();
 }
 @Test
 public void testToString() throws Exception {
   assertThat(describe(first).toString(), is(first.toString()));
   assertThat(describe(second).toString(), is(second.toString()));
 }
  /**
   * Parses the parameters from content, assigns them to variables in obj.
   *
   * @param content contains the parameters to read.
   * @param obj object with the variables to assign.
   */
  public void parseParameters(Content content, Object obj) {
    // Get all fields from the class and store it as key->field
    Field[] fields = obj.getClass().getFields();
    HashMap<String, Field> fieldMap = new HashMap<String, Field>();
    for (Field field : fields) {
      String strField = field.toString();
      int lastDot = strField.lastIndexOf(".");
      String fieldName = strField.substring(lastDot + 1).trim();

      fieldMap.put(fieldName, field);
    }
    Object objVal = null;
    Field cfield = null;
    // Check all parameters from content
    for (String parameter : content.parameters.keySet()) {
      String value = content.parameters.get(parameter);
      if (fieldMap.containsKey(parameter)) {

        try {
          cfield = Types.processField(value);
          objVal = cfield.get(null);
        } catch (Exception e) {
          try {
            if (!parameter.equalsIgnoreCase("scoreChange")) objVal = Integer.parseInt(value);
            else objVal = value;
          } catch (NumberFormatException e1) {
            try {
              objVal = Double.parseDouble(value);
            } catch (NumberFormatException e2) {
              try {
                if ((value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false"))
                    && !parameter.equalsIgnoreCase("win")) objVal = Boolean.parseBoolean(value);
                else objVal = value;
              } catch (NumberFormatException e3) {
                objVal = value;
              }
            }
          }
        }
        try {
          fieldMap.get(parameter).set(obj, objVal);
        } catch (IllegalAccessException e) {
          e.printStackTrace(); // To change body of catch statement use File | Settings | File
          // Templates.
        } catch (Exception e) {
          e.printStackTrace();
        }
      } else {
        // Ignore unknown fields in dependent Effects (TimeEffect).
        boolean warn = true;
        boolean isInteraction = (content instanceof InteractionContent);
        if (isInteraction) {
          boolean isTimeEffect =
              ((InteractionContent) content).object2[0].equalsIgnoreCase("TIME")
                  || ((InteractionContent) content).object1.equalsIgnoreCase("TIME")
                  || (((InteractionContent) content).line.contains("addTimer"));
          if (isTimeEffect) warn = false;
        }

        if (warn)
          System.out.println(
              "Unknown field (" + parameter + "=" + value + ") from " + content.toString());
      }
    }
  }
Example #15
0
  public static void main(String[] args) {
    String basepath = args[0];
    String forgename = args[1];
    String username = args[2];
    String password = args[3];
    String modPackName = args[4];
    String modPackImageName = args[5];
    String minecraftX = args[6];
    String minecraftY = args[7];
    String minecraftXPos = args[8];
    String minecraftYPos = args[9];
    String minecraftMax = args[10];
    String centerWindow = args[11];

    try {
      System.out.println("Loading jars...");
      String[] jarFiles =
          new String[] {"minecraft.jar", "lwjgl.jar", "lwjgl_util.jar", "jinput.jar"};
      HashMap<Integer, File> map = new HashMap<Integer, File>();
      int counter = 0;
      File tempDir = new File(new File(basepath).getParentFile(), "instMods/");
      if (tempDir.isDirectory()) {
        for (String name : tempDir.list()) {
          if (!name.equalsIgnoreCase(forgename)) {
            if (name.toLowerCase().endsWith(".zip") || name.toLowerCase().endsWith(".jar")) {
              map.put(counter, new File(tempDir, name));
              counter++;
            }
          }
        }
      }

      map.put(counter, new File(tempDir, forgename));
      counter++;
      for (String jarFile : jarFiles) {
        map.put(counter, new File(new File(basepath, "bin"), jarFile));
        counter++;
      }

      URL[] urls = new URL[map.size()];
      for (int i = 0; i < counter; i++) {
        try {
          urls[i] = map.get(i).toURI().toURL();
        } catch (MalformedURLException e) {
          e.printStackTrace();
        }
        System.out.println("Loading URL: " + urls[i].toString());
      }

      System.out.println("Loading natives...");
      String nativesDir = new File(new File(basepath, "bin"), "natives").toString();
      System.out.println("Natives loaded...");

      System.setProperty("org.lwjgl.librarypath", nativesDir);
      System.setProperty("net.java.games.input.librarypath", nativesDir);

      System.setProperty("user.home", new File(basepath).getParent());

      URLClassLoader cl = new URLClassLoader(urls, MinecraftLauncher.class.getClassLoader());

      System.out.println("Loading minecraft class");
      Class<?> mc = cl.loadClass("net.minecraft.client.Minecraft");
      System.out.println("mc = " + mc);
      Field[] fields = mc.getDeclaredFields();
      System.out.println("field amount: " + fields.length);

      for (Field f : fields) {
        if (f.getType() != File.class) {
          continue;
        }
        if (0 == (f.getModifiers() & (Modifier.PRIVATE | Modifier.STATIC))) {
          continue;
        }
        f.setAccessible(true);
        f.set(null, new File(basepath));
        System.out.println("Fixed Minecraft Path: Field was " + f.toString());
        break;
      }

      String[] mcArgs = new String[2];
      mcArgs[0] = username;
      mcArgs[1] = password;

      String mcDir = mc.getMethod("a", String.class).invoke(null, (Object) "minecraft").toString();

      System.out.println("MCDIR: " + mcDir);

      System.out.println("Launching with applet wrapper...");

      try {
        Class<?> MCAppletClass = cl.loadClass("net.minecraft.client.MinecraftApplet");
        Applet mcappl = (Applet) MCAppletClass.newInstance();
        MinecraftFrame mcWindow =
            new MinecraftFrame(
                modPackName,
                modPackImageName,
                Integer.parseInt(minecraftX),
                Integer.parseInt(minecraftY),
                Integer.parseInt(minecraftXPos),
                Integer.parseInt(minecraftYPos),
                Boolean.parseBoolean(minecraftMax),
                Boolean.parseBoolean(centerWindow));
        mcWindow.start(mcappl, mcArgs[0], mcArgs[1]);
      } catch (InstantiationException e) {
        Logger.log("Applet wrapper failed! Falling back to compatibility mode.", LogLevel.WARN, e);
        mc.getMethod("main", String[].class).invoke(null, (Object) mcArgs);
      }
    } catch (Exception e) {
    }
  }