/** Do the execution. */ public void execute() throws BuildException { Method setProjectM = null; try { Class c = proxy.getClass(); setProjectM = c.getMethod("setProject", new Class[] {Project.class}); if (setProjectM != null) { setProjectM.invoke(proxy, new Object[] {project}); } } catch (Exception ex) { log("Error setting project in " + proxy.getClass(), Project.MSG_ERR); throw new BuildException(ex); } Method executeM = null; try { Class c = proxy.getClass(); executeM = c.getMethod("execute", new Class[0]); if (executeM == null) { log("No execute in " + proxy.getClass(), Project.MSG_ERR); throw new BuildException("No execute in " + proxy.getClass()); } executeM.invoke(proxy, null); return; } catch (Exception ex) { log("Error in " + proxy.getClass(), Project.MSG_ERR); throw new BuildException(ex); } }
Document parseDocument(String filename) throws Exception { FileReader reader = new FileReader(filename); String firstLine = new BufferedReader(reader).readLine(); reader.close(); Document document = null; if (firstLine.startsWith("<?xml")) { System.err.println("XML detected; using default XML parser."); } else { try { Class nekoParserClass = Class.forName("org.cyberneko.html.parsers.DOMParser"); Object parser = nekoParserClass.newInstance(); Method parse = nekoParserClass.getMethod("parse", new Class[] {String.class}); Method getDocument = nekoParserClass.getMethod("getDocument", new Class[0]); parse.invoke(parser, filename); document = (Document) getDocument.invoke(parser); } catch (Exception e) { System.err.println("NekoHTML HTML parser not found; HTML4 support disabled."); } } if (document == null) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { // http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); } catch (ParserConfigurationException e) { System.err.println("Warning: Could not disable external DTD loading"); } DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(filename); } return document; }
/** private method which actually will do all of our work for the sample */ private void executeSample() { String query = "select anEmployee from staff2"; try { Statement stmt = _con.createStatement(); ; // Execute the query which will return an Employee object // We will cast this using the Person interface. Note the // Person interface class MUST be in your CLASSPATH. You // Do not need Employee in your CLASSPATH. ResultSet rs = stmt.executeQuery(query); output("***Using interface class\n"); while (rs.next()) { Person aPerson = (Person) rs.getObject(1); displayMethods(aPerson.getClass()); output( "The person is: " + aPerson.toString() + "\nFirst Name= " + aPerson.getFirstName() + "\nLast Name= " + aPerson.getLastName() + "\n"); } // Now execute the same query, but this time we will use // reflection to access the class. Again, only the interface // Person is required in the CLASSPATH rs = stmt.executeQuery(query); output("***Using reflection\n"); Object theObj = null; while (rs.next()) { theObj = rs.getObject(1); output("The person is: " + theObj.toString() + "\n"); Class theClass = theObj.getClass(); displayMethods(theClass); Method m1 = theClass.getMethod("toString", new Class[0]); Method m2 = theClass.getMethod("getFirstName", new Class[0]); Method m3 = theClass.getMethod("getLastName", new Class[0]); output( "The person is: " + (Object) m1.invoke(theObj, new Object[0]) + "\nFirst Name= " + (Object) m2.invoke(theObj, new Object[0]) + "\nLast Name= " + (Object) m3.invoke(theObj, new Object[0]) + "\n"); } rs.close(); stmt.close(); } catch (SQLException sqe) { displaySQLEx(sqe); } catch (Exception e) { error("Unexpected exception : " + e.toString() + "\n"); e.printStackTrace(); } }
public void process(File cFile) { try { String cName = ClassNameFinder.thisClass(BinaryFile.read(cFile)); if (!cName.contains("")) return; // Ignore unpackaged classes testClass = Class.forName(cName); } catch (Exception e) { throw new RuntimeException(e); } TestMethods testMethods = new TestMethods(); Method creator = null; Method cleanup = null; for (Method m : testClass.getDeclaredMethods()) { testMethods.addIfTestMethod(m); if (creator == null) creator = checkForCreatorMethod(m); if (cleanup == null) cleanup = checkForCleanupMethod(m); } if (testMethods.size() > 0) { if (creator == null) try { if (!Modifier.isPublic(testClass.getDeclaredConstructor().getModifiers())) { Print.print("Error: " + testClass + " default constructor must be public"); System.exit(1); } } catch (NoSuchMethodException e) { // Synthesized default constructor; OK } Print.print(testClass.getName()); } for (Method m : testMethods) { Print.printnb(" . " + m.getName() + " "); try { Object testObject = createTestObject(creator); boolean success = false; try { if (m.getReturnType().equals(boolean.class)) success = (Boolean) m.invoke(testObject); else { m.invoke(testObject); success = true; // If no assert fails } } catch (InvocationTargetException e) { // Actual exception is inside e: Print.print(e.getCause()); } Print.print(success ? "" : "(failed)"); testsRun++; if (!success) { failures++; failedTests.add(testClass.getName() + ": " + m.getName()); } if (cleanup != null) cleanup.invoke(testObject, testObject); } catch (Exception e) { throw new RuntimeException(e); } } }
public static final void fireEvent(GenericEvent e, Method m, Vector listeners) throws PropertyVetoException { Object[] snapshot = null; synchronized (listeners) { snapshot = new Object[listeners.size()]; listeners.copyInto(snapshot); } // leighd 04/14/99 - modified for event debugging if (gDebugEvents) Engine.debugLog("Event : " + e.toString()); Object params[] = new Object[] {e}; for (int i = 0; i < snapshot.length; i++) { if ((e instanceof Consumable) && ((Consumable) e).isConsumed()) { // leighd 04/14/99 // note that we don't catch the consumption of the // event until we've passed through the loop again, // so we reference i-1 if (gDebugEvents) Engine.debugLog("Consumed By : " + snapshot[i - 1]); return; } try { m.invoke(snapshot[i], params); } catch (IllegalAccessException iae) { iae.printStackTrace(); } catch (InvocationTargetException ite) { Throwable t = ite.getTargetException(); if (t instanceof PropertyVetoException) throw ((PropertyVetoException) t); else t.printStackTrace(); } } }
/** * 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; }
/** * 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<>(); } }
// we set an observer to detect VirtualMachineImpl.dispose call // and on dispose we add corresponding VirtualMachineImpl.class to // free VirtualMachimeImpl Class list. protected static void setVMDisposeObserver(final Object vm) { try { Method setDisposeObserverMethod = vm.getClass() .getDeclaredMethod("setDisposeObserver", new Class[] {java.util.Observer.class}); setDisposeObserverMethod.setAccessible(true); setDisposeObserverMethod.invoke( vm, new Object[] { new Observer() { public void update(Observable o, Object data) { if (DEBUG) { System.out.println("got VM.dispose notification"); } addFreeVMImplClass(vm.getClass()); } } }); } catch (Exception exp) { if (DEBUG) { System.out.println("setVMDisposeObserver() got an exception:"); exp.printStackTrace(); } } }
/* gets target VM version from the given VMVersionMismatchException. * Note that we need to reflectively call the method because of we may * have got this from different classloader's namespace */ private static String getVMVersion(Throwable throwable) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // assert isVMVersionMismatch(throwable), "not a VMVersionMismatch" Class expClass = throwable.getClass(); Method targetVersionMethod = expClass.getMethod("getTargetVersion", new Class[0]); return (String) targetVersionMethod.invoke(throwable); }
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). }
public void apply(Object aTo, T aWith) { try { method.invoke(aTo, aWith); } catch (Exception anExc) { throw new XmlReadingException(anExc); } }
/** * Gets the ObjectLoader for the specified class. * * @param classtype the class * @return the ObjectLoader */ public static XML.ObjectLoader getLoader(Class classtype) { // look for registered loader first ObjectLoader loader = (ObjectLoader) loaders.get(classtype); // if no registered loader, look for static getLoader() method in class if (loader == null) { try { Method method = classtype.getMethod("getLoader", (Class[]) null); // $NON-NLS-1$ if (method != null && Modifier.isStatic(method.getModifiers())) { loader = (ObjectLoader) method.invoke(null, (Object[]) null); if (loader != null) { // register loader for future calls setLoader(classtype, loader); } } } catch (Exception ex) { /** empty block */ } } // if still no loader found, use the default loader if (loader == null) { if (defaultLoader == null) { defaultLoader = new XMLLoader(); } loader = defaultLoader; } return loader; }
private boolean invokeMethod(String line, PrintWriter out, Method method, String[] fields) throws IllegalAccessException, InvocationTargetException { ArrayList<Object> methodArguments = new ArrayList<Object>(); Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 2 && parameterTypes[0] == PrintWriter.class && parameterTypes[1] == String.class) { // FIXME: there must be a better way to say "I want to parse the line myself." methodArguments.add(out); methodArguments.add(line); } else { int nextField = 1; for (Class<?> parameterType : parameterTypes) { if (parameterType == PrintWriter.class) { methodArguments.add(out); } else if (parameterType == String.class) { methodArguments.add(fields[nextField++]); } // FIXME: support other common types. "int" seems a likely first candidate. } } method.invoke(handler, methodArguments.toArray()); return true; }
Entry encode(final T o, final String parentDN) throws LDAPPersistException { // Get the attributes that should be included in the entry. final LinkedHashMap<String, Attribute> attrMap = new LinkedHashMap<String, Attribute>(); attrMap.put("objectClass", objectClassAttribute); for (final Map.Entry<String, FieldInfo> e : fieldMap.entrySet()) { final FieldInfo i = e.getValue(); if (!i.includeInAdd()) { continue; } final Attribute a = i.encode(o, false); if (a != null) { attrMap.put(e.getKey(), a); } } for (final Map.Entry<String, GetterInfo> e : getterMap.entrySet()) { final GetterInfo i = e.getValue(); if (!i.includeInAdd()) { continue; } final Attribute a = i.encode(o); if (a != null) { attrMap.put(e.getKey(), a); } } final String dn = constructDN(o, parentDN, attrMap); final Entry entry = new Entry(dn, attrMap.values()); if (postEncodeMethod != null) { try { postEncodeMethod.invoke(o, entry); } catch (Throwable t) { debugException(t); if (t instanceof InvocationTargetException) { t = ((InvocationTargetException) t).getTargetException(); } throw new LDAPPersistException( ERR_OBJECT_HANDLER_ERROR_INVOKING_POST_ENCODE_METHOD.get( postEncodeMethod.getName(), type.getName(), getExceptionMessage(t)), t); } } setDNAndEntryFields(o, entry); if (superclassHandler != null) { final Entry e = superclassHandler.encode(o, parentDN); for (final Attribute a : e.getAttributes()) { entry.addAttribute(a); } } return entry; }
/** * This method returns the maximum representation size of an object. <code>sizeSoFar</code> is the * object's size measured so far. <code>f</code> is the field being probed. * * <p>The returned offset will be the maximum of whatever was measured so far and <code>f</code> * field's offset and representation size (unaligned). */ private static long adjustForField(long sizeSoFar, final Field f) { final Class<?> type = f.getType(); final int fsize = type.isPrimitive() ? primitiveSizes.get(type) : NUM_BYTES_OBJECT_REF; if (objectFieldOffsetMethod != null) { try { final long offsetPlusSize = ((Number) objectFieldOffsetMethod.invoke(theUnsafe, f)).longValue() + fsize; return Math.max(sizeSoFar, offsetPlusSize); } catch (IllegalAccessException ex) { throw new RuntimeException("Access problem with sun.misc.Unsafe", ex); } catch (InvocationTargetException ite) { final Throwable cause = ite.getCause(); if (cause instanceof RuntimeException) throw (RuntimeException) cause; if (cause instanceof Error) throw (Error) cause; // this should never happen (Unsafe does not declare // checked Exceptions for this method), but who knows? throw new RuntimeException( "Call to Unsafe's objectFieldOffset() throwed " + "checked Exception when accessing field " + f.getDeclaringClass().getName() + "#" + f.getName(), cause); } } else { // TODO: No alignments based on field type/ subclass fields alignments? return sizeSoFar + fsize; } }
/** processing method invoked from a Web environment */ public void doHPTransaction(HttpServletRequest req, HttpServletResponse resp) throws BeanException { oHttpServletRequest = req; oHttpServletResponse = resp; if (tracing == true) { traceArgs[0] = this; traceArgs[1] = " CrownCounselIndexGetList_Access.doHPTransaction()"; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } try { startHereCommon(); } catch (BeanException e) { // remove the ejb instance if handle exists if (ejb != null) { try { ejb.remove(); } catch (Exception x) { } ejb = null; } // go set error fields setupErrorFields(e); throw e; // rethrow the exception. } }
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 void renderValue( Object aObj, JSONObject aObjectElement, JSONMarshall aMarshall, HashMap aPool) throws MarshallException { final JSONObject lElements = new JSONObject(); aObjectElement.getValue().put(JSONMarshall.RNDR_ATTR_VALUE, lElements); try { Class lClass = aObj.getClass(); PropertyDescriptor[] lPropDesc = Introspector.getBeanInfo(lClass, Introspector.USE_ALL_BEANINFO).getPropertyDescriptors(); for (int i = 0; i < lPropDesc.length; i++) { Method lReader = lPropDesc[i].getReadMethod(); Method lWriter = lPropDesc[i].getWriteMethod(); String lPropName = lPropDesc[i].getName(); // Only serialize if the property is READ-WRITE. if (lReader != null && lWriter != null) { lElements .getValue() .put(lPropName, aMarshall.marshallImpl(lReader.invoke(aObj, new Object[] {}), aPool)); } } } catch (IntrospectionException e) { final String lMsg = "Error while introspecting JavaBean."; throw new MarshallException(lMsg); } catch (IllegalAccessException e) { final String lMsg = "Illegal access while trying to fetch a bean property (1)."; throw new MarshallException(lMsg); } catch (InvocationTargetException e) { final String lMsg = "Illegal access while trying to fetch a bean property (2)."; throw new MarshallException(lMsg); } }
private String doCommand(Object target, String method, String[] args) { if (target == null) ; // System.err.println("Huh? Target should never be null " + // domain); else { String cname = "_" + method.replaceAll("-", "_"); try { Method m = target.getClass().getMethod(cname, new Class[] {String[].class}); return (String) m.invoke(target, new Object[] {args}); } catch (NoSuchMethodException e) { // Ignore } catch (InvocationTargetException e) { if (e.getCause() instanceof IllegalArgumentException) { domain.error( "%s, for cmd: %s, arguments; %s", e.getCause().getMessage(), method, Arrays.toString(args)); } else { domain.warning("Exception in replace: %s", e.getCause()); e.getCause().printStackTrace(); } } catch (Exception e) { domain.warning("Exception in replace: " + e + " method=" + method); e.printStackTrace(); } } return null; }
/** Creates the URL connection. */ protected URLConnection openConnection(URL url) throws IOException { URLConnection conn = url.openConnection(); conn.setDoOutput(true); if (_readTimeout > 0) { try { // only available for JDK 1.5 Method method = conn.getClass().getMethod("setReadTimeout", new Class[] {int.class}); if (method != null) method.invoke(conn, new Object[] {new Integer((int) _readTimeout)}); } catch (Throwable e) { } } conn.setRequestProperty("Content-Type", "x-application/hessian"); if (_basicAuth != null) conn.setRequestProperty("Authorization", _basicAuth); else if (_user != null && _password != null) { _basicAuth = "Basic " + base64(_user + ":" + _password); conn.setRequestProperty("Authorization", _basicAuth); } return conn; }
/** * Returns the clone of <code>o_</code>. It calls <code>o_.clone()</code>, if possible, and either * raises an exception or returns null if fails. * * @param raiseException_ set to true if one wishes to get exception instead of receiving null * when this method fails to call <code>o_.clone()</code>. */ public static Object clone(Object o_, boolean raiseException_) { if (o_ == null) return null; if (o_ instanceof String) return o_; try { if (o_ instanceof drcl.ObjectCloneable) return ((drcl.ObjectCloneable) o_).clone(); if (o_.getClass().isArray()) { int length_ = Array.getLength(o_); Class componentType_ = o_.getClass().getComponentType(); Object that_ = Array.newInstance(componentType_, length_); if (componentType_.isPrimitive()) System.arraycopy(o_, 0, that_, 0, length_); else { for (int i = 0; i < length_; i++) Array.set(that_, i, clone(Array.get(o_, i), raiseException_)); } return that_; } Method m_ = o_.getClass().getMethod("clone", null); return m_.invoke(o_, null); } catch (Exception e_) { if (raiseException_) { Thread t_ = Thread.currentThread(); t_.getThreadGroup().uncaughtException(t_, e_); } return null; } }
/** processing method invoked from application */ public void processRequest() throws BeanException { if (tracing == true) { traceArgs[0] = this; traceArgs[1] = " CrownCounselIndexGetList_Access.processRequest()"; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } try { startHereCommon(); } catch (BeanException e) { // remove the ejb instance if handle exists if (ejb != null) { try { ejb.remove(); } catch (Exception x) { } ejb = null; } // go set error fields setupErrorFields(e); throw e; } }
/** * Insert the source code details, if available. * * @param ped The given program element. */ public void addSourcePosition(ProgramElementDoc ped, int indent) { if (!addSrcInfo) return; if (JDiff.javaVersion.startsWith("1.1") || JDiff.javaVersion.startsWith("1.2") || JDiff.javaVersion.startsWith("1.3")) { return; // position() only appeared in J2SE1.4 } try { // Could cache the method for improved performance Class c = ProgramElementDoc.class; Method m = c.getMethod("position", null); Object sp = m.invoke(ped, null); if (sp != null) { for (int i = 0; i < indent; i++) outputFile.print(" "); outputFile.println("src=\"" + sp + "\""); } } catch (NoSuchMethodException e2) { System.err.println("Error: method \"position\" not found"); e2.printStackTrace(); } catch (IllegalAccessException e4) { System.err.println("Error: class not permitted to be instantiated"); e4.printStackTrace(); } catch (InvocationTargetException e5) { System.err.println("Error: method \"position\" could not be invoked"); e5.printStackTrace(); } catch (Exception e6) { System.err.println("Error: "); e6.printStackTrace(); } }
public java.lang.String getHPubXMLProperties(java.lang.String value) { if (tracing == true) { traceArgs[0] = this; traceArgs[1] = "CrownCounselIndexGetList_Access.getHPubXMLProperties(String)"; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } inputProps.setHPubStyleSheet(value); try { startHereCommon(); } catch (BeanException e) { // remove the ejb instance if handle exists if (ejb != null) { try { ejb.remove(); } catch (Exception x) { } ejb = null; } // go set error fields setupErrorFields(e); } if (outputProps != null) return outputProps.getHPubXMLData(); else return null; }
/** * Handles a received {@link MBeanServerConnection} invocation * * @param channel The channel the request was received on * @param remoteAddress The remote address of the caller * @param buffer THe buffer received */ public static void handleJMXRequest( Channel channel, SocketAddress remoteAddress, ChannelBuffer buffer) { buffer.resetReaderIndex(); /* The request write */ // cb.writeByte(OpCode.JMX_REQUEST.op()); // 1 // cb.writeBytes(domainInfoData); // domain data // cb.writeInt(reqId); // 4 // cb.writeByte(methodToKey.get(method)); // 1 // cb.writeInt(sargs.length); // 4 // cb.writeBytes(sargs); // sargs.length Object result = null; MBeanServerConnection server = null; buffer.skipBytes(1); byte domainIndicator = buffer.readByte(); if (domainIndicator == 0) { server = JMXHelper.getHeliosMBeanServer(); } else { byte[] domainBytes = new byte[domainIndicator]; buffer.readBytes(domainBytes); String domain = new String(domainBytes); server = JMXHelper.getLocalMBeanServer(true, domain); if (server == null) { result = new SmallException("Failed to locate MBeanServer for domain [" + domain + "]"); } } int reqId = buffer.readInt(); byte methodId = buffer.readByte(); if (result == null) { int payloadSize = buffer.readInt(); byte[] payload = new byte[payloadSize]; buffer.readBytes(payload); Object[] params = getInput(payload); Method targetMethod = null; try { targetMethod = keyToMethod.get(methodId); if (targetMethod == null) { result = new SmallException( "Failed to handle MBeanServerConnection invocation because method Op Code [" + methodId + "] was not recognized"); } else { if ("addNotificationListener".equals(targetMethod.getName()) && !targetMethod.getParameterTypes()[1].equals(ObjectName.class)) { } else if ("removeNotificationListener".equals(targetMethod.getName()) && !targetMethod.getParameterTypes()[1].equals(ObjectName.class)) { } else { result = targetMethod.invoke(server, params); } } } catch (Throwable t) { SimpleLogger.warn("Failed to invoke [", targetMethod, "]", t); result = new SmallException(t.toString()); } } writeJMXResponse(reqId, methodId, channel, remoteAddress, result); }
/** {@inheritDoc} */ public void invokeMethod(String methodName, Class<?>[] paramClasses, Object[] params) throws Exception { if (DEBUG) { configuration.root.printError("DEBUG: " + this.getClass().getName() + "." + methodName); } Method method = this.getClass().getMethod(methodName, paramClasses); method.invoke(this, params); }
boolean closeAndRemoveResourcesInSet(Set s, Method closeMethod) { boolean okay = true; Set temp; synchronized (s) { temp = new HashSet(s); } for (Iterator ii = temp.iterator(); ii.hasNext(); ) { Object rsrc = ii.next(); try { closeMethod.invoke(rsrc, CLOSE_ARGS); } catch (Exception e) { Throwable t = e; if (t instanceof InvocationTargetException) t = ((InvocationTargetException) e).getTargetException(); logger.log(MLevel.WARNING, "An exception occurred while cleaning up a resource.", t); // t.printStackTrace(); okay = false; } finally { s.remove(rsrc); } } // We had to abandon the idea of simply iterating over s directly, because // our resource close methods sometimes try to remove the resource from // its parent Set. This is important (when the user closes the resources // directly), but leads to ConcurrenModificationExceptions while we are // iterating over the Set to close. So, now we iterate over a copy, but remove // from the original Set. Since removal is idempotent, it don't matter if // the close method already provoked a remove. Sucks that we have to copy // the set though. // // Original (direct iteration) version: // // synchronized (s) // { // for (Iterator ii = s.iterator(); ii.hasNext(); ) // { // Object rsrc = ii.next(); // try // { closeMethod.invoke(rsrc, CLOSE_ARGS); } // catch (Exception e) // { // Throwable t = e; // if (t instanceof InvocationTargetException) // t = ((InvocationTargetException) e).getTargetException(); // t.printStackTrace(); // okay = false; // } // finally // { ii.remove(); } // } // } return okay; }
// The default constructor public CrownCounselIndexGetList_Access() { String traceProp = null; if ((traceProp = System.getProperty(HOSTPUBLISHER_ACCESSBEAN_TRACE)) != null) { try { Class c = Class.forName(HOSTPUBLISHER_ACCESSTRACE_OBJECT); Method m = c.getMethod("getInstance", null); o = m.invoke(null, null); Class parmTypes[] = {String.class}; m = c.getMethod("initTrace", parmTypes); Object initTraceArgs[] = {traceProp}; BitSet tracingBS = (BitSet) m.invoke(o, initTraceArgs); Class parmTypes2[] = {Object.class, String.class}; traceMethod = c.getMethod("trace", parmTypes2); tracing = tracingBS.get(HOSTPUBLISHER_ACCESSBEAN_TRACING); Class parmTypes3[] = {String.class, HttpSession.class}; auditMethod = c.getMethod("audit", parmTypes3); auditing = tracingBS.get(HOSTPUBLISHER_ACCESSBEAN_AUDITING); } catch (Exception e) { // no tracing will be done System.err.println( (new Date(System.currentTimeMillis())).toString() + " hostpublisher.accessbean.trace=" + traceProp + ", Exception=" + e.toString()); } } if (tracing == true) { traceArgs[0] = this; traceArgs[1] = " CrownCounselIndexGetList_Access()"; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { System.err.println( (new Date(System.currentTimeMillis())).toString() + " traceMethod.invoke(null, traceArgs)" + ", Exception=" + x.toString()); } } inputProps = new CrownCounselIndexGetList_Properties(); return; }
Object invoke(String method, Class[] argtypes, Object[] args) throws InvocationTargetException { try { Method m = fact.getClass().getMethod(method, argtypes); return m.invoke(fact, args); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { try { String method = m.getName(); if ("prepareStatement".equals(method) || "createStatement".equals(method)) log.info("[SQL] >>> " + args[0]); return m.invoke(conn, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } }