Philly Java Users Group Whats new in Whats new in Java 2 Standard - - PowerPoint PPT Presentation
Philly Java Users Group Whats new in Whats new in Java 2 Standard - - PowerPoint PPT Presentation
Philly Java Users Group Whats new in Whats new in Java 2 Standard Edition 1.4 Java 2 Standard Edition 1.4 Kirk k B. Spadt padt ki kirk@ k@spadt spadt.com com Java 2 Standard Edition 1.4 Java 2 Standard Edition 1.4
Java 2 Standard Edition 1.4 Java 2 Standard Edition 1.4
- Availability: F
Availability: February 13, 2002 ebruary 13, 2002
- Size: Over 11,000 classes (API’s + impl)
Size: Over 11,000 classes (API’s + impl)
- Changes: 33%
Changes: 33% new or changed methods new or changed methods
- Performance: Major enhancements
Performance: Major enhancements
- Functionality: Enterprise connectivity
unctionality: Enterprise connectivity
- Scalability: 64-bit core support
Scalability: 64-bit core support
- Ease of programming: More API’s
Ease of programming: More API’s
- Ease of use: Drag/drop, wheel, install
Ease of use: Drag/drop, wheel, install
- Compatibility with earlier releases
Compatibility with earlier releases
Perform Performance Enhancem ance Enhancements ents
- 50-100%
50-100% I/O improvement I/O improvement
- 10x Reflection performance increase
10x Reflection performance increase
- Garbage collection - concurrent (MP)
Garbage collection - concurrent (MP)
- 30%
30% Swing improvement (pipeline) Swing improvement (pipeline)
- Hardware acceleration (DirectDraw)
Hardware acceleration (DirectDraw)
- 20%
20% reduction in RAM footprint reduction in RAM footprint
- 20%
20% reduction in startup time reduction in startup time
API’s M API’s Moved into J2SE v1.4
- ved into J2SE v1.4
- JAXP: Java API for XML Processing
JAXP: Java API for XML Processing
- JDBC-2, 2.1 and JDBC 3.0
JDBC-2, 2.1 and JDBC 3.0
- CORBA enhancements
CORBA enhancements
- DNS Service Provider for JNDI
DNS Service Provider for JNDI
- JCE: Java Cryptography Extensions
JCE: Java Cryptography Extensions
- JSSE: Java Secure Socket Extension
JSSE: Java Secure Socket Extension
- JAAS: Java Authentication/Authorization
JAAS: Java Authentication/Authorization
- GSS-API: Kerberos Single sign-on
GSS-API: Kerberos Single sign-on
New Functions New Functions
- Assertions
Assertions
- Regular expressions
Regular expressions
- New I/O API
New I/O API
- Printing API
Printing API
- Logging API
Logging API
- Preferences API
Preferences API
- XML Persistence
XML Persistence
- Fast 2D Graphics
ast 2D Graphics
- Redesigned focus
Redesigned focus
- Swing drag-n-drop
Swing drag-n-drop
- Java Web Start
Java Web Start
Code Disclaim Code Disclaimer er
- Subsequent sections include a
Subsequent sections include a sample sample pro program gram to illustrate use to illustrate use of the new
- f the new
classes. classes.
- Written to be BRIEF
Written to be BRIEF (single slide) (single slide) The code works…, but… he code works…, but… Ignores exceptions Ignores exceptions Breaks MVC & some accepted practices Breaks MVC & some accepted practices
- Code is AS
Code is AS-IS IS, and , and use in nuclear facilities use in nuclear facilities
- r life-support applications is prohibited.
- r life-support applications is prohibited.
Assertions Assertions
- Tests a condition you “know” is true
ests a condition you “know” is true Confirms programmer assumptions Confirms programmer assumptions Improves program reliability Improves program reliability
- assert: New Java language keyword
: New Java language keyword
javac –source 1.4 Foo.java
to compile to compile
java –ea Foo to run
to run
- throws an AssertionError
throws an AssertionError java.lang.Error subclass (unchecked) java.lang.Error subclass (unchecked)
package com.spadt.jdk14; /** * Demonstrates the use of the assert keyword. */ public class Assert { public static void countChars(String s) { assert s != null : "string cannot be null"; System.out.println("String [" + s + "] has " + s.length() + " chars."); } public static void main(String[] args) { countChars("valid string"); countChars(null); } }
Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release 1.4, assert is a keyword, and may not be used as an identifier assert s != null : "string cannot be null"; ^ com\spadt\jdk14\Assert.java:7: ';' expected assert s != null : "string cannot be null"; ^ com\spadt\jdk14\Assert.java:7: cannot resolve symbol symbol : class assert location: class com.spadt.jdk14.Assert assert s != null : "string cannot be null"; ^ com\spadt\jdk14\Assert.java:7: s is already defined in countChars(java.lang.String) assert s != null : "string cannot be null"; ^ Compiling: Assertions enabled
Running: Assertions disabled >java com.spadt.jdk14.Assert String [valid string] has 12 chars. Exception in thread "main" java.lang.NullPointerException at com.spadt.jdk14.Assert.countChars(Assert.java:8) at com.spadt.jdk14.Assert.main(Assert.java:13) Running: Assertions enabled >java -ea com.spadt.jdk14.Assert String [valid string] has 12 chars. Exception in thread "main" java.lang.AssertionError: string is null at com.spadt.jdk14.Assert.countChars(Assert.java:7) at com.spadt.jdk14.Assert.main(Assert.java:13)
Assertions Strategy Assertions Strategy
- YES: Programmer errors or omissions
YES: Programmer errors or omissions if() … else if() … else assert if() … else if() … else assert switch(x) … case 1: … default: assert switch(x) … case 1: … default: assert verifying ownership of object locks verifying ownership of object locks how could I ever get here? how could I ever get here?
- NO: User, system, or configuration errors
NO: User, system, or configuration errors User entry errors – detailed message User entry errors – detailed message SQL, Remote, etc errors – log them SQL, Remote, etc errors – log them Config errors – log for deployers Config errors – log for deployers
Regular Expressions Regular Expressions
- Powerful tools to match and process text.
Powerful tools to match and process text.
- Familiar to unix shell and perl programmers
amiliar to unix shell and perl programmers
- Matching, extraction, and substitution
Matching, extraction, and substitution
- Examples for matches:
Examples for matches: “[0-9]+” – matches one or more digits [0-9]+” – matches one or more digits “dog|cat” – matches either “dog” or “cat” dog|cat” – matches either “dog” or “cat” (.* (.*)\r?\n” – the (.* )\r?\n” – the (.*) matches a text line ) matches a text line “[a-zA-Z [a-zA-Z][a-zA-Z ][a-zA-Z_0-9]* _0-9]*” – a java name ” – a java name
Regular Expression Classes Regular Expression Classes
- java.util.regex: New
ew package package
- Pat
atter ern n cl class: ass: speci specify y a a regul egular ar expr expressi ession
- n
mat atches( ches(): an an easy easy test est for
- r a
a mat atch ch spl split(): br breaks eaks a a st string ng usi using ng del delimiter ers Com
- mpi
pile( e(): Par arse se expr expr ahead ahead - per perfor
- rmance
ance
- Mat
atche cher class: s: mat atch ch and nd par arse se text ext usi using ng the he regul egular ar expr expressi ession
- n
mat atches( ches(): a a fast ast test est for
- r a
a mat atch ch find( nd(): test ests s if text ext cont contai ains ns pat patter ern st star art(), end( end() – – indexes ndexes of
- f mat
atch ch gr group(
- up() –
– a a st string ng or
- r subst
substring ng that hat mat atched ched
package com.spadt.jdk14; import java.io.*; import java.util.regex.*; /** Cool stuff to do with java.util.Regex */ public class RegexTricks { public static void main(String[] args) throws IOException { String info = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); Pattern emailPattern = Pattern.compile("(.+)@(.+\\.(com|net|org))"); Matcher em = emailPattern.matcher(""); while((info = in.readLine()).length() > 0) { if(Pattern.matches("[0-9]*", info)) { System.out.println("Number=" + info); } else if(em.reset(info).matches()) { System.out.println("User=" + em.group(1) + ", host=" + em.group(2) + ", a dot-" + em.group(3)); } else { String[] parts = Pattern.compile("[.,]").split(info); for(int i = 0; i < parts.length; i++) System.out.println("Part " + i + "=" + parts[i]); } } }
from public class RegexTricks Pattern emailPattern = Pattern.compile("(.+)@(.+\\.(com|net|org))"); Matcher em = emailPattern.matcher(""); while((info = in.readLine()).length() > 0) { if(Pattern.matches("[0-9]*", info)) { System.out.println("Number=" + info); } else if(em.reset(info).matches()) { System.out.println("User=" + em.group(1) + ", host=" + em.group(2) + ", a dot-" + em.group(3)); } else { String[] parts = Pattern.compile("[.,]").split(info); for(int i = 0; i < parts.length; i++)
New I/O (NIO) API New I/O (NIO) API
- Ultra-scalable high-performance server apps
Ultra-scalable high-performance server apps
- Access to large quantities of data
Access to large quantities of data
- New F
New File I/O ile I/O Read/write/transfer twice as fast Read/write/transfer twice as fast Concurrent read/write operations Concurrent read/write operations Supports file locking Supports file locking Memory-mapped file I/O Memory-mapped file I/O
- New Network I/O
New Network I/O Far more simultaneous connections ar more simultaneous connections Multiple connections per thread Multiple connections per thread
New File I/O New File I/O
- Buffer: contains sequences of primitive types
Buffer: contains sequences of primitive types Int.. Byte.. Char.. Double.. other primitives Int.. Byte.. Char.. Double.. other primitives Bulk data transfer to buffers and arrays Bulk data transfer to buffers and arrays
- Channel: primitive connection to device
Channel: primitive connection to device
- FileChannel: map() - memory-maps files
ileChannel: map() - memory-maps files lock(position, size, shared) – blocking lock(position, size, shared) – blocking tryLock() – nonblocking tryLock() – nonblocking Read/write to arrays of buffers Read/write to arrays of buffers Bulk data transfer between channels Bulk data transfer between channels force() – guarantees I/O write to device force() – guarantees I/O write to device
package com.spadt.jdk14; import java.io.*; import java.nio.*; import java.nio.channels.*; /** Simple checksum of a list of files using new java.nio packages */ public class Checksum { public static void main(String[] args) { for(int i = 0; i < args.length; i++) { try { File File = new File(args[i]); FileInputStream is = new FileInputStream(File); FileChannel fc = is.getChannel(); long size = fc.size(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, size); int checksum = 0; while(bb.hasRemaining()) { checksum = (checksum * 31) ^ bb.get(); } System.out.println(File.getName() + ": " + checksum); fc.close(); } catch(Exception e) { e.printStackTrace(System.out); } }
from public class Checksum for(int i = 0; i < args.length; i++) { try { File File = new File(args[i]); FileInputStream is = new FileInputStream(File); FileChannel fc = is.getChannel(); long size = fc.size(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, size); int checksum = 0; while(bb.hasRemaining()) { checksum = (checksum * 31) ^ bb.get(); } System.out.println(File.getName() + ": " + checksum); fc.close(); } catch(Exception e) { }
New Network I/O New Network I/O
- IPv6: e.g. 1080:0:0:0:8:800:200C:417A
IPv6: e.g. 1080:0:0:0:8:800:200C:417A
- SocketChannel: Non-blocking option
SocketChannel: Non-blocking option Connect() and finishConnect() Connect() and finishConnect() Datagram- and ServerSocket- Channel Datagram- and ServerSocket- Channel
- Selector: A channel multiplexor
Selector: A channel multiplexor channel.register(selector) – notification channel.register(selector) – notification select(): blocks until channel activity, select(): blocks until channel activity, wakeup(), timeout, thread interrupt wakeup(), timeout, thread interrupt selectedKeys(): channels with pending I/O selectedKeys(): channels with pending I/O Enables multiple channels per thread Enables multiple channels per thread
package com.spadt.jdk14; import java.util.Iterator; import java.io.IOException; import java.net.*; import java.nio.*; import java.nio.channels.*; /** Multiplexed connections: Timing of www port opening */ public class Connect { static String[] urls = { "www.ibm.com", "www.microsoft.com", "www.sun.com"}; static Site[] sites = new Site[urls.length]; static Selector sel; static long startTime = 0; static class Site { String msg = "Timeout"; InetSocketAddress addr; SocketChannel chan; long time; Site(String url) throws UnknownHostException { addr = new InetSocketAddress( InetAddress.getByName(url), 80); } } public static void main(String[] args) throws IOException, UnknownHostException { for(int i = 0; i < urls.length; i++) sites[i] = new Site(urls[i]); sel = Selector.open(); for(int i = 0; i < urls.length; i++) { sites[i].chan = SocketChannel.open(); sites[i].chan.configureBlocking(false); sites[i].chan.connect(sites[i].addr); sites[i].chan.register(sel, SelectionKey.OP_CONNECT | SelectionKey.OP_READ, sites[i]); sites[i].time = System.currentTimeMillis(); } while(sel.select(2000) > 0) { Iterator iter = sel.selectedKeys().iterator(); while(iter.hasNext()) { SelectionKey key = (SelectionKey) iter.next(); iter.remove(); Site site = (Site) key.attachment();
Multiplexed connections: Inner class - Site public class Connect { static String[] urls = { "www.ibm.com", "www.microsoft.com", "www.sun.com"}; static Site[] sites = new Site[urls.length]; static Selector sel; static long startTime = 0; static class Site { String msg = "Timeout"; InetSocketAddress addr; SocketChannel chan; long time; Site(String url) throws UnknownHostException { addr = new InetSocketAddress( InetAddress.getByName(url), 80); } }
Multiplexed connections: Initializing Selector public static void main(String[] args) throws IOException, UnknownHostException { for(int i = 0; i < urls.length; i++) sites[i] = new Site(urls[i]); sel = Selector.open(); for(int i = 0; i < urls.length; i++) { sites[i].chan = SocketChannel.open(); sites[i].chan.configureBlocking(false); sites[i].chan.connect(sites[i].addr); sites[i].chan.register(sel, SelectionKey.OP_CONNECT | SelectionKey.OP_READ, sites[i]); sites[i].time = System.currentTimeMillis(); } . . .
Multiplexed connections: Processing Selector while(sel.select(2000) > 0) { Iterator iter = sel.selectedKeys().iterator(); while(iter.hasNext()) { SelectionKey key = (SelectionKey) iter.next(); iter.remove(); Site site = (Site) key.attachment(); if(site.chan.finishConnect()) { key.cancel(); site.msg = "time: " + (System.currentTimeMillis()
- site.time);
site.chan.close(); } } } for(int i = 0; i < sites.length; i++) System.out.println(sites[i].addr.getHostName() + " - " + sites[i].msg); }
New I/O Strategy New I/O Strategy
- Server development: “Must do”
Server development: “Must do” Far more scalable – not thread-limited ar more scalable – not thread-limited 50 – 100% 50 – 100% performance improvement performance improvement App servers – will be done for us App servers – will be done for us
- Client development: New development
Client development: New development Large and composite file processing Large and composite file processing Entire file, e.g. DOM XML, images, models Entire file, e.g. DOM XML, images, models
- Retrofit: Only as dictated by needs
Retrofit: Only as dictated by needs Application performance / profiling Application performance / profiling
Java Print Service Java Print Service
- Discovery and selection of available printers
Discovery and selection of available printers PrintServiceLookup PrintServiceLookup Selection based on capabilities / properties Selection based on capabilities / properties
- DocF
DocFlavor – specifies destination and format lavor – specifies destination and format Stream, reader, byte array, URL Stream, reader, byte array, URL Format: MIME type constants
- rmat: MIME type constants
- Doc object: request attributes and print data
Doc object: request attributes and print data
- DocPrintJob: submits document to printer
DocPrintJob: submits document to printer
- Pluggable print services using spi
Pluggable print services using spi
package com.spadt.jdk14; import java.io.*; import javax.print.*; import javax.print.attribute.*; import javax.print.attribute.standard.*; public class FilePrint { public static void main(String[] args) throws IOException, PrintException { FileInputStream is = new FileInputStream("c:/tmp/p.xml"); DocFlavor flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_US_ASCII; Doc doc = new SimpleDoc(is, flavor, null); PrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet(); attrs.add(new Copies(2)); attrs.add(MediaSize.NA.LETTER); PrintService[] printers = PrintServiceLookup .lookupPrintServices(flavor, attrs); if(printers.length > 0) { DocPrintJob job = printers[0].createPrintJob(); job.print(doc, attrs); } else
FileInputStream is = new FileInputStream("c:/tmp/p.xml"); DocFlavor flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_US_ASCII; Doc doc = new SimpleDoc(is, flavor, null); PrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet(); attrs.add(new Copies(2)); attrs.add(MediaSize.NA.LETTER); PrintService[] printers = PrintServiceLookup .lookupPrintServices(flavor, attrs); if(printers.length > 0) { DocPrintJob job = printers[0].createPrintJob(); job.print(doc, attrs); } else System.out.println("No printers can print this job");
Logging API Logging API
- Facilitates analysis, application error reporting
acilitates analysis, application error reporting
- Logger: logs application and error messages
Logger: logs application and error messages
- LogRecord: information to be logged
LogRecord: information to be logged
- Handler: Determines destination (1 or more)
Handler: Determines destination (1 or more) File.. Console.. Stream.. Socket.. Memory.. ile.. Console.. Stream.. Socket.. Memory..
- Formatter: Determines format of info
- rmatter: Determines format of info
SimpleF SimpleFormatter, XMLF
- rmatter, XMLFormatter
- rmatter
- LogManager: Controls logging configuration
LogManager: Controls logging configuration Provides default handling – config file Provides default handling – config file
Logger functionality Logger functionality
- Log messages are tagged with a level:
Log messages are tagged with a level: SE SEVE VERE, WA RE, WARNING, INF RNING, INFO, O, CONF CONFIG, IG, FINE, F INE, FINER, F INER, FINEST INEST Severe(message), …, finest(message) Severe(message), …, finest(message) Log(level, message) Log(level, message)
- Additional information in log() methods:
Additional information in log() methods: Class, method, an object, array of objects, Class, method, an object, array of objects, Throwable, Log(level, message, Object) hrowable, Log(level, message, Object) System attempts to identify class/method System attempts to identify class/method
Logged inform Logged information ation
- A LogRecord contains attributes that include
A LogRecord contains attributes that include Level, message, time, logger name, Level, message, time, logger name, message parameters, class * message parameters, class *, method * , method *, thread id, exception details thread id, exception details
- A F
A Formatter formats these fields into a string
- rmatter formats these fields into a string
SimpleF SimpleFormatter – A string, inserts values
- rmatter – A string, inserts values
XMLF XMLFormatter – XML using a fixed dtd
- rmatter – XML using a fixed dtd
Write your own formatter Write your own formatter A F A Filter includes/excludes based on tests ilter includes/excludes based on tests
package com.spadt.jdk14; import java.util.logging.*; /** Illustrates the new java.util.logging facilities. */ public class SimpleLogging { public static void main(String[] args) { // Set up a logger using all the defaults Logger log = Logger.getLogger("com.spadt.simple"); log.info("starting main"); try { int a = 1 / 0; } catch(Exception e) { log.log(Level.WARNING, "Calculation error", e); } log.info("Completed"); } }
Console Log – Results of SimpleLogging Apr 26, 2002 2:53:40 PM com.spadt.jdk14.SimpleLogging main INFO: starting main Apr 26, 2002 2:53:40 PM com.spadt.jdk14.SimpleLogging main WARNING: Calculation error java.lang.ArithmeticException: / by zero at com.spadt.jdk14.SimpleLogging.main(SimpleLogging.java:13) Apr 26, 2002 2:53:40 PM com.spadt.jdk14.SimpleLogging main INFO: Completed
package com.spadt.jdk14; import java.io.IOException; import java.util.logging.*; /** Illustrates custom java.util.logging functions. */ public class XmlLogging { public static void main(String[] args) throws IOException { // Set up a custom logger Logger log = Logger.getLogger("com.spadt.xml"); FileHandler h = new FileHandler("c:/log/log.xml"); h.setFormatter(new XMLFormatter()); log.addHandler(h); log.setLevel(Level.ALL); try { int a = 1 / 0; } catch(Exception e) { log.log(Level.WARNING, "Calculation error", e); } log.fine("Completed"); }
c:/log/log.xml log file contents – XmlLogging <?xml version="1.0" encoding="windows-1252" standalone="no"?> <!DOCTYPE log SYSTEM "logger.dtd"> <log> <record> <date>2002-04-27T10:33:17</date> <millis>1019917997510</millis> <sequence>0</sequence> <logger>com.spadt.xml</logger> <level>WARNING</level> <class>com.spadt.jdk14.XmlLogging</class> <method>main</method> <thread>10</thread> <message>Calculation error</message> <exception> <message>java.lang.ArithmeticException: / by zero</message> <frame> <class>com.spadt.jdk14.XmlLogging</class> <method>main</method> <line>18</line> </frame> </exception> </record>
Logging Strategy Logging Strategy
- Specify logging.properties entries - each app
Specify logging.properties entries - each app
- Logging config in properties file – not code
Logging config in properties file – not code
- 2 lines of code to use in each class
2 lines of code to use in each class
- System.out.println() aficionados
System.out.println() aficionados Start using java.util.logging now Start using java.util.logging now
- Log4j users
Log4j users Both solutions are appropriate Both solutions are appropriate Same hierarchical / declarative strategy Same hierarchical / declarative strategy Different keywords for level of detail Different keywords for level of detail
Debugging Features Debugging Features
- Full-speed debugging: for long-running progs
ull-speed debugging: for long-running progs
- Hot-swap: runtime swap of classes
Hot-swap: runtime swap of classes
- Validation of parameters/returns in JNI calls
Validation of parameters/returns in JNI calls
- Debug information for native code crashes
Debug information for native code crashes
- Chained exceptions (like EJBException)
Chained exceptions (like EJBException)
throw new MyException(msg, cause);
- Garbage collection logging
Garbage collection logging
Preferences API Preferences API
- Can replace Properties in most cases
Can replace Properties in most cases
- Stores application and configuration data
Stores application and configuration data Standard place for property data Standard place for property data Storage of data is system-independent Storage of data is system-independent Facilitates moving to another machine acilitates moving to another machine You can implement any data store You can implement any data store
- User and system-wide preferences
User and system-wide preferences
- Store application and configuration data
Store application and configuration data
- Typed getters and setters …
yped getters and setters …
Preferences functionality Preferences functionality
- Methods to access values
Methods to access values
get(String key, String default) getInt, getBoolean, getDouble, getFloat, Long, getByteArray put(String key, String value)
- Static methods to retrieve preferences nodes
Static methods to retrieve preferences nodes
userNodeForPackage() per user/package systemNodeForPackage() for all users userRoot().node(name) user info systemRoot().node(name) config info
package com.spadt.jdk14; import java.io.*; import java.util.prefs.*; /** Access and change User preferences example */ public class Prefs { public void run() throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); Preferences prefs = Preferences.userNodeForPackage(this.getClass()); String greeting = prefs.get("greeting", "sir/madam"); System.out.println("Greetings, " + greeting + “!”); System.out.println("Type your new greeting."); if((greeting = in.readLine()).length() > 0) { prefs.put("greeting", greeting); System.out.println("New greeting saved."); } } public static void main(String[] args) throws IOException { (new Prefs()).run(); } }
Results from running Prefs > java com.spadt.jdk14.Prefs Greetings, sir/madam! Type your new greeting. Bad Dog New greeting saved. > java com.spadt.jdk14.Prefs Greetings, Bad Dog! Type your new greeting. This was added to the Windows Registry: My Computer\HKEY_CURRENT_USER\Software \JavaSoft\Prefs\com\spadt\jdk14 Name: greeting Data: “/Bad /Dog”
package com.spadt.jdk14; import java.io.*; import java.util.prefs.*; /** System preferences example */ public class SysPrefs { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); Preferences prefs = Preferences.systemRoot().node("email-settings"); String replyTo = prefs.get("reply-to", ""); System.out.println("Reply-to is now [" + replyTo + "]"); System.out.println("Type updated reply-to."); replyTo = in.readLine(); prefs.put("reply-to", replyTo); System.out.println("New reply-to saved."); } }
Results from running SysPrefs > java com.spadt.jdk14.SysPrefs Reply-to is now [] Type updated reply-to. jack@cheese.com New reply-to saved. > java com.spadt.jdk14.SysPrefs Reply-to is now [jack@cheese.com] Type updated reply-to. This was added to the Windows Registry: My Computer\HKEY_LOCAL_MACHINE\Software \JavaSoft\Prefs\email-settings Name: reply-to Data: “jack@cheese.com”
Object Persistence Object Persistence
- Solves serialization version problems
Solves serialization version problems
- Long-term persistence
Long-term persistence Independent of serial version Independent of serial version Works with different JVM’s Works with different JVM’s Object information saved in xml format Object information saved in xml format
- XMLEncoder and XMLDecoder
XMLEncoder and XMLDecoder Constructors take input/output streams Constructors take input/output streams readObject() and writeObject() readObject() and writeObject() Reads/builds objects using get/set Reads/builds objects using get/set Object information saved in xml format Object information saved in xml format
package com.spadt.jdk14; import java.io.*; import java.beans.*; import javax.swing.JLabel; public class Persist { public static void main(String[] args) throws IOException { JLabel label1 = new JLabel(); label1.setText("Caption"); label1.setBounds(20, 40, 120, 20); XMLEncoder enc = new XMLEncoder( new FileOutputStream("c:/tmp/p.xml")); enc.writeObject(label1); enc.close(); XMLDecoder dec = new XMLDecoder( new FileInputStream("c:/tmp/p.xml")); JLabel label2 = (JLabel) dec.readObject(); dec.close(); System.out.println(
Contents of the xml file for Persist <?xml version="1.0" encoding="UTF-8"?> <java version="1.4.0" class="java.beans.XMLDecoder"> <object class="javax.swing.JLabel"> <void property="bounds"> <object class="java.awt.Rectangle"> <int>20</int> <int>40</int> <int>120</int> <int>20</int> </object> </void> <void property="text"> <string>Caption</string> </void> </object> </java>
GUI Enhancem GUI Enhancements ents
- New focus architecture
New focus architecture Fixes bugs, platform incompatibilities ixes bugs, platform incompatibilities Can now identify who’s focused Can now identify who’s focused
- Mouse wheel support
Mouse wheel support
- Spinner widget
Spinner widget
- Windows 2000 look and feel
Windows 2000 look and feel
- Improved JF
Improved JFileChooser ileChooser
- Much faster 2D rendering
Much faster 2D rendering
- Game support: accelerator cards
Game support: accelerator cards
Swing Drag and Drop Swing Drag and Drop
- D-n-D is not new in 1.4 – just much easier
D-n-D is not new in 1.4 – just much easier
- Two methods of data transfer
wo methods of data transfer Drag and drop – not just text Drag and drop – not just text Clipboard transfer: cut, copy, and paste Clipboard transfer: cut, copy, and paste
- Platform independent: Java - Java transfer
Platform independent: Java - Java transfer
- Platform dependent – native implementation
Platform dependent – native implementation Windows OLE drag-n-drop Windows OLE drag-n-drop Motif and Mac OS implementations Motif and Mac OS implementations
- Data transfer model based on MIME types
Data transfer model based on MIME types
Drag and Drop operations Drag and Drop operations
- Drag = press mouse button, drag a few pixels
Drag = press mouse button, drag a few pixels
- Automatic support – setDragEnabled()
Automatic support – setDragEnabled() JColorChooser JColorChooser, JE , JEditor ditorPane, JF ane, JFileC ileChooser hooser, , JList, JT JList, JTab able, e, JT JTextArea, JT extArea, JTextF extField, JT ield, JTree, ee, JT JTextPane, JF extPane, JFormattedT
- rmattedTextF
extField ield
- Handle drag: exportAsDrag()
Handle drag: exportAsDrag()
- Add dnd support – T
Add dnd support – TransferHandler ransferHandler new T new TransferHandler(“text”) ransferHandler(“text”) getCutAction(), getPasteAction() getCutAction(), getPasteAction()
package com.spadt.jdk14; import java.awt.event.*; import javax.swing.*; public class DragDrop extends JFrame { public DragDrop() { addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { System.exit(0); } }); panel.setLayout(null); panel.setPreferredSize(new java.awt.Dimension(340, 72)); labelApe.setBounds(10, 20, 40, 16); panel.add(labelApe); labelBear.setBounds(10, 36, 40, 16); panel.add(labelBear); text.setBounds(60, 20, 260, 30); text.setDragEnabled(true); panel.add(text); getContentPane().add(panel); pack(); }
public static void main(String args[]) { new DragDrop().show(); } private static class DropLabel extends JLabel { public DropLabel(String text) { super(text); setTransferHandler(new TransferHandler("text")); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { JLabel lbl = (JLabel) e.getSource(); TransferHandler h = lbl.getTransferHandler(); h.exportAsDrag(lbl, e, TransferHandler.COPY); } }); } } private JPanel panel = new JPanel(); private DropLabel labelApe = new DropLabel("Ape"); private DropLabel labelBear = new DropLabel("Bear"); private JTextField text = new JTextField("Drop here"); }
Java Web Start Java Web Start
- Launch full java applications automatically
Launch full java applications automatically Web browser link to load/run over network Web browser link to load/run over network Java Web Start application manager Java Web Start application manager Windows: creates desktop icon Windows: creates desktop icon
- Client systems cache the application code
Client systems cache the application code Checks server for latest version Checks server for latest version Runs application from disk Runs application from disk
- Java 2 security model for required privileges
Java 2 security model for required privileges
Java Web Start: Server Prep Java Web Start: Server Prep
- JNLP = Java Network Loading Protocol
JNLP = Java Network Loading Protocol
- Web server: recognize .jnlp file extension
Web server: recognize .jnlp file extension Apache: Add a directive in httpd.conf Apache: Add a directive in httpd.conf AddT AddType application/x-java-jnlp-file .jnlp ype application/x-java-jnlp-file .jnlp Restart web server to activate Restart web server to activate
- Create a .jnlp xml file to describe the app
Create a .jnlp xml file to describe the app
- Package jnlp file and all jars onto web server
Package jnlp file and all jars onto web server
Java Web Start: dragdrop.jnlp file <?xml version="1.0" encoding="utf-8"?> <jnlp spec="1.0+" codebase="http://www.accubase.com/java" href="dragdrop.jnlp"> <information> <title>Web Start for DragDrop</title> <vendor>Kirk Spadt</vendor> <homepage href="java/help.html"/> <description>Web Start DragDrop demo</description> <offline-allowed/> </information> <resources> <j2se version="1.4"/> <jar href="dragdrop.jar"/> </resources> <application-desc main-class="com.spadt.jdk14.DragDrop“ /> </jnlp>
Java Web Start: Client Prep Java Web Start: Client Prep
- Do once:
Do once: Download Java Web Start from Sun: Download Java Web Start from Sun: http://java.sun.com/products/ http://java.sun.com/products/ javawebstart/download-windows.html javawebstart/download-windows.html Follow the instructions to download the
- llow the instructions to download the
java runtime and Web Start java runtime and Web Start
- To run:
- run:
Navigate to a link that points to the jnlp file Navigate to a link that points to the jnlp file The program loads and runs automatically he program loads and runs automatically
- E.g.: www.accubase.com/java/dragdrop.jnlp
E.g.: www.accubase.com/java/dragdrop.jnlp
API’s M API’s Moved into J2SE v1.4
- ved into J2SE v1.4
- JAXP: Java API for XML Processing
JAXP: Java API for XML Processing
- JDBC-2, 2.1 and JDBC 3.0
JDBC-2, 2.1 and JDBC 3.0
- CORBA enhancements
CORBA enhancements
- DNS Service Provider for JNDI
DNS Service Provider for JNDI
- JCE: Java Cryptography Extensions
JCE: Java Cryptography Extensions
- JSSE: Java Secure Socket Extension
JSSE: Java Secure Socket Extension
- JAAS: Java Authentication/Authorization
JAAS: Java Authentication/Authorization
- GSS-API: Kerberos Single sign-on
GSS-API: Kerberos Single sign-on
JAXP : XM JAXP : XML Processing L Processing
- SAX 2.0: Simple API for XML Processing
SAX 2.0: Simple API for XML Processing org.xml.sax.*
- rg.xml.sax.* - sequential parsers
- sequential parsers
javax.xml.parsers – Pluggable parsers javax.xml.parsers – Pluggable parsers
- DOM Level 2 – Document Object Model
DOM Level 2 – Document Object Model org.w3c.dom – Doc model interfaces
- rg.w3c.dom – Doc model interfaces
- XSLT
XSLT – XML Document conversion – XML Document conversion javax.xml.transform javax.xml.transform
JDBC-2, 2.1, and JDBC 3.0 JDBC-2, 2.1, and JDBC 3.0
- JD
JDBC-2 2 (javax. avax.sql sql) is s incl ncluded uded now now Dat ataS aSour
- urce:
ce: access access thr hrough
- ugh JN
JNDI Row
- wSet
et: caches caches resul esult set set on
- n cl
client ent Scr crol
- llabl
able e resul esult set sets s (cur cursor sors) s) Bat atch ch updat updates: es: mul ultipl ple e sql sql st stat atem ement ents
- JD
JDBC 3. 3.0 0 new new feat eatur ures es added added to
- J2S
J2SE 1. 1.4 Pool
- oled
ed dat datasour asources ces and and st stat atem ement ents Mul ultipl ple e resul esult set sets Updat pdate e BLO LOB, CLO LOB, ar array, ay, Ref ef’s Dat ata a types: ypes: BOOLE LEAN, DATA TALI LINK, UDT Savepoi avepoint nt suppor support – – rest estor
- re
e to
- mul
ultipl ple e savepoi savepoint nts
CORBA Enhancem CORBA Enhancements ents
- POA –
– Por
- rtabl
able e Obj bject ect Adapt dapter er suppor support Obj bject ects s por portabl able e acr across
- ss CORBA impl
pl
- INS –
– Int nter eroper
- perabl
able e Nam aming ng Ser ervi vice ce Resol esolve ve ser servi vices ces usi using ng nam name e st strings ngs URLs Ls for
- r CORBA obj
- bject
ect ref efer erences ences
- GIOP: Gener
eneral al IIOP – – gener general al wire e pr prot
- tocol
- col
- Dynam
ynamic c Anys: nys: runt untime e type ype di discover scovery
- ORBD: An
n Obj bject ect request equest br broker
- ker daem
daemon
- n
impl plem ement entat ation
- n
JNDI DNS Service Provider JNDI DNS Service Provider
- Allow
- ws
s JN JNDI appl applicat cations
- ns to
- access
access DNS
- Impl
plem ement ents s RFC FC-1034 1034 and and 1035 1035
- URL
L : dns: dns://ns. ns.who. ho.com com:53/ 53/dom domai ain. n.to.
- .find.
nd.com com
- Ret
etrieve eve at attribut butes es usi using ng di direct ector
- ry
y cont context ext: Hasht ashtabl able e env env = new new HashTabl ashTable( e(); env. env.put put(“java. ava.nam naming. ng.pr provi
- vider
der.ur url”, “dns: dns://ns. ns.myi yisp. sp.com com/ser server ver.com com”); DirCont
- ntext
ext c c = new new Ini nitial alDirCont
- ntext
ext(env) env); Attribut butes es at attr = c. c.get getAttribut butes( es(“host host” new new String[ ng[] {“A”}));
- Ret
etrieves eves ip p addr address ess for
- r host
host.ser server ver.com com
JCE: Java Cryptography JCE: Java Cryptography
- Crypt
yptogr
- graphy
aphy engi engines nes Message essage di digest gests s (hashes) hashes) Signat gnatur ures es (si sign gn and and ver verify) y) Key ey pai pair gener generat ation
- n (publ
public/ c/pr privat vate) e) Cer ertificat cates es (used used to
- aut
authent henticat cate e ident dentities) es) Key ey st stor
- res
es ( a a dat database abase of
- f publ
public/ c/pr privat vate e keys) keys) Random andom gener generat ator
- r
- New
ew in n J2S J2SE 1. 1.4 Cer ertificat cate e pat path h bui builder der (cer cert chai chains) ns) Cer ertificat cate e pat path h val validat dator
- r
Cer ertificat cate e st stor
- re
JSSE: Java Secure Socket JSSE: Java Secure Socket
- Impl
plem ement ents s secur secure e com communi unicat cation
- n with
h SSL
- SSL
L (cl client ent) and and ser server ver socket sockets
- Key
ey and and trust ust manager anager int nter erfaces aces (X.509) 509)
- Secur
ecure e HTTP TTP URL L connect connections
- ns
- Publ
ublic c key key cer certificat cate e API
- SunJS
unJSSE pr provi
- vider
der impl plem ement entat ation
- n
RSA suppor support SSL L 3. 3.0 0 and and TLS TLS 1. 1.0 Most
- st com
common
- n ci
cipher pher sui suites es RSA, DES, DES3, 3, DES40, 40, RC4, 4, SHA, MD5 5 com combi binat nations
- ns ar
are e impl plem ement ented. ed.
JAAS: Authentication/Authorization JAAS: Authentication/Authorization
- Aut
uthent henticat cation:
- n: Who
Who ar are e you, you, real eally? y?
- Aut
uthor horizat zation:
- n: What
What will I al allow
- w you
you to
- do?
do?
- PAM: Pluggabl
uggable e aut authent henticat cation
- n modul
- dule
Add dd aut auth h without hout changi changing ng appl applicat cation
- n
- Access
ccess cont control
- l in
n 1. 1.4 4 now now based based on:
- n:
CodeS
- deSour
- urce:
ce: code code locat
- cation
- n and
and si signer gners Princi ncipal pal: Repr epresent esents s a a Subj ubject ect at at si signon gnon Subj ubject ect: User ser (Princi ncipal pal(s) s) and and cr credent edential als) s) Per ermissi ssion:
- n: What
What you you can can do do Pol
- licy:
cy: gr grant ants s use use of
- f CodeS
- deSour
- urce
ce to
- Princi
ncipal pal
Item Items Deferred to J2SE 1.5 s Deferred to J2SE 1.5
- JSR-014 Generic T
JSR-014 Generic Types ypes
List<String> list = Arrays.asList(args) String argZero = list.get(0);
- JSR-051 printf/scanf capabilities
JSR-051 printf/scanf capabilities
- JSR-076 RMI Security for J2SE
JSR-076 RMI Security for J2SE
- JSR-078 RMI Custom Remote References
JSR-078 RMI Custom Remote References
- JSR-031 XML Data Binding Specification
JSR-031 XML Data Binding Specification
- XML: JAXM, JAXR
XML: JAXM, JAXR
- Additional Swing and 2D performance