Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 51 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
51
Dung lượng
444,06 KB
Nội dung
System.out.println (sqlex); } } } Java DB version 10.2.1.7 does not support the SQL XML data type. 8. The purpose of dblook’s -z option is to limit DDL generation to a specific schema; only those database objects that belong to the schema will have their DDL state- ments generated. The purpose of dblook’s -t option is to limit table-related DDL generation to those tables identified by this option. The purpose of dblook’s -td option is to specify the DDL statement terminator (which is the semicolon charac- ter by default). 9. Listing D-10 presents a DumpSchemas application that takes a single command-line argument, the JDBC URL to a data source, and dumps the names of its schemas to the standard output. Listing D-10. DumpSchemas.java // DumpSchemas.java import java.sql.*; public class DumpSchemas { public static void main (String [] args) { if (args.length != 1) { System.err.println ("usage: java DumpSchemas jdbcURL"); return; } try { Connection con; con = DriverManager.getConnection (args [0]); APPENDIX D ■ TEST YOUR UNDERSTANDING ANSWERS436 830-X XD.qxd 9/24/07 8:25 PM Page 436 DatabaseMetaData dbmd = con.getMetaData (); ResultSet rs = dbmd.getSchemas (); while (rs.next ()) System.out.println (rs.getString (1)); if (con.getMetaData ().getDriverName ().equals ("Apache Derby "+ "Embedded JDBC Driver")) try { DriverManager.getConnection ("jdbc:derby:;shutdown=true"); } catch (SQLException sqlex) { System.out.println ("Database shut down normally"); } } catch (SQLException sqlex) { System.out.println (sqlex); } } } When you run this application against the EMPLOYEE database, the following schemas are identified: APP NULLID SQLJ SYS SYSCAT SYSCS_DIAG SYSCS_UTIL SYSFUN SYSIBM SYSPROC SYSSTAT APPENDIX D ■ TEST YOUR UNDERSTANDING ANSWERS 437 830-X XD.qxd 9/24/07 8:25 PM Page 437 Chapter 7: Monitoring and Management 1. Local monitoring refers to running JConsole (or any JMX client) on the same machine as the application being monitored. Both the application and JConsole must belong to the same user. You do not need to specify the com.sun.management. jmxremote system property when starting an application to be locally monitored under Java SE 6. 2. According to the JDK documentation for Class’s protected final Class<?> defineClass(String name, byte[] b, int off, int len) method, class definition involves converting an array of bytes into an instance of class Class. In contrast, transformation involves changing the definition in some way, such as instrument- ing the class through the addition of bytecodes to various methods. Redefinition does not cause a class’s initializers to run. The retransform() method identifies these steps for retransformation: • Begin with the initial class-file bytes. • For each transformer added via void addTransformer(ClassFileTransformer transformer), or void addTransformer(ClassFileTransformer transformer, boolean canRetransform) where false is passed to canRetransform, the bytes returned by the transform() method during the last class load or redefinition are reused as the output of the transformation. • For each transformer that was added with true passed to canRetransform, the transform() method is called in these transformers. • The transformed class-file bytes are installed as the new definition of the class. 3. The agentmain() method is often (but not necessarily) invoked after an applica- tion’s main() method has run. In contrast, premain() is always invoked before main() runs. Also, agentmain() is invoked as a result of dynamic attach, whereas premain() is invoked as a result of starting the virtual machine with the -javaagent option, which specifies an agent JAR file’s path and name. 4. Listing D-11 presents a LoadAverageViewer application that invokes OperatingSystemMXBean’s getSystemLoadAverage() method. If this method returns a negative value, the application outputs a message stating that the load average is not supported on this platform. Otherwise, it repeatedly outputs the load average once per minute, for a specific number of minutes as determined by a command- line argument. APPENDIX D ■ TEST YOUR UNDERSTANDING ANSWERS438 830-X XD.qxd 9/24/07 8:25 PM Page 438 Listing D-11. LoadAverageViewer.java // LoadAverageViewer.java; // Unix compile : javac -cp $JAVA_HOME/lib/tools.jar LoadAverageViewer.java // // Windows compile: javac -cp %JAVA_HOME%/lib/tools.jar LoadAverageViewer.java import static java.lang.management.ManagementFactory.*; import java.lang.management.*; import java.io.*; import java.util.*; import javax.management.*; import javax.management.remote.*; import com.sun.tools.attach.*; public class LoadAverageViewer { static final String CON_ADDR = "com.sun.management.jmxremote.localConnectorAddress"; static final int MIN_MINUTES = 2; static final int MAX_MINUTES = 10; public static void main (String [] args) throws Exception { int minutes = MIN_MINUTES; if (args.length != 2) { System.err.println ("Unix usage : "+ "java -cp $JAVA_HOME/lib/tools.jar:. "+ "LoadAverageViewer pid minutes"); System.err.println (); System.err.println ("Windows usage: "+ "java -cp %JAVA_HOME%/lib/tools.jar;. "+ "LoadAverageViewer pid minutes"); APPENDIX D ■ TEST YOUR UNDERSTANDING ANSWERS 439 830-X XD.qxd 9/24/07 8:25 PM Page 439 return; } try { int min = Integer.parseInt (args [1]); if (min < MIN_MINUTES || min > MAX_MINUTES) { System.err.println (min+" out of range ["+MIN_MINUTES+", "+ MAX_MINUTES+"]"); return; } minutes = min; } catch (NumberFormatException nfe) { System.err.println ("Unable to parse "+args [1]+" as an integer."); System.err.println ("LoadAverageViewer will repeatedly check "+ " average (if available) every minute for "+ MIN_MINUTES+" minutes."); } // Attempt to attach to the target virtual machine whose identifier is // specified as a command-line argument. VirtualMachine vm = VirtualMachine.attach (args [0]); // Attempt to obtain the target virtual machine's connector address so // that this virtual machine can communicate with its connector server. String conAddr = vm.getAgentProperties ().getProperty (CON_ADDR); // If there is no connector address, a connector server and JMX agent // are not started in the target virtual machine. Therefore, load the // JMX agent into the target. if (conAddr == null) { // The JMX agent is stored in management-agent.jar. This JAR file // is located in the lib subdirectory of the JRE's home directory. String agent = vm.getSystemProperties () APPENDIX D ■ TEST YOUR UNDERSTANDING ANSWERS440 830-X XD.qxd 9/24/07 8:25 PM Page 440 .getProperty ("java.home")+File.separator+ "lib"+File.separator+"management-agent.jar"; // Attempt to load the JMX agent. vm.loadAgent (agent); // Once again, attempt to obtain the target virtual machine's // connector address. conAddr = vm.getAgentProperties ().getProperty (CON_ADDR); // Although the second attempt to obtain the connector address // should succeed, throw an exception if it does not. if (conAddr == null) throw new NullPointerException ("conAddr is null"); } // Prior to connecting to the target virtual machine's connector // server, the String-based connector address must be converted into a // JMXServiceURL. JMXServiceURL servURL = new JMXServiceURL (conAddr); // Attempt to create a connector client that is connected to the // connector server located at the specified URL. JMXConnector con = JMXConnectorFactory.connect (servURL); // Attempt to obtain an MBeanServerConnection that represents the // remote JMX agent's MBean server. MBeanServerConnection mbsc = con.getMBeanServerConnection (); // Obtain object name for thread MBean, and use this name to obtain the // name of the OS MBean that is controlled by the JMX agent's MBean // server. ObjectName osName = new ObjectName (OPERATING_SYSTEM_MXBEAN_NAME); Set<ObjectName> mbeans = mbsc.queryNames (osName, null); APPENDIX D ■ TEST YOUR UNDERSTANDING ANSWERS 441 830-X XD.qxd 9/24/07 8:25 PM Page 441 // The for-each loop conveniently returns the name of the OS MBean. // There should only be one iteration because there is only one OS // MBean. for (ObjectName name: mbeans) { // Obtain a proxy for the OperatingSystemMXBean interface that // forwards its method calls through the MBeanServerConnection // identified by mbsc. OperatingSystemMXBean osb; osb = newPlatformMXBeanProxy (mbsc, name.toString (), OperatingSystemMXBean.class); double loadAverage = osb.getSystemLoadAverage (); if (loadAverage < 0) { System.out.println (loadAverage); System.out.println ("Load average not supported on platform"); return; } for (int i = 0; i < minutes; i++) { System.out.printf ("Load average: %f", loadAverage); System.out.println (); try { Thread.sleep (60000); // Sleep for about one minute. } catch (InterruptedException ie) { } loadAverage = osb.getSystemLoadAverage (); } break; } } } APPENDIX D ■ TEST YOUR UNDERSTANDING ANSWERS442 830-X XD.qxd 9/24/07 8:25 PM Page 442 5. The purpose of the JConsole API’s JConsoleContext interface is to represent a JConsole connection to an application running in a target virtual machine. 6. The java.beans.PropertyChangeListener is added to a plug-in’s JConsoleContext via JConsolePlugin’s public final void addContextPropertyChangeListener (PropertyChangeListener listener) method, or via a call to JConsolePlugin’s public final JConsoleContext getContext() method followed by a call to JConsoleContext’s void addPropertyChangeListener(PropertyChangeListener listener) method (assuming that getContext() does not return null). It is invoked when the connection state between JConsole and a target virtual machine changes. The JConsoleContext.ConnectionState enumeration’s CONNECTED, CONNECTING, and DISCONNECTED constants identify the three connection states. This listener benefits a plug-in by providing a convenient place to obtain a new javax.management.MBeanServerConnection via JConsoleContext’s MBeanServerConnection getMBeanServerConnection() method when the connection state becomes CONNECTED. The current MBeanServerConnection becomes invalid when the connection is disconnected. The sample JTop plug-in’s jtopplugin. java source code (included in the JDK) shows how to implement PropertyChangeListener’s void propertyChange(PropertyChangeEvent evt) method to restore the MBeanServerConnection. Chapter 8: Networking 1. If you placed new URL (args [0]).openConnection ().getContent (); before CookieManager cm = new CookieManager (); in Listing 8-1, you would observe no cookie output. The HTTP protocol handler requires an implementation (the cookie manager, for example) of a system-wide cookie handler to be present before it executes. This is because the protocol handler invokes the system- wide cookie handler’s public void put(URI uri, Map<String,List<String>> responseHeaders) method to store response cookies in a cookie cache. It cannot invoke this method to accomplish this task if a cookie handler implementation has not been installed. 2. IDN’s toASCII() methods throw IllegalArgumentException if their input strings do not conform to RFC 3490. APPENDIX D ■ TEST YOUR UNDERSTANDING ANSWERS 443 830-X XD.qxd 9/24/07 8:25 PM Page 443 3. The following excerpt from the revised MinimalHTTPServer application (see Listing 8-4 for the original application’s source code) introduces a DateHandler class associ- ated with the /date root URI. In addition to this excerpt, you need to add a server.createContext ("/date", new DateHandler ()); method call in the main() method. class DateHandler implements HttpHandler { public void handle (HttpExchange xchg) throws IOException { xchg.sendResponseHeaders (200, 0); OutputStream os = xchg.getResponseBody (); DataOutputStream dos = new DataOutputStream (os); dos.writeBytes ("<html><head></head><body><center><b>"+ new Date ().toString ()+"</b></center></body></html>"); dos.close (); } } 4. The following excerpt from the revised NetParms application (see Listing 8-5 for the original application’s source code) obtains all accessible InterfaceAddresses for each network interface, and outputs each InterfaceAddress’s IP address, broadcast address, and network prefix length/subnet mask: List<InterfaceAddress> ias = ni.getInterfaceAddresses (); for (InterfaceAddress ia: ias) { // Because it is possible for getInterfaceAddresses() to // return a list consisting of a single null element I // found this to be the case for a WAN (PPP/SLIP) interface // an if statement test is needed to prevent a // NullPointerException. if (ia == null) break; System.out.println ("Interface Address"); System.out.println (" Address: "+ia.getAddress ()); System.out.println (" Broadcast: "+ia.getBroadcast ()); System.out.println (" Prefix length/Subnet mask: "+ ia.getNetworkPrefixLength ()); } APPENDIX D ■ TEST YOUR UNDERSTANDING ANSWERS444 830-X XD.qxd 9/24/07 8:25 PM Page 444 Chapter 9: Scripting 1. The name of the package assigned to the Scripting API is javax.script. 2. The Compilable interface describes a script engine that lets scripts be compiled to intermediate code. The CompiledScript abstract class is extended by subclasses that store the results of compilations—the intermediate code, as it were. 3. The scripting language associated with Java SE 6’s Rhino-based script engine is JavaScript. 4. ScriptEngineFactory’s getEngineName() method returns an engine’s full name (such as Mozilla Rhino). ScriptEngineFactory’s getNames() method returns a list of engine short names (such as rhino). You can pass any short name to ScriptEngineManager’s getEngineByName(String shortName) method. 5. For a script engine to exhibit the MULTITHREADED threading behavior, scripts can execute concurrently on different threads, although the effects of executing a script on one thread might be visible to threads executing on other threads. 6. ScriptEngineManager’s getEngineByExtension(String extension) method would be appropriate for obtaining a script engine after selecting the name of a script file via a dialog box. 7. ScriptEngine offers six eval() methods for evaluating scripts. 8. The Rhino-based script engine does not import the java.lang package by default to prevent conflicts with same-named JavaScript types— Object, Math, Boolean, and so on. 9. The problem with importPackage() and importClass() is that they pollute JavaScript’s global variable scope. Rhino overcomes this problem by providing a JavaImporter class that works with JavaScript’s with statement to let you specify classes and interfaces without their package names from within this statement’s scope. 10. A Java program communicates with a script by passing objects to the script via script variables, and by obtaining script variable values as objects. ScriptEngine provides void put(String key, Object value) and Object get(String key) methods for these tasks. APPENDIX D ■ TEST YOUR UNDERSTANDING ANSWERS 445 830-X XD.qxd 9/24/07 8:25 PM Page 445 [...]... Microsystems presents a new generation of the Java platform to the Java community See the J 2SE Code Names page (http:/ /java. sun.com/ j 2se/ codenames.html) for a list of official Java release dates You can add a Java SE 6/ Mustang/Dec 11, 20 06 entry to this list If Sun adheres to this pattern, the official release of the next generation, Java SE 7 (I assume that Sun will use this name; Java SE 7 is currently... arguments 16 The tool used to generate web service artifacts needed to deploy a web service is wsgen 17 The tool used to generate web service artifacts needed to import a web service to client programs is wsimport 18 Listing D-13 presents a revised SkyView application (shown in Listing 10- 8) whose use of SwingWorker ensures that the GUI is still responsive whenever byte [] image = Imgcutoutsoap.getJpeg... DeflaterInputStream, 26 Desktop action methods, 81–87 browse() method, 81 exceptions thrown, 82 getDesktop() method, 80 DiagnosticCollector, 45– 46 DriverManager, 188 File file-access permissions methods, 54– 56 partition-space methods, 52–53 HTTPContext, 265 httpserver package, 264 HTTPServer, 265 IDN, 258 InflaterInputStream, 26 InterfaceAddress, 269 java. text.spi package, 160 – 162 java. util package, 57 63 java. util.concurrent... currently being referred to as Dolphin) should occur in mid -to- late 2008 Work began on Java SE 7 before Java SE 6 s official release Danny Coward, the platform lead for Java SE, identifies a variety of features planned for Java SE 7 in his “What’s coming in Java SE 7” document (http://blogs.sun.com/dannycoward/resource/ Java7 Overview_Prague_JUG.pdf) and in his “Channeling Java SE 7” blog entry (http://blogs... Application.vendorId 465 830-X XE.qxd 466 10/ 1/07 8:37 PM Page 466 APPENDIX E ■ A PREVIEW OF JAVA SE 7 On my Windows XP platform, for example, the c:\Documents and Settings\ Jeff Friesen\Application Data\Jeff Friesen\WhoIs directory stores the WhoIs application’s mainFrame.session.xml file The Application.id and Application.vendorId values are responsible for the final Jeff Friesen\WhoIs portion of the directory path... ImgCutoutSoap imgcutoutsoap; double ra, dec, scale; String dopt; JLabel lblImage; public SkyView () { super ("SkyView"); setDefaultCloseOperation (EXIT_ON_CLOSE); setContentPane (createContentPane ()); pack (); setResizable (false); setVisible (true); } JPanel createContentPane () { JPanel pane = new JPanel (new BorderLayout (10, 10) ); pane.setBorder (BorderFactory.createEmptyBorder (10, 10, 10, 10) );... blog entry (http://blogs sun.com/dannycoward/entry/channeling _java_ se_ 7) This appendix discusses several features that are most likely to be part of Java SE 7 ■ Caution Because Java SE 7 is a work in progress, some of the features discussed in this appendix may differ from those in the final release, or may not even be present Closures Java 5 is largely remembered for introducing generics and other... support for, 91 overview of, 79 Solaris and, 117 Splash Screen API customizing, 99 102 splash window, creating, 98 System Tray API quick launch from system tray, 110 1 16 SystemTray class, 103 105 TrayIcon class, 1 06 110 accents, removing, 169 –171 accessing existing web services, 371–3 76 JRuby from Java program, 333 action keys, 6 11 adapter pattern support and JDBC 4.0 API, 202–204 addStatementEventListener()... input, support for, 91 overview of, 79 Solaris and, 117 469 830-X Index.qxd 470 10/ 3/07 4: 36 PM Page 470 ■INDEX Splash Screen API customizing, 99 102 splash window, creating, 98 System Tray API quick launch from system tray, 110 1 16 SystemTray class, 103 105 TrayIcon class, 1 06 110 B background thread, 139 bankers’ rounding, 19 base64 algorithm, 352 BaselineResizeBehavior enumeration, 14 basic agent application,... (http://weblogs .java. net/blog/emcmanus/archive/2007/05/custom_types_fo.html) In addition to JSR 255, Eamonn is the lead on JSR 262 : Web Services Connector for Java Management Extensions (JMX) Agents (http://jcp.org/en/jsr/detail?id= 262 ) This JSR seeks to define a JMX Remote API connector for making JMX instrumentation available to remote Java and non -Java clients via web services For more information about JSR 262 , . the web service’s address URI and an instance of the web service class as arguments. 16. The tool used to generate web service artifacts needed to deploy a web service is wsgen. 17. The tool used to. Prior to connecting to the target virtual machine's connector // server, the String-based connector address must be converted into a // JMXServiceURL. JMXServiceURL servURL = new JMXServiceURL. Preview of Java SE 7 Approximately every two years, Sun Microsystems presents a new generation of the Java platform to the Java community. See the J 2SE Code Names page ( http:/ /java. sun.com/ j 2se/ codenames.html)