private XmlUIElement getXmlUIElementFor(String typeArg) { if (typeToClassMappingProp == null) { setUpMappingsHM(); } String clsName = (String) typeToClassMappingProp.get(typeArg); if ((clsName != null) && !(clsName.equals("*NOTFOUND*")) && !(clsName.equals("*EXCEPTION*"))) { try { Class cls = Class.forName(clsName); return (XmlUIElement) cls.newInstance(); } catch (Throwable th) { typeToClassMappingProp.put(typeArg, "*EXCEPTION*"); showErrorMessage( MessageFormat.format( ProvClientUtils.getString( "{0} occurred when trying to get the XmlUIElement for type : {1}"), new Object[] {th.getClass().getName(), typeArg})); th.printStackTrace(); return null; } } else if (clsName == null) { typeToClassMappingProp.put(typeArg, "*NOTFOUND*"); showErrorMessage( MessageFormat.format( ProvClientUtils.getString( "The type {0} does not have the corresponding XMLUIElement specified in the TypeToUIElementMapping.txt file"), new Object[] {typeArg})); } return null; }
public Object deserializeInto(@NotNull Object result, @NotNull Element element) { Set<Binding> bindings = myPropertyBindings.keySet(); MultiMap<Binding, Object> data = MultiMap.createSmartList(); nextNode: for (Object child : ContainerUtil.concat(element.getContent(), element.getAttributes())) { if (XmlSerializerImpl.isIgnoredNode(child)) { continue; } for (Binding binding : bindings) { if (binding.isBoundTo(child)) { data.putValue(binding, child); continue nextNode; } } final String message = "Format error: no binding for " + child + " inside " + this; LOG.debug(message); Logger.getInstance(myBeanClass.getName()).debug(message); Logger.getInstance("#" + myBeanClass.getName()).debug(message); } for (Binding binding : data.keySet()) { binding.deserialize(result, ArrayUtil.toObjectArray(data.get(binding))); } return result; }
public void loadMacros() { File f = new File(System.getProperty("user.dir")); String[] files = f.list(); for (int i = 0; i < files.length; i++) { try { if (files[i].startsWith("macro_") && files[i].endsWith(".class") && files[i].indexOf('$') == -1) { System.out.println(files[i]); Class clazz = Class.forName(files[i].substring(0, files[i].length() - ".class".length())); Macro macro = (Macro) clazz .getConstructor(new Class[] {mudclient_Debug.class}) .newInstance(new Object[] {inner}); String[] commands = macro.getCommands(); for (int j = 0; j < commands.length; j++) { System.out.println("command registered:" + commands[j]); mudclient_Debug.macros.put(commands[j], macro); } } } catch (Exception e) { e.printStackTrace(); } } }
/*package*/ static boolean isModern(Class<? extends LoadStatistics> clazz) { // cannot use Util.isOverridden as these are protected methods. boolean hasGetNodes = false; boolean hasMatches = false; while (clazz != LoadStatistics.class && clazz != null && !(hasGetNodes && hasMatches)) { if (!hasGetNodes) { try { final Method getNodes = clazz.getDeclaredMethod("getNodes"); hasGetNodes = !Modifier.isAbstract(getNodes.getModifiers()); } catch (NoSuchMethodException e) { // ignore } } if (!hasMatches) { try { final Method getNodes = clazz.getDeclaredMethod("matches", Queue.Item.class, SubTask.class); hasMatches = !Modifier.isAbstract(getNodes.getModifiers()); } catch (NoSuchMethodException e) { // ignore } } if (!(hasGetNodes && hasMatches) && LoadStatistics.class.isAssignableFrom(clazz.getSuperclass())) { clazz = (Class<? extends LoadStatistics>) clazz.getSuperclass(); } } return hasGetNodes && hasMatches; }
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; }
public static void clearFields(final Object test) throws IllegalAccessException { Class aClass = test.getClass(); while (aClass != null) { clearDeclaredFields(test, aClass); aClass = aClass.getSuperclass(); } }
private static Method getBaselineMethod(JComponent component) { if (COMPONENT_BASELINE_METHOD != null) { return COMPONENT_BASELINE_METHOD; } Class klass = component.getClass(); while (klass != null) { if (BASELINE_MAP.containsKey(klass)) { Method method = (Method) BASELINE_MAP.get(klass); return method; } klass = klass.getSuperclass(); } klass = component.getClass(); Method[] methods = klass.getMethods(); for (int i = methods.length - 1; i >= 0; i--) { Method method = methods[i]; if ("getBaseline".equals(method.getName())) { Class[] params = method.getParameterTypes(); if (params.length == 2 && params[0] == int.class && params[1] == int.class) { BASELINE_MAP.put(klass, method); return method; } } } BASELINE_MAP.put(klass, null); return null; }
/** * @return an instanciation of the given content-type class name, or null if class wasn't found */ public static ContentType getContentTypeFromClassName(String contentTypeClassName) { if (contentTypeClassName == null) contentTypeClassName = getAvailableContentTypes()[DEFAULT_CONTENT_TYPE_INDEX]; ContentType ct = null; try { Class clazz = Class.forName(contentTypeClassName); ct = (ContentType) clazz.newInstance(); } catch (ClassNotFoundException cnfex) { if (jpicedt.Log.DEBUG) cnfex.printStackTrace(); JPicEdt.getMDIManager() .showMessageDialog( "The pluggable content-type you asked for (class " + cnfex.getLocalizedMessage() + ") isn't currently installed, using default instead...", Localizer.currentLocalizer().get("msg.LoadingContentTypeClass"), JOptionPane.ERROR_MESSAGE); } catch (Exception ex) { if (jpicedt.Log.DEBUG) ex.printStackTrace(); JPicEdt.getMDIManager() .showMessageDialog( ex.getLocalizedMessage(), Localizer.currentLocalizer().get("msg.LoadingContentTypeClass"), JOptionPane.ERROR_MESSAGE); } return ct; }
private boolean isSynthIcon(Icon icon) { if (_synthIconMap == null) { _synthIconMap = new HashMap<String, Boolean>(); } Class<?> aClass = icon.getClass(); java.util.List<String> classNamesToPut = new ArrayList<String>(); boolean isSynthIcon = false; while (aClass != null) { String name = aClass.getCanonicalName(); if (name != null) { Boolean value = _synthIconMap.get(name); if (value != null) { return value; } classNamesToPut.add(name); if (isSynthIconClassName(name)) { isSynthIcon = true; break; } } aClass = aClass.getSuperclass(); } for (String name : classNamesToPut) { _synthIconMap.put(name, isSynthIcon); } return isSynthIcon; }
/** * Creates the brain and launches if it is an agent. The brain class is given as a String. The * name argument is used to instantiate the name of the corresponding agent. If the gui flag is * true, a bean is created and associated to this agent. */ public void makeBrain(String className, String name, boolean gui, String behaviorFileName) { try { Class c; // c = Class.forName(className); c = madkit.kernel.Utils.loadClass(className); myBrain = (Brain) c.newInstance(); myBrain.setBody(this); if (myBrain instanceof AbstractAgent) { String n = name; if (n == null) { n = getLabel(); } if (n == null) { n = getID(); } if (behaviorFileName != null) setBehaviorFileName(behaviorFileName); getStructure().getAgent().doLaunchAgent((AbstractAgent) myBrain, n, gui); } } catch (ClassNotFoundException ev) { System.err.println("Class not found :" + className + " " + ev); ev.printStackTrace(); } catch (InstantiationException e) { System.err.println("Can't instanciate ! " + className + " " + e); e.printStackTrace(); } catch (IllegalAccessException e) { System.err.println("illegal access! " + className + " " + e); e.printStackTrace(); } }
/** * Get the appropriate editor for the given property. * * @param prop Property to get editor for. * @return Editor to use, or null if none found. */ private PropertyEditor getEditorForProperty(PropertyDescriptor prop) { PropertyEditor retval = null; Class type = prop.getPropertyEditorClass(); if (type != null) { try { retval = (PropertyEditor) type.newInstance(); } catch (Exception ex) { ex.printStackTrace(); } } // Handle case where there is no special editor // associated with the property. In that case we ask the // PropertyEditor manager for the editor registered for the // given property type. if (retval == null) { Class t = prop.getPropertyType(); if (t != null) { retval = PropertyEditorManager.findEditor(t); } } // In the worse case we resort to the generic editor for Object types. if (retval == null) { retval = PropertyEditorManager.findEditor(Object.class); } return retval; }
/** 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; }
private void calculateWrapSize(Rectangle bounds) { if (myWrapSize.width == -1 || myWrapSize.height == -1) { try { Object viewObject = myComponent.getViewInfo().getViewObject(); Class<?> viewClass = viewObject.getClass(); viewClass.getMethod("forceLayout").invoke(viewObject); viewClass .getMethod("measure", int.class, int.class) .invoke(viewObject, WRAP_CONTENT, WRAP_CONTENT); if (myWrapSize.width == -1) { myWrapSize.width = (Integer) viewClass.getMethod("getMeasuredWidth").invoke(viewObject); } if (myWrapSize.height == -1) { myWrapSize.height = (Integer) viewClass.getMethod("getMeasuredHeight").invoke(viewObject); } } catch (Throwable e) { if (myWrapSize.width == -1) { myWrapSize.width = bounds.width; } if (myWrapSize.height == -1) { myWrapSize.height = bounds.height; } } } }
public void testChainedConstructor() throws Exception { Class cls = loadAndPatchClass("TestChainedConstructor.form", "ChainedConstructorTest"); Field scrollPaneField = cls.getField("myScrollPane"); Object instance = cls.newInstance(); JScrollPane scrollPane = (JScrollPane) scrollPaneField.get(instance); assertNotNull(scrollPane.getViewport().getView()); }
public static FontMetrics getFontMetrics(JComponent c, Graphics g, Font f) { FontMetrics fm = null; if (getJavaVersion() >= 1.6) { try { Class swingUtilities2Class = Class.forName("sun.swing.SwingUtilities2"); Class classParams[] = {JComponent.class, Graphics.class, Font.class}; Method m = swingUtilities2Class.getMethod("getFontMetrics", classParams); Object methodParams[] = {c, g, f}; fm = (FontMetrics) m.invoke(null, methodParams); } catch (Exception ex) { // Nothing to do } } if (fm == null) { if (g == null) { if (c != null) { g = c.getGraphics(); } } if (g != null) { if (f != null) { fm = g.getFontMetrics(f); } else { fm = g.getFontMetrics(); } } else if (c != null) { if (f != null) { fm = c.getFontMetrics(f); } else { fm = c.getFontMetrics(c.getFont()); } } } return fm; }
public BeanBinding(Class<?> beanClass) { assert !beanClass.isArray() : "Bean is an array: " + beanClass; assert !beanClass.isPrimitive() : "Bean is primitive type: " + beanClass; myBeanClass = beanClass; myTagName = getTagName(beanClass); assert !StringUtil.isEmptyOrSpaces(myTagName) : "Bean name is empty: " + beanClass; }
public static void drawStringUnderlineCharAt( JComponent c, Graphics g, String text, int underlinedIndex, int x, int y) { Graphics2D g2D = (Graphics2D) g; Object savedRenderingHint = null; if (AbstractLookAndFeel.getTheme().isTextAntiAliasingOn()) { savedRenderingHint = g2D.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); g2D.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, AbstractLookAndFeel.getTheme().getTextAntiAliasingHint()); } if (getJavaVersion() >= 1.6) { try { Class swingUtilities2Class = Class.forName("sun.swing.SwingUtilities2"); Class classParams[] = { JComponent.class, Graphics.class, String.class, Integer.TYPE, Integer.TYPE, Integer.TYPE }; Method m = swingUtilities2Class.getMethod("drawStringUnderlineCharAt", classParams); Object methodParams[] = { c, g, text, new Integer(underlinedIndex), new Integer(x), new Integer(y) }; m.invoke(null, methodParams); } catch (Exception ex) { BasicGraphicsUtils.drawString(g, text, underlinedIndex, x, y); } } else if (getJavaVersion() >= 1.4) { BasicGraphicsUtils.drawStringUnderlineCharAt(g, text, underlinedIndex, x, y); } else { BasicGraphicsUtils.drawString(g, text, underlinedIndex, x, y); } if (AbstractLookAndFeel.getTheme().isTextAntiAliasingOn()) { g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, savedRenderingHint); } }
public void testIdeadev14081() throws Exception { // NOTE: That doesn't really reproduce the bug as it's dependent on a particular instrumentation // sequence used during form preview // (the nested form is instrumented with a new AsmCodeGenerator instance directly in the middle // of instrumentation of the current form) final String testDataPath = PluginPathManager.getPluginHomePath("ui-designer") + File.separatorChar + "testData" + File.separatorChar + File.separatorChar + "formEmbedding" + File.separatorChar + "Ideadev14081" + File.separatorChar; AsmCodeGenerator embeddedClassGenerator = initCodeGenerator("Embedded.form", "Embedded", testDataPath); byte[] embeddedPatchedData = getVerifiedPatchedData(embeddedClassGenerator); myClassFinder.addClassDefinition("Embedded", embeddedPatchedData); myNestedFormLoader.registerNestedForm("Embedded.form", testDataPath + "Embedded.form"); AsmCodeGenerator mainClassGenerator = initCodeGenerator("Main.form", "Main", testDataPath); byte[] mainPatchedData = getVerifiedPatchedData(mainClassGenerator); /* FileOutputStream fos = new FileOutputStream("C:\\yole\\FormPreview27447\\MainPatched.class"); fos.write(mainPatchedData); fos.close(); */ myClassFinder.addClassDefinition("Main", mainPatchedData); final Class mainClass = myClassFinder.getLoader().loadClass("Main"); Object instance = mainClass.newInstance(); assert instance != null : mainClass; }
/** * Load a class specified by a file- or entry-name * * @param name name of a file or entry * @return class file that was denoted by the name, null if no class or does not contain a main * method */ private Class load(String name) { if (name.endsWith(".class") && name.indexOf("Test") >= 0 && name.indexOf('$') < 0) { String classname = name.substring(0, name.length() - ".class".length()); if (classname.startsWith("/")) { classname = classname.substring(1); } classname = classname.replace('/', '.'); try { final Class<?> cls = Class.forName(classname); cls.getMethod("main", new Class[] {String[].class}); if (!getClass().equals(cls)) { return cls; } } catch (NoClassDefFoundError e) { // class has unresolved dependencies return null; } catch (ClassNotFoundException e) { // class not in classpath return null; } catch (NoSuchMethodException e) { // class does not have a main method return null; } catch (UnsupportedClassVersionError e) { // unsupported version return null; } } return null; }
/** * Create the given ViewManager * * @param viewDescriptor Identifies the VM * @param properties Property string to pass * @return The new one */ public ViewManager createViewManager(ViewDescriptor viewDescriptor, String properties) { synchronized (viewManagers) { try { ViewManager viewManager = null; if (viewDescriptor == null) { viewDescriptor = new ViewDescriptor(); } if (viewDescriptor.getClassNames().size() > 0) { Class viewManagerClass = Misc.findClass((String) viewDescriptor.getClassNames().get(0)); Constructor ctor = Misc.findConstructor( viewManagerClass, new Class[] {IntegratedDataViewer.class, ViewDescriptor.class, String.class}); if (ctor == null) { throw new IllegalArgumentException( "cannot create ViewManager:" + viewManagerClass.getName()); } viewManager = (ViewManager) ctor.newInstance(new Object[] {getIdv(), viewDescriptor, properties}); } else { viewManager = new MapViewManager(getIdv(), viewDescriptor, properties); } addViewManager(viewManager); return viewManager; } catch (Throwable e) { logException("In getViewManager", e); return null; } } }
private JComponent getInstrumentedRootComponent(final String formFileName, final String className) throws Exception { Class cls = loadAndPatchClass(formFileName, className); Field rootComponentField = cls.getField("myRootComponent"); rootComponentField.setAccessible(true); Object instance = cls.newInstance(); return (JComponent) rootComponentField.get(instance); }
public static void invoke(String aClass, String aMethod, Class[] params, Object[] args) throws Exception { Class c = Class.forName(aClass); Constructor constructor = c.getConstructor(params); Method m = c.getDeclaredMethod(aMethod, params); Object i = constructor.newInstance(args); Object r = m.invoke(i, args); }
public void testMethodCallInSuper() throws Exception { // todo[yole] make this test work in headless if (!GraphicsEnvironment.isHeadless()) { Class cls = loadAndPatchClass("TestMethodCallInSuper.form", "MethodCallInSuperTest"); JDialog instance = (JDialog) cls.newInstance(); assertEquals(1, instance.getContentPane().getComponentCount()); } }
private static boolean shouldIgnoreAction(@NotNull AnAction action) { for (Class<?> actionType : IGNORED_CONSOLE_ACTION_TYPES) { if (actionType.isInstance(action)) { return true; } } return false; }
public static <T> T assertInstanceOf(Object o, Class<T> aClass) { Assert.assertNotNull("Expected instance of: " + aClass.getName() + " actual: " + null, o); Assert.assertTrue( "Expected instance of: " + aClass.getName() + " actual: " + o.getClass().getName(), aClass.isInstance(o)); @SuppressWarnings("unchecked") T t = (T) o; return t; }
protected static Object newInstance(String name) { try { Class clazz = Class.forName(name); return clazz.newInstance(); } catch (Exception e) { Logger().severe("Cannot extatiate class " + name + ": " + e.getMessage()); return null; } }
/** * Removes the property of the given type. * * @return The property that was just removed. * @since 1.279 */ public <T extends JobProperty> T removeProperty(Class<T> clazz) throws IOException { for (JobProperty<? super JobT> p : properties) { if (clazz.isInstance(p)) { removeProperty(p); return clazz.cast(p); } } return null; }
/** * A utility function that layers on top of the LookAndFeel's isSupportedLookAndFeel() method. * Returns true if the LookAndFeel is supported. Returns false if the LookAndFeel is not supported * and/or if there is any kind of error checking if the LookAndFeel is supported. * * <p>The L&F menu will use this method to detemine whether the various L&F options should be * active or inactive. */ protected boolean isAvailableLookAndFeel(String laf) { try { Class lnfClass = Class.forName(laf); LookAndFeel newLAF = (LookAndFeel) (lnfClass.newInstance()); return newLAF.isSupportedLookAndFeel(); } catch (Exception e) { // If ANYTHING weird happens, return false return false; } }
private static String getTagName(Class<?> aClass) { for (Class<?> c = aClass; c != null; c = c.getSuperclass()) { String name = getTagNameFromAnnotation(c); if (name != null) { return name; } } return aClass.getSimpleName(); }
private Action tryEmptyConstructor(final Class aClass) throws Exception { for (final Constructor constructor : aClass.getConstructors()) { final Class[] types = constructor.getParameterTypes(); if (types == null || types.length == 0) { return (Action) aClass.newInstance(); } } return null; }