private static void reregisterNativeMethodsForRestoredClass(@Nonnull Class<?> realClass) { Method registerNatives = null; try { registerNatives = realClass.getDeclaredMethod("registerNatives"); } catch (NoSuchMethodException ignore) { try { registerNatives = realClass.getDeclaredMethod("initIDs"); } catch (NoSuchMethodException ignored) { } // OK } if (registerNatives != null) { try { registerNatives.setAccessible(true); registerNatives.invoke(null); } catch (IllegalAccessException ignore) { } // won't happen catch (InvocationTargetException ignore) { } // shouldn't happen either } // OK, although another solution will be required for this particular class if it requires // natives to be explicitly registered again (not all do, such as java.lang.Float). }
void callMethod(String command, List<String> args) { Class implementation = this.getClass(); String methodName = command.replace("-", "") + "Command"; try { Method method = implementation.getDeclaredMethod(methodName, List.class); method.invoke(this, args); } catch (NoSuchMethodException ex) { System.out.println( "No such method exception occured while trying" + " to run storm method " + command); } catch (IllegalAccessException ex) { System.out.println( "Illegal access exception occured while trying" + " to run storm method " + command); } catch (IllegalArgumentException ex) { System.out.println( "Illegal argument exception occured while " + "trying" + " to run storm method " + command); } catch (InvocationTargetException ex) { System.out.println( "Invocation target exception occured while " + "trying" + " to run storm method " + command); } }
/** 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; }
static Field test() throws Exception { Class c = Java6Reflection.class; Field f = c.getDeclaredField("field1"); f.setAccessible(true); Method m = c.getDeclaredMethod("testMethod"); m.setAccessible(true); m.invoke(new Java6Reflection()); return f; }
/** * Check if the receiver is enabled for the given selection. * * @param selection * @return <code>true</code> if the given selection matches the conditions specified in <code> * IConfirgurationElement</code>. */ public boolean isEnabledForSelection(ISelection selection) { // Optimize it. if (mode == UNKNOWN) { return false; } // Handle undefined selections. if (selection == null) { selection = StructuredSelection.EMPTY; } // According to the dictionary, a selection is "one that // is selected", or "a collection of selected things". // In reflection of this, we deal with one or a collection. // special case: structured selections if (selection instanceof IStructuredSelection) { return isEnabledFor((IStructuredSelection) selection); } // special case: text selections // Code should read // if (selection instanceof ITextSelection) { // int count = ((ITextSelection) selection).getLength(); // return isEnabledFor(selection, count); // } // use Java reflection to avoid dependence of org.eclipse.jface.text // which is in an optional part of the generic workbench Class tselClass = getTextSelectionClass(); if (tselClass != null && tselClass.isInstance(selection)) { try { Method m = tselClass.getDeclaredMethod("getLength", new Class[0]); // $NON-NLS-1$ Object r = m.invoke(selection, new Object[0]); if (r instanceof Integer) { return isEnabledFor(selection, ((Integer) r).intValue()); } // should not happen - but enable if it does return true; } catch (NoSuchMethodException e) { // should not happen - fall through if it does } catch (IllegalAccessException e) { // should not happen - fall through if it does } catch (InvocationTargetException e) { // should not happen - fall through if it does } } // all other cases return isEnabledFor(selection); }
/** * Invokes a method in the supplied class with the given arguments, and returnes the methods * result in the desired type. <br> * <br> * The only requirement ist, that the type, on which the method is to be called, has the default * constructor. <br> * <br> * This method will create an instance of the provided class <code>targetClass</code>, which is * generally described by the generic parameter <code>T</code> (for <i>Type</i>). The instance is * created using the <b>default constructor</b>. If the default constructor is not declared, an * Exception will be throwen. However, there is no requirement on the visibility of the default * constructor. <br> * Using this instance, the method specified by the string parameter <code>methodName</code> will * be invoked. Again, there is no requirement on the visibility of the method. <br> * The method will be invoked, using the supplied parameter-list <code>params</code>. <br> * <br> * The result will be returned as an object of the generic type <code>R</code> (for * <i>Result</i>), and as this type parameter <code>R</code> is not further specified, the result * my be any type and does not need to be casted. * * @param <R> The result type of the method. Does not need to be declared. * @param <T> The type, on which the method will be invoked. * @param methodName Method name to be invoked. * @param targetClass Class instance of the type, on which the method is to be invoked. * @param params Parameters for the invokation of the method. * @return The result of the method, that is invoked. */ @SuppressWarnings("unchecked") public static <R, T> R invokeMethod(String methodName, Class<T> targetClass, Object... params) throws Exception { T instance = DatabaseFileLookupTest.getInstanceFromType(targetClass); if (instance == null) { throw new InstantiationException("The type '" + targetClass + "' could not be instantiated."); } Class<?>[] paramTypes = new Class<?>[params.length]; for (int i = 0; i < params.length; i++) { paramTypes[i] = params[i].getClass(); } Method method = targetClass.getDeclaredMethod(methodName, paramTypes); method.setAccessible(true); return (R) method.invoke(instance, params); }
public static void executeMethodClass( String pathToJar, String pkg, String classToGet, String methodName, String pathToFile, long logIdSyncMin, long logIdSyncMax) throws IOException, ClassNotFoundException, SecurityException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException { Class<?> c = getClassFromJar(pathToJar, pkg, classToGet); Method method = c.getDeclaredMethod(methodName, String.class, long.class, long.class); method.invoke(null, pathToFile, logIdSyncMin, logIdSyncMax); }
private Method findParamsProvidingMethodInTestclassHierarchy( String methodName, Class<?> testClass) { Method provideMethod = null; Class<?> declaringClass = testClass; while (declaringClass.getSuperclass() != null) { try { provideMethod = declaringClass.getDeclaredMethod(methodName); break; } catch (Exception e) { } declaringClass = declaringClass.getSuperclass(); } if (provideMethod == null) throw new RuntimeException( "Could not find method: " + methodName + " so no params were used."); return provideMethod; }
/** * Find a method in the class with the given name and argument types. This method will iterate * through superclasses and even inspect the Object class. * * @param cls the class where to search the method. * @param methodName the name of the method that is being searched. * @param argumentTypes the types of the arguments of the method. * @return the method or null if not found. * @since 1.4 */ public static Method safeGetMethod(Class cls, String methodName, Class[] argumentTypes) { while (cls != null) { Method method; try { method = cls.getDeclaredMethod(methodName, argumentTypes); } catch (Exception ex) { method = null; } if (method == null) { cls = cls.getSuperclass(); continue; } return method; } return null; }
protected boolean annotatedWith(@NotNull Class annotationClass) { Class<?> aClass = getClass(); String methodName = "test" + getTestName(false); boolean methodChecked = false; while (aClass != null && aClass != Object.class) { if (aClass.getAnnotation(annotationClass) != null) return true; if (!methodChecked) { try { Method method = aClass.getDeclaredMethod(methodName); if (method.getAnnotation(annotationClass) != null) return true; methodChecked = true; } catch (NoSuchMethodException ignored) { } } aClass = aClass.getSuperclass(); } return false; }
private static void fixPopupSize(final Popup popup, final Component contents) { if (!UIUtil.isUnderGTKLookAndFeel() || !(contents instanceof JPopupMenu)) return; for (Class<?> aClass = popup.getClass(); aClass != null && Popup.class.isAssignableFrom(aClass); aClass = aClass.getSuperclass()) { try { final Method getComponent = aClass.getDeclaredMethod("getComponent"); getComponent.setAccessible(true); final Object component = getComponent.invoke(popup); if (component instanceof JWindow) { ((JWindow) component).setSize(new Dimension(0, 0)); } break; } catch (Exception ignored) { } } }
/** * Installs a Grails plugin into the current project if it isn't already installed. It works by * simply unpacking the plugin artifact (a ZIP file) into the appropriate location and adding the * plugin to the application's metadata. * * @param plugins The plugin artifact to install. * @param launcher The launcher instance that contains information about the various project * directories. In particular, this is where the method gets the location of the project's * "plugins" directory from. * @return <code>true</code> if the plugin is installed and the metadata updated, otherwise <code> * false</code>. * @throws IOException * @throws ArchiverException */ private boolean installGrailsPlugins( List<File> plugins, final DecentGrailsLauncher launcher, Field settingsField, Class clazz) throws MojoExecutionException { Object settings = null; try { settings = settingsField.get(launcher); Method m = clazz.getDeclaredMethod("addPluginDirectory", new Class[] {File.class, boolean.class}); for (File targetDir : plugins) m.invoke(settings, targetDir, true); } catch (Exception e) { throw new MojoExecutionException("Unable to install plugins", e); } return false; }
public void run() { if (useMainThread) { // we have to start first to provide the service .. singletonMainThread.waitUntilRunning(); } // start user app .. try { Class mainClass = ReflectionUtil.getClass(mainClassName, true, getClass().getClassLoader()); if (null == mainClass) { throw new RuntimeException( new ClassNotFoundException("MainThread couldn't find main class " + mainClassName)); } try { mainClassMain = mainClass.getDeclaredMethod("main", new Class[] {String[].class}); mainClassMain.setAccessible(true); } catch (Throwable t) { throw new RuntimeException(t); } if (DEBUG) System.err.println( "MainAction.run(): " + Thread.currentThread().getName() + " invoke " + mainClassName); mainClassMain.invoke(null, new Object[] {mainClassArgs}); } catch (InvocationTargetException ite) { ite.getTargetException().printStackTrace(); } catch (Throwable t) { t.printStackTrace(); } if (DEBUG) System.err.println( "MainAction.run(): " + Thread.currentThread().getName() + " user app fin"); if (useMainThread) { singletonMainThread.stop(); if (DEBUG) System.err.println( "MainAction.run(): " + Thread.currentThread().getName() + " MainThread fin - stop"); System.exit(0); } }
public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(br.readLine().trim()); Object o; // Solution starts here if (num < 1 || num > Math.pow(2, 30)) throw new Exception(); Solution ob = new Solution(); Class<?> c = Class.forName("Solution$Private"); Constructor<?> constructor = c.getDeclaredConstructor(Solution.class); constructor.setAccessible(true); o = constructor.newInstance(ob); Method m = c.getDeclaredMethod("powerof2", new Class[] {int.class}); m.setAccessible(true); String ans = (String) m.invoke(o, num); System.out.println(num + " is " + ans); // ends here System.out.println( "An instance of class: " + o.getClass().getSimpleName() + " has been created"); } // end of main
protected static void checkAllTimersAreDisposed() { try { Class<?> aClass = Class.forName("javax.swing.TimerQueue"); Method inst = aClass.getDeclaredMethod("sharedInstance"); inst.setAccessible(true); Object queue = inst.invoke(null); Field field = aClass.getDeclaredField("firstTimer"); field.setAccessible(true); Object firstTimer = field.get(queue); if (firstTimer != null) { try { fail("Not disposed Timer: " + firstTimer.toString() + "; queue:" + queue); } finally { field.set(queue, null); } } } catch (Throwable e) { // Ignore } }
private static final void ensureScalaPath(Map<String, String> options, String[] cp) { // (check if it's in the classpath) try { Class.forName("scala.None", false, ClassLoader.getSystemClassLoader()); } catch (ClassNotFoundException e) { // (case: scala library not in the classpath) if (options.containsKey(SCALA_PATH)) { // (case: scala_path option set) try { String path = options.get(SCALA_PATH); if (!(new File(path).exists())) { System.err.println("The library strongly integrates with the Scala runtime, "); System.err.println("however it could not find the Scala library (scala-library.jar) "); System.err.println( "at the path given by the command line option '" + SCALA_PATH + "': " + path); log.exit(ExitCode.BAD_OPTION); } URL url = new File(path).toURI().toURL(); URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Class<URLClassLoader> sysclass = URLClassLoader.class; Method method = sysclass.getDeclaredMethod("addURL", url.getClass()); boolean savedAccessible = method.isAccessible(); method.setAccessible(true); method.invoke(sysloader, new Object[] {url}); method.setAccessible(savedAccessible); Class.forName("scala.None", false, ClassLoader.getSystemClassLoader()); } catch (Exception ex) { throw log.fail(ex); } // end try catch } else { // (case: we cannot find the scala library at all) System.err.println("The library strongly integrates with the Scala runtime, "); System.err.println( "however it could not find the Scala library (scala-library.jar) in the classpath, "); System.err.println("and the '" + SCALA_PATH + "' command line argument is not set."); log.exit(ExitCode.BAD_OPTION); } } options.remove(SCALA_PATH); }
private static int execInProcess( File kotlinHome, VirtualFile outputDir, File scriptFile, PrintStream out, CompileContext context) { URLClassLoader loader = getOrCreateClassloader(kotlinHome, context); try { String compilerClassName = "org.jetbrains.jet.cli.KotlinCompiler"; Class<?> kompiler = Class.forName(compilerClassName, true, loader); Method exec = kompiler.getDeclaredMethod("exec", PrintStream.class, String[].class); String[] arguments = { "-module", scriptFile.getAbsolutePath(), "-output", path(outputDir), "-tags" }; context.addMessage(INFORMATION, "Using kotlinHome=" + kotlinHome, "", -1, -1); context.addMessage( INFORMATION, "Invoking in-process compiler " + compilerClassName + " with arguments " + Arrays.asList(arguments), "", -1, -1); Object rc = exec.invoke(null, out, arguments); if (rc instanceof Integer) { return ((Integer) rc).intValue(); } else { throw new IllegalStateException("Unexpected return: " + rc); } } catch (Throwable e) { LOG.error(e); return -1; } }
public Factory make(Class<?> cl) throws InstantiationException, IllegalAccessException { if (Factory.class.isAssignableFrom(cl)) return (cl.asSubclass(Factory.class).newInstance()); try { final Method mkm = cl.getDeclaredMethod("mkwidget", Widget.class, Object[].class); int mod = mkm.getModifiers(); if (Widget.class.isAssignableFrom(mkm.getReturnType()) && ((mod & Modifier.STATIC) != 0) && ((mod & Modifier.PUBLIC) != 0)) { return (new Factory() { public Widget create(Widget parent, Object[] args) { try { return ((Widget) mkm.invoke(null, parent, args)); } catch (Exception e) { if (e instanceof RuntimeException) throw ((RuntimeException) e); throw (new RuntimeException(e)); } } }); } } catch (NoSuchMethodException e) { } return (null); }
private Method cacheMethod( Object obj, String methodName, Class[] methodParameters, HashMap methodCache) { Class objClass = obj.getClass(); Method objMethod = null; // Look up inheritance hierarchy while (objClass != Object.class) { try { objMethod = objClass.getDeclaredMethod(methodName, methodParameters); objClass = Object.class; // executed only if call succeeds } catch (NoSuchMethodException nsmE) { objClass = objClass.getSuperclass(); } } // Cache result if (objMethod == null) { methodCache.put(obj.getClass(), NONE); } else { objMethod.setAccessible(true); // monstrous, monstrous methodCache.put(obj.getClass(), objMethod); } return objMethod; }
@SuppressWarnings("unchecked") LDAPObjectHandler(final Class<T> type) throws LDAPPersistException { this.type = type; final Class<? super T> superclassType = type.getSuperclass(); if (superclassType == null) { superclassHandler = null; } else { final LDAPObject superclassAnnotation = superclassType.getAnnotation(LDAPObject.class); if (superclassAnnotation == null) { superclassHandler = null; } else { superclassHandler = new LDAPObjectHandler(superclassType); } } final TreeMap<String, FieldInfo> fields = new TreeMap<String, FieldInfo>(); final TreeMap<String, GetterInfo> getters = new TreeMap<String, GetterInfo>(); final TreeMap<String, SetterInfo> setters = new TreeMap<String, SetterInfo>(); ldapObject = type.getAnnotation(LDAPObject.class); if (ldapObject == null) { throw new LDAPPersistException(ERR_OBJECT_HANDLER_OBJECT_NOT_ANNOTATED.get(type.getName())); } final LinkedHashMap<String, String> objectClasses = new LinkedHashMap<String, String>(10); final String oc = ldapObject.structuralClass(); if (oc.length() == 0) { structuralClass = getUnqualifiedClassName(type); } else { structuralClass = oc; } final StringBuilder invalidReason = new StringBuilder(); if (PersistUtils.isValidLDAPName(structuralClass, invalidReason)) { objectClasses.put(toLowerCase(structuralClass), structuralClass); } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_STRUCTURAL_CLASS.get( type.getName(), structuralClass, invalidReason.toString())); } auxiliaryClasses = ldapObject.auxiliaryClass(); for (final String auxiliaryClass : auxiliaryClasses) { if (PersistUtils.isValidLDAPName(auxiliaryClass, invalidReason)) { objectClasses.put(toLowerCase(auxiliaryClass), auxiliaryClass); } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_AUXILIARY_CLASS.get( type.getName(), auxiliaryClass, invalidReason.toString())); } } superiorClasses = ldapObject.superiorClass(); for (final String superiorClass : superiorClasses) { if (PersistUtils.isValidLDAPName(superiorClass, invalidReason)) { objectClasses.put(toLowerCase(superiorClass), superiorClass); } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_SUPERIOR_CLASS.get( type.getName(), superiorClass, invalidReason.toString())); } } if (superclassHandler != null) { for (final String s : superclassHandler.objectClassAttribute.getValues()) { objectClasses.put(toLowerCase(s), s); } } objectClassAttribute = new Attribute("objectClass", objectClasses.values()); final String parentDNStr = ldapObject.defaultParentDN(); try { defaultParentDN = new DN(parentDNStr); } catch (LDAPException le) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_DEFAULT_PARENT.get( type.getName(), parentDNStr, le.getMessage()), le); } final String postDecodeMethodName = ldapObject.postDecodeMethod(); if (postDecodeMethodName.length() > 0) { try { postDecodeMethod = type.getDeclaredMethod(postDecodeMethodName); postDecodeMethod.setAccessible(true); } catch (Exception e) { debugException(e); throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_POST_DECODE_METHOD.get( type.getName(), postDecodeMethodName, getExceptionMessage(e)), e); } } else { postDecodeMethod = null; } final String postEncodeMethodName = ldapObject.postEncodeMethod(); if (postEncodeMethodName.length() > 0) { try { postEncodeMethod = type.getDeclaredMethod(postEncodeMethodName, Entry.class); postEncodeMethod.setAccessible(true); } catch (Exception e) { debugException(e); throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_POST_ENCODE_METHOD.get( type.getName(), postEncodeMethodName, getExceptionMessage(e)), e); } } else { postEncodeMethod = null; } try { constructor = type.getDeclaredConstructor(); constructor.setAccessible(true); } catch (Exception e) { debugException(e); throw new LDAPPersistException( ERR_OBJECT_HANDLER_NO_DEFAULT_CONSTRUCTOR.get(type.getName()), e); } Field tmpDNField = null; Field tmpEntryField = null; final LinkedList<FieldInfo> tmpRFilterFields = new LinkedList<FieldInfo>(); final LinkedList<FieldInfo> tmpAAFilterFields = new LinkedList<FieldInfo>(); final LinkedList<FieldInfo> tmpCAFilterFields = new LinkedList<FieldInfo>(); final LinkedList<FieldInfo> tmpRDNFields = new LinkedList<FieldInfo>(); for (final Field f : type.getDeclaredFields()) { final LDAPField fieldAnnotation = f.getAnnotation(LDAPField.class); final LDAPDNField dnFieldAnnotation = f.getAnnotation(LDAPDNField.class); final LDAPEntryField entryFieldAnnotation = f.getAnnotation(LDAPEntryField.class); if (fieldAnnotation != null) { f.setAccessible(true); final FieldInfo fieldInfo = new FieldInfo(f, type); final String attrName = toLowerCase(fieldInfo.getAttributeName()); if (fields.containsKey(attrName)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), fieldInfo.getAttributeName())); } else { fields.put(attrName, fieldInfo); } switch (fieldInfo.getFilterUsage()) { case REQUIRED: tmpRFilterFields.add(fieldInfo); break; case ALWAYS_ALLOWED: tmpAAFilterFields.add(fieldInfo); break; case CONDITIONALLY_ALLOWED: tmpCAFilterFields.add(fieldInfo); break; case EXCLUDED: default: break; } if (fieldInfo.includeInRDN()) { tmpRDNFields.add(fieldInfo); } } if (dnFieldAnnotation != null) { f.setAccessible(true); if (fieldAnnotation != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_CONFLICTING_FIELD_ANNOTATIONS.get( type.getName(), "LDAPField", "LDAPDNField", f.getName())); } if (tmpDNField != null) { throw new LDAPPersistException(ERR_OBJECT_HANDLER_MULTIPLE_DN_FIELDS.get(type.getName())); } final int modifiers = f.getModifiers(); if (Modifier.isFinal(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_DN_FIELD_FINAL.get(f.getName(), type.getName())); } else if (Modifier.isStatic(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_DN_FIELD_STATIC.get(f.getName(), type.getName())); } final Class<?> fieldType = f.getType(); if (fieldType.equals(String.class)) { tmpDNField = f; } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_DN_FIELD_TYPE.get( type.getName(), f.getName(), fieldType.getName())); } } if (entryFieldAnnotation != null) { f.setAccessible(true); if (fieldAnnotation != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_CONFLICTING_FIELD_ANNOTATIONS.get( type.getName(), "LDAPField", "LDAPEntryField", f.getName())); } if (tmpEntryField != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_MULTIPLE_ENTRY_FIELDS.get(type.getName())); } final int modifiers = f.getModifiers(); if (Modifier.isFinal(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ENTRY_FIELD_FINAL.get(f.getName(), type.getName())); } else if (Modifier.isStatic(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ENTRY_FIELD_STATIC.get(f.getName(), type.getName())); } final Class<?> fieldType = f.getType(); if (fieldType.equals(ReadOnlyEntry.class)) { tmpEntryField = f; } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_ENTRY_FIELD_TYPE.get( type.getName(), f.getName(), fieldType.getName())); } } } dnField = tmpDNField; entryField = tmpEntryField; requiredFilterFields = Collections.unmodifiableList(tmpRFilterFields); alwaysAllowedFilterFields = Collections.unmodifiableList(tmpAAFilterFields); conditionallyAllowedFilterFields = Collections.unmodifiableList(tmpCAFilterFields); rdnFields = Collections.unmodifiableList(tmpRDNFields); final LinkedList<GetterInfo> tmpRFilterGetters = new LinkedList<GetterInfo>(); final LinkedList<GetterInfo> tmpAAFilterGetters = new LinkedList<GetterInfo>(); final LinkedList<GetterInfo> tmpCAFilterGetters = new LinkedList<GetterInfo>(); final LinkedList<GetterInfo> tmpRDNGetters = new LinkedList<GetterInfo>(); for (final Method m : type.getDeclaredMethods()) { final LDAPGetter getter = m.getAnnotation(LDAPGetter.class); final LDAPSetter setter = m.getAnnotation(LDAPSetter.class); if (getter != null) { m.setAccessible(true); if (setter != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_CONFLICTING_METHOD_ANNOTATIONS.get( type.getName(), "LDAPGetter", "LDAPSetter", m.getName())); } final GetterInfo methodInfo = new GetterInfo(m, type); final String attrName = toLowerCase(methodInfo.getAttributeName()); if (fields.containsKey(attrName) || getters.containsKey(attrName)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), methodInfo.getAttributeName())); } else { getters.put(attrName, methodInfo); } switch (methodInfo.getFilterUsage()) { case REQUIRED: tmpRFilterGetters.add(methodInfo); break; case ALWAYS_ALLOWED: tmpAAFilterGetters.add(methodInfo); break; case CONDITIONALLY_ALLOWED: tmpCAFilterGetters.add(methodInfo); break; case EXCLUDED: default: // No action required. break; } if (methodInfo.includeInRDN()) { tmpRDNGetters.add(methodInfo); } } if (setter != null) { m.setAccessible(true); final SetterInfo methodInfo = new SetterInfo(m, type); final String attrName = toLowerCase(methodInfo.getAttributeName()); if (fields.containsKey(attrName) || setters.containsKey(attrName)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), methodInfo.getAttributeName())); } else { setters.put(attrName, methodInfo); } } } requiredFilterGetters = Collections.unmodifiableList(tmpRFilterGetters); alwaysAllowedFilterGetters = Collections.unmodifiableList(tmpAAFilterGetters); conditionallyAllowedFilterGetters = Collections.unmodifiableList(tmpCAFilterGetters); rdnGetters = Collections.unmodifiableList(tmpRDNGetters); if (rdnFields.isEmpty() && rdnGetters.isEmpty()) { throw new LDAPPersistException(ERR_OBJECT_HANDLER_NO_RDN_DEFINED.get(type.getName())); } fieldMap = Collections.unmodifiableMap(fields); getterMap = Collections.unmodifiableMap(getters); setterMap = Collections.unmodifiableMap(setters); final TreeSet<String> attrSet = new TreeSet<String>(); final TreeSet<String> lazySet = new TreeSet<String>(); if (ldapObject.requestAllAttributes()) { attrSet.add("*"); attrSet.add("+"); } else { for (final FieldInfo i : fields.values()) { if (i.lazilyLoad()) { lazySet.add(i.getAttributeName()); } else { attrSet.add(i.getAttributeName()); } } for (final SetterInfo i : setters.values()) { attrSet.add(i.getAttributeName()); } } attributesToRequest = new String[attrSet.size()]; attrSet.toArray(attributesToRequest); lazilyLoadedAttributes = new String[lazySet.size()]; lazySet.toArray(lazilyLoadedAttributes); }
private void loadPluginsIntoClassLoader() { File pluginsFile = environment.pluginsFile(); if (!pluginsFile.exists()) { return; } if (!pluginsFile.isDirectory()) { return; } ClassLoader classLoader = settings.getClassLoader(); Class classLoaderClass = classLoader.getClass(); Method addURL = null; while (!classLoaderClass.equals(Object.class)) { try { addURL = classLoaderClass.getDeclaredMethod("addURL", URL.class); addURL.setAccessible(true); break; } catch (NoSuchMethodException e) { // no method, try the parent classLoaderClass = classLoaderClass.getSuperclass(); } } if (addURL == null) { logger.debug( "Failed to find addURL method on classLoader [" + classLoader + "] to add methods"); return; } File[] pluginsFiles = pluginsFile.listFiles(); for (File pluginFile : pluginsFiles) { if (!pluginFile.getName().endsWith(".zip")) { continue; } if (logger.isTraceEnabled()) { logger.trace("Processing [{}]", pluginFile); } String pluginNameNoExtension = pluginFile.getName().substring(0, pluginFile.getName().lastIndexOf('.')); File extractedPluginDir = new File(new File(environment.workFile(), "plugins"), pluginNameNoExtension); extractedPluginDir.mkdirs(); File stampsDir = new File(new File(environment.workFile(), "plugins"), "_stamps"); stampsDir.mkdirs(); boolean extractPlugin = true; File stampFile = new File(stampsDir, pluginNameNoExtension + ".stamp"); if (stampFile.exists()) { // read it, and check if its the same size as the pluginFile RandomAccessFile raf = null; try { raf = new RandomAccessFile(stampFile, "r"); long size = raf.readLong(); if (size == pluginFile.length()) { extractPlugin = false; if (logger.isTraceEnabled()) { logger.trace("--- No need to extract plugin, same size [" + size + "]"); } } } catch (Exception e) { // ignore and extract the plugin } finally { if (raf != null) { try { raf.close(); } catch (IOException e) { // ignore } } } } if (extractPlugin) { if (logger.isTraceEnabled()) { logger.trace("--- Extracting plugin to [" + extractedPluginDir + "]"); } deleteRecursively(extractedPluginDir, false); ZipFile zipFile = null; try { zipFile = new ZipFile(pluginFile); Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = zipEntries.nextElement(); if (!(zipEntry.getName().endsWith(".jar") || zipEntry.getName().endsWith(".zip"))) { continue; } String name = zipEntry.getName().replace('\\', '/'); File target = new File(extractedPluginDir, name); Streams.copy(zipFile.getInputStream(zipEntry), new FileOutputStream(target)); } } catch (Exception e) { logger.warn("Failed to extract plugin [" + pluginFile + "], ignoring...", e); continue; } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // ignore } } } try { RandomAccessFile raf = new RandomAccessFile(stampFile, "rw"); raf.writeLong(pluginFile.length()); raf.close(); } catch (Exception e) { // ignore } } try { for (File jarToAdd : extractedPluginDir.listFiles()) { if (!(jarToAdd.getName().endsWith(".jar") || jarToAdd.getName().endsWith(".zip"))) { continue; } addURL.invoke(classLoader, jarToAdd.toURI().toURL()); } } catch (Exception e) { logger.warn("Failed to add plugin [" + pluginFile + "]", e); } } }
@Override protected StringBuilder appendInternal( ObjectLocator locator, StringBuilder stringBuilder, Object value) { insideArray = insideArrayStack.peek(); insideArrayStack.push(false); try { if (value instanceof String && ((String) value).isEmpty()) { appendNullText(stringBuilder); return stringBuilder; } if (!canBeInlinedWithOtherArrayElements(value)) { appendNewLine(stringBuilder); } if (value instanceof Map) { indentationValue++; for (Object key : ((Map) value).keySet()) { appendNewLine( indent(stringBuilder).append(key).append(": ").append(((Map) value).get(key))); } indentationValue--; return stringBuilder; } if (value instanceof XProperty || value instanceof XPartSpecElement || value instanceof XTimePartSpecElement || value instanceof ResultColumn) { removeLastArrayStart(stringBuilder); if (value instanceof ResultColumn) { ResultColumn column = (ResultColumn) value; indent(stringBuilder).append(column.getName()).append(": ").append(column.getType()); } if (value instanceof XProperty) { XProperty property = (XProperty) value; indent(stringBuilder).append(property.getName()).append(": ").append(property.getValue()); } if (value instanceof XPartSpecElement) { XPartSpecElement partSpecElement = (XPartSpecElement) value; indent(stringBuilder) .append(partSpecElement.getKey()) .append(": ") .append(partSpecElement.getValue()); } if (value instanceof XTimePartSpecElement) { XTimePartSpecElement partSpecElement = (XTimePartSpecElement) value; indent(stringBuilder) .append(partSpecElement.getKey()) .append(": ") .append(partSpecElement.getValue()); } return appendNewLine(stringBuilder); } if (value instanceof XJoinEdge) { XJoinEdge edge = (XJoinEdge) value; XTableReference from = edge.getFrom(); XTableReference to = edge.getTo(); stringBuilder.setLength(stringBuilder.length() - 2); stringBuilder .append(from.getTable()) .append(".") .append(from.getColumn()) .append(from.isMapsToMany() ? "(many)" : "") .append("=") .append(to.getTable()) .append(".") .append(to.getColumn()) .append(to.isMapsToMany() ? "(many)" : ""); return appendNewLine(stringBuilder); } NameableContext context = getNameableContext(value); if (context != null) { String heading = context.getHeading(); if (isBlank(heading)) { heading = "-"; } if (insideArray) { stringBuilder.setLength(stringBuilder.length() - 2); } String details = context.getDetails(); stringBuilder.append(heading); if (details.charAt(0) != '\n') { stringBuilder.append(" "); } stringBuilder.append(details); return appendNewLine(stringBuilder); } // some other way of getting heading if (value instanceof Collection) { Collection collection = (Collection) value; // try inline StringBuilder allElements = super.appendInternal(locator, new StringBuilder(), value); if (collection.size() != 0 && canBeInlinedWithOtherArrayElements((collection.iterator().next())) && allElements.length() < 120) { stringBuilder.setLength(stringBuilder.length() - 1); String sep = " "; for (Object singleElement : collection) { stringBuilder.append(sep); appendInternal(locator, stringBuilder, singleElement); sep = ", "; } return stringBuilder; } else { return stringBuilder.append(allElements); } } // If this class is just a wrapper over a another object Field[] fields = value.getClass().getDeclaredFields(); int nonStaticFields = 0; String fieldName = null; for (Field field : fields) { if (!Modifier.isStatic(field.getModifiers())) { nonStaticFields++; fieldName = field.getName(); } } if (nonStaticFields == 1) { Class<?> claz = value.getClass(); String getterName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); try { Object wrappedValue = claz.getDeclaredMethod(getterName).invoke(value); return appendNewLine(appendInternal(locator, stringBuilder, wrappedValue)); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { log.trace( "getter access failed for {}#{}. Going the usual way", claz.getName(), getterName, e); } } return super.appendInternal(locator, stringBuilder, value); } finally { insideArrayStack.pop(); } }
public static void doIt(Config config) throws java.io.IOException, Schema2BeansException { normalizeConfig(config); calculateNewestSourceTime(config); boolean needToWriteMetaDD = processMetaDD(config); // The class that build the DTD object graph TreeBuilder tree = new TreeBuilder(config); // The file parser calling back the handler SchemaParser parser = null; boolean tryAgain; int schemaType = config.getSchemaTypeNum(); SchemaParseException lastException = null; do { tryAgain = false; if (schemaType == Config.XML_SCHEMA) { XMLSchemaParser xmlSchemaParser = new XMLSchemaParser(config, tree); if (config.getInputURI() != null) xmlSchemaParser.setInputURI(config.getInputURI()); parser = xmlSchemaParser; } else { parser = new DocDefParser(config, tree); } readBeanGraphs(config); try { // parse the DTD, building the object graph parser.process(); } catch (SchemaParseException e) { if (schemaType == Config.DTD) { // Retry as XML Schema tryAgain = true; schemaType = Config.XML_SCHEMA; } else { if (lastException == null) throw e; else throw lastException; } lastException = e; } } while (tryAgain); config.setSchemaTypeNum(schemaType); // Build the beans from the graph, and code generate them out to disk. BeanBuilder builder = new BeanBuilder(tree, config, config.getCodeGeneratorFactory()); builder.process(); if (needToWriteMetaDD) { try { config.messageOut.println("Writing metaDD XML file"); // NOI18N FileOutputStream mddOut = new FileOutputStream(config.getMddFile()); config.getMetaDD().write(mddOut); mddOut.close(); } catch (IOException e) { config.messageOut.println("Failed to write the mdd file: " + e.getMessage()); // NOI18N throw e; } } if (config.isDoCompile() && config.getOutputStreamProvider() instanceof DefaultOutputStreamProvider) { DefaultOutputStreamProvider out = (DefaultOutputStreamProvider) config.getOutputStreamProvider(); String[] javacArgs = new String[out.getGeneratedFiles().size()]; int javaFileCount = 0; for (Iterator it = out.getGeneratedFiles().iterator(); it.hasNext(); ) { javacArgs[javaFileCount] = (String) it.next(); ++javaFileCount; } if (javaFileCount == 0) { if (!config.isQuiet()) config.messageOut.println(Common.getMessage("MSG_NothingToCompile")); } else { if (!config.isQuiet()) config.messageOut.println(Common.getMessage("MSG_Compiling")); try { Class javacClass = Class.forName("com.sun.tools.javac.Main"); java.lang.reflect.Method compileMethod = javacClass.getDeclaredMethod( "compile", new Class[] {String[].class, PrintWriter.class}); // com.sun.tools.javac.Main.compile(javacArgs, pw); PrintWriter pw = new PrintWriter(config.messageOut, true); Object result = compileMethod.invoke(null, new Object[] {javacArgs, pw}); pw.flush(); int compileExitCode = 0; if (result instanceof Integer) compileExitCode = ((Integer) result).intValue(); if (compileExitCode != 0) throw new RuntimeException( "Compile errors: javac had an exit code of " + compileExitCode); } catch (java.lang.Exception e) { // Maybe it's just a missing $JRE/tools.jar from // the CLASSPATH. // config.messageOut.println(Common.getMessage("MSG_UnableToCompile")); // config.messageOut.println(e.getClass().getName()+": "+e.getMessage()); // NOI18N // e.printStackTrace(); if (e instanceof IOException) throw (IOException) e; if (e instanceof Schema2BeansException) throw (Schema2BeansException) e; throw new Schema2BeansNestedException(Common.getMessage("MSG_UnableToCompile"), e); } } } }
/** @param arg */ public static void main(String arg[]) { TestApp af = new TestApp(); SourceImage sImg = null; int imagesPerRow = 0; int imagesPerCol = 0; int imgMin = 65536; int imgMax = 0; boolean signed = false; boolean inverted = false; boolean hasPad = false; int padValue = 0; if (arg.length == 6) { // do it with raw file int w = 0; int h = 0; int d = 0; try { w = Integer.valueOf(arg[1]).intValue(); h = Integer.valueOf(arg[2]).intValue(); d = Integer.valueOf(arg[3]).intValue(); imagesPerRow = Integer.valueOf(arg[4]).intValue(); imagesPerCol = Integer.valueOf(arg[5]).intValue(); } catch (Exception e) { System.err.println(e); System.exit(0); } try { FileInputStream i = new FileInputStream(arg[0]); sImg = new SourceImage(i, w, h, d); } catch (Exception e) { System.err.println(e); System.exit(0); } } else { // do it with DICOM file if (arg.length > 2) { try { imagesPerRow = Integer.valueOf(arg[1]).intValue(); imagesPerCol = Integer.valueOf(arg[2]).intValue(); } catch (Exception e) { System.err.println(e); e.printStackTrace(System.err); System.exit(0); } } else { imagesPerRow = 1; imagesPerCol = 1; } try { DicomInputStream i = new DicomInputStream(new FileInputStream(arg[0])); sImg = new SourceImage(i); } catch (Exception e) { System.err.println(e); e.printStackTrace(System.err); System.exit(0); } } try { // com.apple.cocoa.application.NSMenu.setMenuBarVisible(false); // Won't compile on // other platforms // Class classToUse = // ClassLoader.getSystemClassLoader().loadClass("com.apple.cocoa.application.NSMenu"); // // Needs "/System/Library/Java" in classpath Class classToUse = new java.net.URLClassLoader(new java.net.URL[] {new File("/System/Library/Java").toURL()}) .loadClass("com.apple.cocoa.application.NSMenu"); Class[] parameterTypes = {Boolean.TYPE}; java.lang.reflect.Method methodToUse = classToUse.getDeclaredMethod("setMenuBarVisible", parameterTypes); Object[] args = {Boolean.FALSE}; methodToUse.invoke(null /*since static*/, args); } catch (Exception e) { // ClassNotFoundException,NoSuchMethodException,IllegalAccessException e.printStackTrace(System.err); } java.awt.Dimension d = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); int frameWidth = (int) d.getWidth(); int frameHeight = (int) d.getHeight(); System.err.println("frameWidth=" + frameWidth); System.err.println("frameHeight=" + frameHeight); af.setUndecorated(true); af.setLocation(0, 0); af.setSize(frameWidth, frameHeight); JPanel multiPanel = new JPanel(); multiPanel.setLayout(new GridLayout(imagesPerCol, imagesPerRow)); multiPanel.setBackground(Color.black); SingleImagePanel imagePanel[] = new SingleImagePanel[imagesPerRow * imagesPerCol]; int singleWidth = frameWidth / imagesPerRow; int singleHeight = frameHeight / imagesPerCol; System.err.println("singleWidth=" + singleWidth); System.err.println("singleHeight=" + singleHeight); for (int x = 0; x < imagesPerCol; ++x) { for (int y = 0; y < imagesPerRow; ++y) { SingleImagePanel ip = new SingleImagePanel(sImg); // ip.setPreferredSize(new Dimension(img.getWidth(),img.getHeight())); // ip.setPreferredSize(new Dimension(sImg.getWidth(),sImg.getHeight())); ip.setPreferredSize(new Dimension(singleWidth, singleHeight)); multiPanel.add(ip); imagePanel[x * imagesPerRow + y] = ip; } } // multiPanel.setSize(img.getWidth()*imagesPerRow,img.getHeight()*imagesPerRow); // JScrollPane scrollPane = new JScrollPane(multiPanel); Container content = af.getContentPane(); content.setLayout(new GridLayout(1, 1)); // content.add(scrollPane); content.add(multiPanel); af.pack(); af.setVisible(true); }
public StructDef(Class c, String path, org.omg.CORBA.Container _defined_in, org.omg.CORBA.Repository ir) { def_kind = org.omg.CORBA.DefinitionKind.dk_Struct; containing_repository = ir; defined_in = _defined_in; this.path = path; Debug.assert( defined_in != null, "defined_in = null"); Debug.assert( containing_repository != null, "containing_repository = null"); try { String classId = c.getName(); myClass = c; version( "1.0" ); full_name = classId.replace('.', '/'); if( classId.indexOf('.') > 0 ) { name( classId.substring( classId.lastIndexOf('.')+1 ) ); absolute_name = org.omg.CORBA.ContainedHelper.narrow( defined_in ).absolute_name() + "::" + name; } else { name( classId ); absolute_name = "::" + name; } helperClass = RepositoryImpl.loader.loadClass( classId + "Helper") ; id( (String)helperClass.getDeclaredMethod( "id", null ).invoke( null, null )); type = TypeCodeUtil.getTypeCode( myClass, RepositoryImpl.loader, null, classId ); members = new org.omg.CORBA.StructMember[ type.member_count() ]; for( int i = 0; i < members.length; i++ ) { org.omg.CORBA.TypeCode type_code = type.member_type(i); String member_name = type.member_name(i); members[i] = new org.omg.CORBA.StructMember( member_name, type_code, null ); } /* get directory for nested definitions' classes */ File f = new File( path + fileSeparator + classId.replace('.', fileSeparator) + "Package" ); if( f.exists() && f.isDirectory() ) my_dir = f; org.jacorb.util.Debug.output(2, "StructDef: " + absolute_name ); } catch ( Exception e ) { e.printStackTrace(); throw new org.omg.CORBA.INTF_REPOS( ErrorMsg.IR_Not_Implemented, org.omg.CORBA.CompletionStatus.COMPLETED_NO); } }