Пример #1
0
 private String getExifData(ImagePlus imp) {
   FileInfo fi = imp.getOriginalFileInfo();
   if (fi == null) return null;
   String directory = fi.directory;
   String name = fi.fileName;
   if (directory == null) return null;
   if ((name == null || name.equals("")) && imp.getStack().isVirtual())
     name = imp.getStack().getSliceLabel(imp.getCurrentSlice());
   if (name == null || !(name.endsWith("jpg") || name.endsWith("JPG"))) return null;
   String path = directory + name;
   String metadata = null;
   try {
     Class c = IJ.getClassLoader().loadClass("Exif_Reader");
     if (c == null) return null;
     String methodName = "getMetadata";
     Class[] argClasses = new Class[1];
     argClasses[0] = methodName.getClass();
     Method m = c.getMethod("getMetadata", argClasses);
     Object[] args = new Object[1];
     args[0] = path;
     Object obj = m.invoke(null, args);
     metadata = obj != null ? obj.toString() : null;
   } catch (Exception e) {
     return null;
   }
   if (metadata != null && !metadata.startsWith("Error:")) return metadata;
   else return null;
 }
Пример #2
0
  /**
   * Set the object to be edited.
   *
   * @param value The object to be edited.
   */
  public void setObject(Object value) {
    if (!(_type.isInstance(value))) {
      throw new IllegalArgumentException(value.getClass() + " is not of type " + _type);
    }
    _value = value;

    // Disable event generation.
    _squelchChangeEvents = true;

    // Iterate over each property, doing a lookup on the associated editor
    // and setting the editor's value to the value of the property.
    Iterator it = _prop2Editor.keySet().iterator();
    while (it.hasNext()) {
      PropertyDescriptor desc = (PropertyDescriptor) it.next();
      PropertyEditor editor = (PropertyEditor) _prop2Editor.get(desc);
      Method reader = desc.getReadMethod();
      if (reader != null) {
        try {
          Object val = reader.invoke(_value, null);
          editor.setValue(val);
        } catch (IllegalAccessException ex) {
          ex.printStackTrace();
        } catch (InvocationTargetException ex) {
          ex.getTargetException().printStackTrace();
        }
      }
    }

    // Enable event generation.
    _squelchChangeEvents = false;
  }
 @Override
 public int compare(Method o1, Method o2) {
   String n1 = o1.getName().toLowerCase(), n2 = o2.getName().toLowerCase();
   if (n1.contains("dispose") || n1.contains("close")) return 1;
   if (n2.contains("dispose") || n2.contains("close")) return -1;
   return n1.compareTo(n2);
 }
Пример #4
0
    @Override
    public Component getListCellRendererComponent(
        JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {

      // ### We should indicate the current thread independently of the
      // ### selection, e.g., with an icon, because the user may change
      // ### the selection graphically without affecting the current
      // ### thread.

      super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
      if (value == null) {
        this.setText("<unavailable>");
      } else {
        StackFrame frame = (StackFrame) value;
        Location loc = frame.location();
        Method meth = loc.method();
        String methName = meth.declaringType().name() + '.' + meth.name();
        String position = "";
        if (meth.isNative()) {
          position = " (native method)";
        } else if (loc.lineNumber() != -1) {
          position = ":" + loc.lineNumber();
        } else {
          long pc = loc.codeIndex();
          if (pc != -1) {
            position = ", pc = " + pc;
          }
        }
        // Indices are presented to the user starting from 1, not 0.
        this.setText("[" + (index + 1) + "] " + methName + position);
      }
      return this;
    }
Пример #5
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());
    }
  }
Пример #6
0
 public void toggleLionFS() {
   try {
     Class appClass = Class.forName("com.apple.eawt.Application");
     Method getApplication = appClass.getMethod("getApplication", (Class[]) null);
     Object app = getApplication.invoke(appClass);
     Method requestToggleFullScreen = appClass.getMethod("requestToggleFullScreen", Window.class);
     requestToggleFullScreen.invoke(app, this);
   } catch (Exception e) {
     vlog.debug("Could not toggle OS X 10.7+ full-screen mode:");
     vlog.debug("  " + e.toString());
   }
 }
Пример #7
0
 static synchronized void initializeSwing() {
   if (swingInitialized) return;
   swingInitialized = true;
   try {
     /* Initialize the default focus traversal policy */
     Class[] emptyClass = new Class[0];
     Object[] emptyObject = new Object[0];
     Class clazz = Class.forName("javax.swing.UIManager");
     Method method = clazz.getMethod("getDefaults", emptyClass);
     if (method != null) method.invoke(clazz, emptyObject);
   } catch (Throwable e) {
   }
 }
Пример #8
0
  void buildConfigPanel() {
    try {
      Config config = playerObjects.getConfig();
      for (Field field : config.getClass().getDeclaredFields()) {
        Annotation excludeAnnotation = field.getAnnotation(ReflectionHelper.Exclude.class);
        if (excludeAnnotation == null) { // so, this field is not excluded
          Class<?> fieldType = field.getType();
          Method getMethod = getGetMethod(config.getClass(), field.getType(), field.getName());
          if (getMethod != null) {
            Object value = getMethod.invoke(config);
            if (fieldType == String.class) {
              addTextBox(field.getName(), (String) value);
            }
            if (fieldType == boolean.class || fieldType == Boolean.class) {
              addBooleanComponent(field.getName(), (Boolean) value);
            }
            if (fieldType == float.class || fieldType == Float.class) {
              addTextBox(field.getName(), "" + value);
            }
            if (fieldType == int.class || fieldType == Integer.class) {
              addTextBox(field.getName(), "" + value);
            }
          } else {
            playerObjects
                .getLogFile()
                .WriteLine("No get accessor method for config field " + field.getName());
          }
        }
      }
    } catch (Exception e) {
      playerObjects.getLogFile().WriteLine(Formatting.exceptionToStackTrace(e));
    }

    configGridLayout.setRows(configGridLayout.getRows() + 2);

    configRevertButton = new JButton("Revert");
    configReloadButton = new JButton("Reload");
    configApplyButton = new JButton("Apply");
    configSaveButton = new JButton("Save");

    configRevertButton.addActionListener(new ConfigRevert());
    configReloadButton.addActionListener(new ConfigReload());
    configApplyButton.addActionListener(new ConfigApply());
    configSaveButton.addActionListener(new ConfigSave());

    configPanel.add(configRevertButton);
    configPanel.add(configReloadButton);
    configPanel.add(configApplyButton);
    configPanel.add(configSaveButton);
  }
  /**
   * Calls all public methods declared in the class corresponding to the given object. Does not
   * include methods from superclasses.
   *
   * @param object object to call the public methods on
   * @param comparator method comparator, allows running the methods in a specific order
   * @return list of methods invoked, including the parameters used for calling them
   */
  private static List<MethodInvocation> callPublicMethodsInOrder(
      Object object, Comparator<Method> comparator) {
    try {
      List<MethodInvocation> invocations = new ArrayList<>();
      Method[] methods = object.getClass().getDeclaredMethods();
      if (comparator != null) Arrays.sort(methods, comparator);

      for (Method method : methods) {
        if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers()))
          continue;

        Object[] params = new Object[method.getParameterTypes().length];
        for (int i = 0; i < method.getParameterTypes().length; i++) {
          params[i] = instantiateType(method.getParameterTypes()[i]);
        }
        method.invoke(object, params);
        invocations.add(new MethodInvocation(method.getName(), params));
      }
      return invocations;
    } catch (Exception ex) {
      ex.printStackTrace();
      assertTrue(
          "Error calling public methods on object "
              + object
              + " ("
              + object.getClass().getSimpleName()
              + ")",
          false);
      return new ArrayList<>();
    }
  }
