void enableLionFS() { try { String version = System.getProperty("os.version"); String[] tokens = version.split("\\."); int major = Integer.parseInt(tokens[0]), minor = 0; if (tokens.length > 1) minor = Integer.parseInt(tokens[1]); if (major < 10 || (major == 10 && minor < 7)) throw new Exception("Operating system version is " + version); Class fsuClass = Class.forName("com.apple.eawt.FullScreenUtilities"); Class argClasses[] = new Class[] {Window.class, Boolean.TYPE}; Method setWindowCanFullScreen = fsuClass.getMethod("setWindowCanFullScreen", argClasses); setWindowCanFullScreen.invoke(fsuClass, this, true); Class fsListenerClass = Class.forName("com.apple.eawt.FullScreenListener"); InvocationHandler fsHandler = new MyInvocationHandler(cc); Object proxy = Proxy.newProxyInstance( fsListenerClass.getClassLoader(), new Class[] {fsListenerClass}, fsHandler); argClasses = new Class[] {Window.class, fsListenerClass}; Method addFullScreenListenerTo = fsuClass.getMethod("addFullScreenListenerTo", argClasses); addFullScreenListenerTo.invoke(fsuClass, this, proxy); canDoLionFS = true; } catch (Exception e) { vlog.debug("Could not enable OS X 10.7+ full-screen mode:"); vlog.debug(" " + e.toString()); } }
public static void invokeSetMethod(Object obj, String prop, String value) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class cl = obj.getClass(); // change first letter to uppercase String setMeth = "set" + prop.substring(0, 1).toUpperCase() + prop.substring(1); // try string method try { Class[] cldef = {String.class}; Method meth = cl.getMethod(setMeth, cldef); Object[] params = {value}; meth.invoke(obj, params); return; } catch (NoSuchMethodException ex) { try { // try int method Class[] cldef = {Integer.TYPE}; Method meth = cl.getMethod(setMeth, cldef); Object[] params = {Integer.valueOf(value)}; meth.invoke(obj, params); return; } catch (NoSuchMethodException nsmex) { // try boolean method Class[] cldef = {Boolean.TYPE}; Method meth = cl.getMethod(setMeth, cldef); Object[] params = {Boolean.valueOf(value)}; meth.invoke(obj, params); return; } } }
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); } } }
/** * This creates a new <code>{@link Document}</code> from an existing <code>InputStream</code> by * letting a DOM parser handle parsing using the supplied stream. * * @param in <code>InputStream</code> to parse. * @param validate <code>boolean</code> to indicate if validation should occur. * @return <code>Document</code> - instance ready for use. * @throws IOException when I/O error occurs. * @throws JDOMException when errors occur in parsing. */ public Document getDocument(InputStream in, boolean validate) throws IOException, JDOMException { try { // Load the parser class Class parserClass = Class.forName("org.apache.xerces.parsers.DOMParser"); Object parser = parserClass.newInstance(); // Set validation Method setFeature = parserClass.getMethod("setFeature", new Class[] {java.lang.String.class, boolean.class}); setFeature.invoke( parser, new Object[] {"http://xml.org/sax/features/validation", new Boolean(validate)}); // Set namespaces true setFeature.invoke( parser, new Object[] {"http://xml.org/sax/features/namespaces", new Boolean(true)}); // Set the error handler if (validate) { Method setErrorHandler = parserClass.getMethod("setErrorHandler", new Class[] {ErrorHandler.class}); setErrorHandler.invoke(parser, new Object[] {new BuilderErrorHandler()}); } // Parse the document Method parse = parserClass.getMethod("parse", new Class[] {org.xml.sax.InputSource.class}); parse.invoke(parser, new Object[] {new InputSource(in)}); // Get the Document object Method getDocument = parserClass.getMethod("getDocument", null); Document doc = (Document) getDocument.invoke(parser, null); return doc; } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); if (targetException instanceof org.xml.sax.SAXParseException) { SAXParseException parseException = (SAXParseException) targetException; throw new JDOMException( "Error on line " + parseException.getLineNumber() + " of XML document: " + parseException.getMessage(), e); } else if (targetException instanceof IOException) { IOException ioException = (IOException) targetException; throw ioException; } else { throw new JDOMException(targetException.getMessage(), e); } } catch (Exception e) { throw new JDOMException(e.getClass().getName() + ": " + e.getMessage(), e); } }
public void toggleLionFS() { try { Class appClass = Class.forName("com.apple.eawt.Application"); Method getApplication = appClass.getMethod("getApplication", (Class[]) null); Object app = getApplication.invoke(appClass); Method requestToggleFullScreen = appClass.getMethod("requestToggleFullScreen", Window.class); requestToggleFullScreen.invoke(app, this); } catch (Exception e) { vlog.debug("Could not toggle OS X 10.7+ full-screen mode:"); vlog.debug(" " + e.toString()); } }
/** 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. } }
// 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); }
/** 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; } }
private static double toDouble(Object value) { if (value instanceof Number) { return ((Number) value).doubleValue(); } else if (value instanceof String) { return ScriptRuntime.toNumber((String) value); } else if (value instanceof Scriptable) { if (value instanceof Wrapper) { // XXX: optimize tail-recursion? return toDouble(((Wrapper) value).unwrap()); } else { return ScriptRuntime.toNumber(value); } } else { Method meth; try { meth = value.getClass().getMethod("doubleValue", (Class[]) null); } catch (NoSuchMethodException e) { meth = null; } catch (SecurityException e) { meth = null; } if (meth != null) { try { return ((Number) meth.invoke(value, (Object[]) null)).doubleValue(); } catch (IllegalAccessException e) { // XXX: ignore, or error message? reportConversionError(value, Double.TYPE); } catch (InvocationTargetException e) { // XXX: ignore, or error message? reportConversionError(value, Double.TYPE); } } return ScriptRuntime.toNumber(value.toString()); } }
/** * 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; }
/** 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; }
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; }
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; }
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; }
/** * @return a String representation of the invariantToTest. This String is produced by invoking * the invariant's format_using with method with the argument OutputFormat.Daikon. */ private static String getInvariantFormat() { try { return (String) outputProducer.invoke(invariantToTest, new Object[] {OutputFormat.DAIKON}); } catch (Exception e) { throw new RuntimeException(invariantToTest + " " + outputProducer); } }
/** * @return the InvariantStatus produced by invoking invariantToTest's check_modified method on * the arguments represented by params. */ private static InvariantStatus getCheckStatus(Object[] params) { try { return (InvariantStatus) checkModified.invoke(invariantToTest, params); } catch (Exception e) { throw new RuntimeException(" error in " + invariantToTest.getClass() + ": " + 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(); } }
/** * 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); }
/** * Given the name and parameters, invoke the method in the builder. This method is required to * invoke the appropriate build method as instructed by the builder XML file. * * @param methodName the name of the method that we would like to invoke. * @param paramClasses the types for each parameter. * @param params the parameters of the method. */ protected 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); }
public static void invokeSetMethodCaseInsensitive(Object obj, String prop, String value) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String alternateMethodName = null; Class cl = obj.getClass(); String setMeth = "set" + prop; Method[] methodsList = cl.getMethods(); boolean methodFound = false; int i = 0; for (i = 0; i < methodsList.length; ++i) { if (methodsList[i].getName().equalsIgnoreCase(setMeth) == true) { Class[] parameterTypes = methodsList[i].getParameterTypes(); if (parameterTypes.length == 1) { if (parameterTypes[0].getName().equals("java.lang.String")) { methodFound = true; break; } else alternateMethodName = methodsList[i].getName(); } } } if (methodFound == true) { Object[] params = {value}; methodsList[i].invoke(obj, params); return; } if (alternateMethodName != null) { try { // try int method Class[] cldef = {Integer.TYPE}; Method meth = cl.getMethod(alternateMethodName, cldef); Object[] params = {Integer.valueOf(value)}; meth.invoke(obj, params); return; } catch (NoSuchMethodException nsmex) { // try boolean method Class[] cldef = {Boolean.TYPE}; Method meth = cl.getMethod(alternateMethodName, cldef); Object[] params = {Boolean.valueOf(value)}; meth.invoke(obj, params); return; } } else throw new NoSuchMethodException(setMeth); }
// 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; }
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { Object obj = null; if (CLOSE_METHOD_NAME.equals(m.getName())) { SimpleConnectionPool.pushConnectionBackToPool(this); } else { obj = m.invoke(m_originConnection, args); } lastAccessTime = System.currentTimeMillis(); return obj; }
public void run() { while (Thread.currentThread() == thread) { try { Socket socket = server.accept(); Client client = new Client(parent, socket); if (clientValidationMethod != null) { try { clientValidationMethod.invoke(parent, new Object[] {this, client}); } catch (Exception e) { // System.err.println("Disabling serverEvent() for port " + port); e.printStackTrace(); } } if (client.active()) { synchronized (clients) { addClient(client); if (serverEventMethod != null) { try { serverEventMethod.invoke(parent, new Object[] {this, client}); } catch (Exception e) { // System.err.println("Disabling serverEvent() for port " + port); e.printStackTrace(); } } } } } catch (SocketException e) { // thrown when server.close() is called and server is waiting on accept System.err.println("Server SocketException: " + e.getMessage()); thread = null; } catch (IOException e) { // errorMessage("run", e); e.printStackTrace(); thread = null; } try { Thread.sleep(8); } catch (InterruptedException ex) { } } }
/** * Creates a SAX XMLReader. * * @return <code>XMLReader</code> a SAX2 parser. * @throws Exception if no parser can be created. */ protected XMLReader createParser() throws Exception { XMLReader parser = null; // Try using JAXP... // Note we need JAXP 1.1, and if JAXP 1.0 is all that's // available then the getXMLReader call fails and we skip // to the hard coded default parser try { Class factoryClass = Class.forName("javax.xml.parsers.SAXParserFactory"); // MODIFIED: Added (Class[]) and (Object[]) cast sentences in "null" parameters // to avoid warnings during compilation // factory = SAXParserFactory.newInstance(); Method newParserInstance = factoryClass.getMethod("newInstance", (Class[]) null); Object factory = newParserInstance.invoke(null, (Object[]) null); // jaxpParser = factory.newSAXParser(); Method newSAXParser = factoryClass.getMethod("newSAXParser", (Class[]) null); Object jaxpParser = newSAXParser.invoke(factory, (Object[]) null); // parser = jaxpParser.getXMLReader(); Class parserClass = jaxpParser.getClass(); Method getXMLReader = parserClass.getMethod("getXMLReader", (Class[]) null); parser = (XMLReader) getXMLReader.invoke(jaxpParser, (Object[]) null); } catch (ClassNotFoundException e) { // e.printStackTrace(); } catch (InvocationTargetException e) { // e.printStackTrace(); } catch (NoSuchMethodException e) { // e.printStackTrace(); } catch (IllegalAccessException e) { // e.printStackTrace(); } // Check to see if we got a parser yet, if not, try to use a // hard coded default if (parser == null) { parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); } return parser; }
// // Examine a single method to see if it raises SQLFeatureNotSupportedException. // private void vetMethod( Object candidate, Class iface, Method method, HashSet<String> unsupportedList, HashSet<String> notUnderstoodList) throws Exception { try { method.invoke(candidate, getNullArguments(method.getParameterTypes())); // it's ok for the method to succeed } catch (Throwable e) { if (!(e instanceof InvocationTargetException)) { recordUnexpectedError(candidate, iface, method, notUnderstoodList, e); } else { Throwable cause = e.getCause(); if (cause instanceof SQLFeatureNotSupportedException) { boolean isExcludable = isExcludable(method); if (!isExcludable) { StackTraceElement[] stack = cause.getStackTrace(); int i = 0; while (i < stack.length && !stack[i].getMethodName().equals("notImplemented")) { ++i; } while (i < stack.length && stack[i].getMethodName().equals("notImplemented")) { ++i; } if (i == stack.length) { // cause.printStackTrace(); } unsupportedList.add( candidate.getClass().getName() + ": " + method + "@" + (i == stack.length ? "no source" : cause.getStackTrace()[i])); } else { } } else if (cause instanceof SQLException) { // swallow other SQLExceptions, caused by bogus args } else if (cause instanceof NullPointerException) { // swallow other NPEs, caused by bogus args } else if (cause instanceof ArrayIndexOutOfBoundsException) { // swallow these, caused by bogus args } else { recordUnexpectedError(candidate, iface, method, notUnderstoodList, cause); } } } }
/** event driven processing methods */ public void hPubStartPerformed(HPubStartEvent evt) { if (tracing == true) { traceArgs[0] = this; traceArgs[1] = "CrownCounselIndexGetList_Access.hPubStartPerformed()"; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } Thread newThread = new Thread(this); newThread.start(); }
/** * This function instantiates an invariant class by using the <type>(PptSlice) constructor. * * @param theClass the invariant class to be instantiated * @param sl the PptSlice representing the variables about which an invariant is determined * @return an instance of the class in theClass if one can be constructed, else throw a * RuntimeException */ private static Invariant instantiateClass(Class<? extends Invariant> theClass, PptSlice sl) { try { Method get_proto = theClass.getMethod("get_proto", new Class<?>[] {}); Invariant proto = (/*@Prototype*/ Invariant) get_proto.invoke(null, new Object[] {}); Invariant inv = proto.instantiate(sl); return (inv); } catch (Exception e) { e.printStackTrace(System.out); throw new RuntimeException( "Error while instantiating invariant " + theClass.getName() + ": " + e.toString()); } }