Пример #10
0
 /**
  * Try to execute given method on given object. Handles invocation target exceptions. XXX nearly
  * duplicates tryMethod in JGEngine.
  *
  * @return null means method does not exist or returned null/void
  */
 static Object tryMethod(Object o, String name, Object[] args) {
   try {
     Method met = JREEngine.getMethod(o.getClass(), name, args);
     if (met == null) return null;
     return met.invoke(o, args);
   } catch (InvocationTargetException ex) {
     Throwable ex_t = ex.getTargetException();
     ex_t.printStackTrace();
     return null;
   } catch (IllegalAccessException ex) {
     System.err.println("Unexpected exception:");
     ex.printStackTrace();
     return null;
   }
 }
Пример #11
0
 public Object invoke(Object proxy, Method method, Object[] args) {
   if (method.getName().equals("windowEnteringFullScreen")) {
     cc.opts.fullScreen = true;
     cc.menu.fullScreen.setSelected(cc.opts.fullScreen);
     updateMacMenuFS();
     showToolbar(cc.showToolbar);
   } else if (method.getName().equals("windowExitingFullScreen")) {
     cc.opts.fullScreen = false;
     cc.menu.fullScreen.setSelected(cc.opts.fullScreen);
     updateMacMenuFS();
     showToolbar(cc.showToolbar);
   } else if (method.getName().equals("windowEnteredFullScreen")) {
     cc.sizeWindow();
   }
   return null;
 }
 public static void setAutoRequestFocus(JFrame window, boolean autoRequestFocus) {
   try {
     Method setAutoRequestFocusMethod =
         window.getClass().getMethod("setAutoRequestFocus", boolean.class);
     setAutoRequestFocusMethod.invoke(window, autoRequestFocus);
   } catch (NoSuchMethodException e) {
     throw new RuntimeException(e);
   } catch (SecurityException e) {
     throw new RuntimeException(e);
   } catch (IllegalAccessException e) {
     throw new RuntimeException(e);
   } catch (IllegalArgumentException e) {
     throw new RuntimeException(e);
   } catch (InvocationTargetException e) {
     throw new RuntimeException(e);
   }
 }
Пример #13
0
    public Object createValue(UIDefaults table) {
      try {
        Class c = Class.forName(className, true, Thread.currentThread().getContextClassLoader());

        if (methodName == null) {
          return c.newInstance();
        }
        Method m = c.getMethod(methodName, (Class[]) null);

        return m.invoke(c, (Object[]) null);
      } catch (ClassNotFoundException cnfe) {
      } catch (IllegalAccessException iae) {
      } catch (InvocationTargetException ite) {
      } catch (NoSuchMethodException nsme) {
      } catch (InstantiationException ie) {
      }
      return null;
    }
Пример #14
0
    public void propertyChange(PropertyChangeEvent e) {
      if (_squelchChangeEvents) return;

      PropertyEditor editor = (PropertyEditor) e.getSource();
      PropertyDescriptor prop = (PropertyDescriptor) _editor2Prop.get(editor);
      Method writer = prop.getWriteMethod();
      if (writer != null) {
        try {
          Object[] params = {editor.getValue()};
          writer.invoke(_value, params);
          setObject(_value);
          firePropertyChange(_value, prop.getName(), null, editor.getValue());
        } catch (IllegalAccessException ex) {
          ex.printStackTrace();
        } catch (InvocationTargetException ex) {
          ex.getTargetException().printStackTrace();
        }
      }
    }
Пример #15
0
 void revertConfig() {
   try {
     debug("reverting config panel");
     Config config = playerObjects.getConfig();
     for (Field field : config.getClass().getDeclaredFields()) {
       Annotation excludeAnnotation = field.getAnnotation(ReflectionHelper.Exclude.class);
       if (excludeAnnotation == null) { // so, this field is not excluded
         debug("field " + field.getName());
         Class<?> fieldType = field.getType();
         Method getMethod = getGetMethod(config.getClass(), field.getType(), field.getName());
         if (getMethod != null) {
           debug(" ... found accessor method");
           Object value = getMethod.invoke(config);
           String fieldname = field.getName();
           Component component = componentByName.get(fieldname);
           if (component != null) {
             debug(" ... found component");
             if (fieldType == String.class) {
               ((JTextField) component).setText((String) value);
             }
             if (fieldType == boolean.class || fieldType == Boolean.class) {
               ((JCheckBox) component).setSelected((Boolean) value);
             }
             if (fieldType == float.class || fieldType == Float.class) {
               ((JTextField) component).setText("" + value);
             }
             if (fieldType == int.class || fieldType == Integer.class) {
               ((JTextField) component).setText("" + value);
             }
           }
         } else {
           playerObjects
               .getLogFile()
               .WriteLine("No get accessor method for config field " + field.getName());
         }
       }
     }
   } catch (Exception e) {
     playerObjects.getLogFile().WriteLine(Formatting.exceptionToStackTrace(e));
   }
 }
    /**
     * Check that all methods declared in the given interface were called. Does *not* include
     * methods from super interfaces.
     *
     * @return this for fluent api
     */
    public MethodCallTester<MonitoredClass> assertAllInterfaceMethodsCalled() {
      List<MethodInvocation> currentInvocation =
          new ArrayList<>(invocations); // Debugger calling toString can mess with this
      for (Method method : mockClass.getDeclaredMethods()) {
        if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers()))
          continue;

        boolean called = false;
        for (MethodInvocation invocation : currentInvocation) {
          if (invocation.method.equals(method.getName())) {
            called = true;
            break;
          }
        }

        assertTrue(
            "Method " + mockClass.getSimpleName() + "." + method.getName() + " was not called",
            called);
      }
      return this;
    }
Пример #17
0
 public Object visit(Method node) {
   return layoutBinary(
       "Method " + node.getName() + ":" + node.getReturnType(),
       node.getFormalList(),
       node.getStmtList());
 }
Пример #18
0
 void applyConfig() {
   debug("applying config from panel");
   Config config = playerObjects.getConfig();
   for (Field field : config.getClass().getDeclaredFields()) {
     Annotation excludeAnnotation = field.getAnnotation(ReflectionHelper.Exclude.class);
     if (excludeAnnotation == null) { // so, this field is not excluded
       debug("field " + field.getName());
       Class<?> fieldType = field.getType();
       Method setMethod = getSetMethod(config.getClass(), field.getType(), field.getName());
       if (setMethod != null) {
         debug(" ... found accessor method");
         String fieldname = field.getName();
         Component component = componentByName.get(fieldname);
         if (component != null) {
           debug(" ... found component");
           Object value = null;
           if (fieldType == String.class) {
             value = ((JTextField) component).getText();
           }
           if (fieldType == boolean.class || fieldType == Boolean.class) {
             value = ((JCheckBox) component).isSelected();
           }
           if (fieldType == float.class || fieldType == Float.class) {
             String stringvalue = (String) ((JTextField) component).getText();
             try {
               value = Float.parseFloat(stringvalue);
             } catch (Exception e) {
             }
           }
           if (fieldType == int.class || fieldType == Integer.class) {
             String stringvalue = (String) ((JTextField) component).getText();
             try {
               value = Integer.parseInt(stringvalue);
             } catch (Exception e) {
             }
           }
           if (value != null) {
             try {
               setMethod.invoke(config, value);
             } catch (Exception e) {
               playerObjects.getLogFile().WriteLine(Formatting.exceptionToStackTrace(e));
             }
           }
         }
         if (fieldType == boolean.class || fieldType == Boolean.class) {
           // addBooleanComponent( field.getName(), (Boolean)value );
         }
       } else {
         playerObjects
             .getLogFile()
             .WriteLine("No get accessor method for config field " + field.getName());
       }
     }
   }
   revertConfig(); // in case some parses and stuff didn't work, so
   // user can see what is actually being read.
   playerObjects
       .getMainUI()
       .showInfo(
           "Config updated.  Note that most changes require an AI restart.  You can click on 'reloadAI' in 'Actions' tab to do so.");
   playerObjects.getConfig().configUpdated();
 }
Пример #19
0
 public void read() {
   System.out.println("Reading file " + filename);
   Vector ls = readlinesfromfile(filename);
   int i = 0;
   while (i < ls.size()
       && !((String) ls.get(i)).startsWith("class")
       && !((String) ls.get(i)).startsWith("public class")) {
     precode += (String) ls.get(i) + "\n";
     i++;
   }
   while (i < ls.size()) {
     JString l = new JString((String) ls.get(i));
     // System.out.println("Looking for a class in "+l);
     boolean pubclass = false;
     if (l.starts("public ")) {
       pubclass = true;
       l = l.after(" ");
     }
     if (l.starts("class ")) {
       // Parse class
       // Parse first line
       l = l.after("class ");
       Class c = new Class(pubclass, l.before(" ").toString());
       l = l.after(" ");
       l = l.removeall(",");
       if (l.starts("extends ")) {
         l = l.after("extends ");
         while (!l.starts("{") && !l.starts("implements")) {
           c.extended.add(l.before(" "));
           l = l.after(" ");
         }
       }
       if (l.starts("implements ")) {
         l = l.after("implements ");
         while (!l.starts("{")) {
           c.implemented.add(l.before(" "));
           l = l.after(" ");
         }
       }
       l = l.expect("{");
       i++;
       l = new JString((String) ls.get(i));
       while (!l.r.equals("}")) {
         // System.out.println("Parsing class "+c.name+" at "+l);
         if (l.r.length() == 0) i++;
         else {
           // Parse a constructor, field or method
           String type = "";
           boolean priv = true;
           boolean stat = false;
           boolean fin = false;
           boolean con = false;
           String a = l.getalphanum().toString();
           // System.out.println("Comparing >"+a+"< to class name >"+c.name+"<");
           // System.out.println("Line now "+l);
           if (a.equals(c.name)) { // Constructor
             con = true;
             // System.out.println("hello\n");
           } else {
             type = l.before(" ").toString();
             l = l.after(" ");
             if (type.equals("public")) {
               priv = false;
               type = l.before(" ").toString();
               l = l.after(" ");
             }
             if (type.equals("private")) {
               priv = true;
               type = l.before(" ").toString();
               l = l.after(" ");
             }
             if (type.equals("static")) {
               stat = true;
               type = l.before(" ").toString();
               l = l.after(" ");
             }
             // System.out.println("Checking "+type+" for \"final\"");
             if (type.equals("final")) { // Should this be before static?
               fin = true;
               type = l.before(" ").toString();
               l = l.after(" ");
             }
           }
           String name = l.getalphanum().toString();
           // System.out.println("Got name "+name+" in line "+l);
           l = l.after(name);
           l.r = l.r.trim();
           // Is it a variable (field) ?
           // Are there more than one?
           // System.out.println("Looking for = or ; in "+l);
           while (l.starts(",")) {
             // ***
             Field f = new Field(type, name, "");
             c.fields.add(f);
             l = l.after(",");
             name = l.getalphanum().toString();
             l = l.after(name);
             l.r = l.r.trim();
           }
           // Is this the last one?
           if (l.starts("=") || l.starts(";")) {
             // System.out.println("Starts = or ;");
             String init = "";
             if (l.starts("=")) {
               init = l.after("=").before(";").toString();
             }
             Field f = new Field(priv, stat, fin, type, name, init);
             c.fields.add(f);
             i++;
             // System.out.println("Added field "+f);
           } else { // It must be a method
             l = l.expect("(");
             Method m = new Method(con, !priv, stat, type, name);
             while (!l.starts(")")) {
               String atype = l.before(" ").toString();
               l = l.from(" ");
               String aname; // Is it last?
               if (l.r.indexOf(",") != -1) {
                 aname = l.before(",").toString();
                 l = l.after(",");
               } else {
                 aname = l.before(")").toString();
                 l = l.after(aname);
               }
               m.args.add(new Argument(atype, aname));
             }
             l = l.expect(")");
             l.r = l.r.trim();
             l.expect("{");
             // Read code
             i++;
             int curlycount = 1;
             while (curlycount > 0) {
               l = new JString((String) ls.get(i));
               for (int j = 0; j < l.r.length(); j++) {
                 if (l.r.charAt(j) == '{') curlycount++;
                 if (l.r.charAt(j) == '}') curlycount--;
               }
               if (curlycount > 0) {
                 String ind = "  ";
                 for (int ib = 1; ib <= curlycount; ib++) ind += "  ";
                 m.code += ind + l + "\n";
                 // System.out.println("Adding code "+l);
               }
               i++;
               // System.out.println("Ended on line "+(String)ls.get(i));
             }
             c.methods.add(m);
           }
         }
         // System.out.println("Got so far with class "+c);
         //        i++;
         l = new JString((String) ls.get(i));
         // System.out.println("Checking line "+l);
       }
       classes.add(c);
     } else {
       //        precode+=(String)ls.get(i)+"\n";
       i++;
     }
   }
   System.out.println("Found " + classes.size() + " classes.");
 }
Пример #20
0
    /**
     * Create a new ProjectionClass from the class
     *
     * @param pc projection class
     * @throws ClassNotFoundException couldn't find the class
     * @throws IntrospectionException problem with introspection
     */
    ProjectionClass(Class pc) throws ClassNotFoundException, IntrospectionException {
      projClass = pc;

      // eliminate common properties with "stop class" for getBeanInfo()
      Class stopClass;
      try {
        stopClass = Misc.findClass("ucar.unidata.geoloc.ProjectionImpl");
      } catch (Exception ee) {
        System.err.println("constructParamInput failed ");
        stopClass = null;
      }

      // analyze current projection class as a bean; may throw IntrospectionException
      BeanInfo info = java.beans.Introspector.getBeanInfo(projClass, stopClass);

      // find read/write methods
      PropertyDescriptor[] props = info.getPropertyDescriptors();
      if (debugBeans) {
        System.out.print("Bean Properties for class " + projClass);
        if ((props == null) || (props.length == 0)) {
          System.out.println("none");
          return;
        }
        System.out.println("");
      }
      for (int i = 0; i < props.length; i++) {
        PropertyDescriptor pd = props[i];
        Method reader = pd.getReadMethod();
        Method writer = pd.getWriteMethod();
        // only interesetd in read/write properties
        if ((reader == null) || (writer == null)) {
          continue;
        }
        // A hack to exclude some attributes
        if (pd.getName().equals("name") || pd.getName().equals("defaultMapArea")) {
          continue;
        }
        ProjectionParam p = new ProjectionParam(pd.getName(), reader, writer, pd.getPropertyType());
        paramList.add(p);

        if (debugBeans) {
          System.out.println("  -->" + p);
        }
      }

      // get an instance of this class so we can call toClassName()
      Projection project;
      if (null == (project = makeDefaultProjection())) {
        name = "none";
        return;
      }

      // invoke the toClassName method
      try {
        Method m = projClass.getMethod("getProjectionTypeLabel", VOIDCLASSARG);
        name = (String) m.invoke(project, VOIDOBJECTARG);
      } catch (NoSuchMethodException ee) {
        System.err.println(
            "ProjectionManager: class "
                + projClass
                + " does not have method getProjectionTypeLabel()");
        throw new ClassNotFoundException();
      } catch (SecurityException ee) {
        System.err.println(
            "ProjectionManager: class "
                + projClass
                + " got SecurityException on getProjectionTypeLabel()"
                + ee);
        throw new ClassNotFoundException();
      } catch (Exception ee) {
        System.err.println(
            "ProjectionManager: class "
                + projClass
                + " Exception when invoking getProjectionTypeLabel()"
                + ee);
        throw new ClassNotFoundException();
      }
    }