65
Philly Java Users Group Kirk B. Spadt What’s new in Java 2 Standard Edition 1.4 [email protected]

Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Philly Java Users Group

Kirk B. Spadt

What’s new inJava 2 Standard Edition 1.4

[email protected]

Page 2: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Java 2 Standard Edition 1.4• Availability: February 13, 2002• Size: Over 11,000 classes (API’s + impl)• Changes: 33% new or changed methods• Performance: Major enhancements• Functionality: Enterprise connectivity• Scalability: 64-bit core support• Ease of programming: More API’s• Ease of use: Drag/drop, wheel, install• Compatibility with earlier releases

Page 3: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Performance Enhancements

• 50-100% I/O improvement• 10x Reflection performance increase• Garbage collection - concurrent (MP)• 30% Swing improvement (pipeline)• Hardware acceleration (DirectDraw)• 20% reduction in RAM footprint• 20% reduction in startup time

Page 4: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

API’s Moved into J2SE v1.4

• JAXP: Java API for XML Processing• JDBC-2, 2.1 and JDBC 3.0• CORBA enhancements• DNS Service Provider for JNDI• JCE: Java Cryptography Extensions• JSSE: Java Secure Socket Extension• JAAS: Java Authentication/Authorization• GSS-API: Kerberos Single sign-on

Page 5: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

New Functions

• Assertions• Regular expressions• New I/O API• Printing API• Logging API• Preferences API

• XML Persistence• Fast 2D Graphics• Redesigned focus• Swing drag-n-drop• Java Web Start

Page 6: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Code Disclaimer

• Subsequent sections include a sample program to illustrate use of the new classes.

• Written to be BRIEF (single slide) The code works…, but… Ignores exceptions Breaks MVC & some accepted practices

• Code is AS-IS, and use in nuclear facilities or life-support applications is prohibited.

Page 7: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Assertions

• Tests a condition you “know” is true Confirms programmer assumptions Improves program reliability

• assert: New Java language keyword javac –source 1.4 Foo.java to compile

java –ea Foo to run• throws an AssertionError

java.lang.Error subclass (unchecked)

Page 8: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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); }}

Page 9: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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 symbolsymbol : class assertlocation: 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

>javac –source 1.4 com\spadt\jdk14\Assert.java

Page 10: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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)

Page 11: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Assertions Strategy• YES: Programmer errors or omissions

if() … else if() … else assert switch(x) … case 1: … default: assert verifying ownership of object locks how could I ever get here?

• NO: User, system, or configuration errors User entry errors – detailed message SQL, Remote, etc errors – log them Config errors – log for deployers

Page 12: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Regular Expressions

• Powerful tools to match and process text.• Familiar to unix shell and perl programmers• Matching, extraction, and substitution• Examples for matches:

“[0-9]+” – matches one or more digits “dog|cat” – matches either “dog” or “cat” (.*)\r?\n” – the (.*) matches a text line “[a-zA-Z][a-zA-Z_0-9]*” – a java name

Page 13: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Regular Expression Classes• java.util.regex: New package• Pattern class: specify a regular expression

matches(): an easy test for a match split(): breaks a string using delimiters Compile(): Parse expr ahead - performance

• Matcher class: match and parse text using the regular expression matches(): a fast test for a match find(): tests if text contains pattern start(), end() – indexes of match group() – a string or substring that matched

Page 14: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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]); } } }}

Page 15: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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++)

System.out.println("Part " + i + "=" + parts[i]);

}

}

Page 16: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

New I/O (NIO) API• Ultra-scalable high-performance server apps• Access to large quantities of data• New File I/O

Read/write/transfer twice as fast Concurrent read/write operations Supports file locking Memory-mapped file I/O

• New Network I/O Far more simultaneous connections Multiple connections per thread

Page 17: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

New File I/O• Buffer: contains sequences of primitive types

Int.. Byte.. Char.. Double.. other primitives Bulk data transfer to buffers and arrays

• Channel: primitive connection to device• FileChannel: map() - memory-maps files

lock(position, size, shared) – blocking tryLock() – nonblocking Read/write to arrays of buffers Bulk data transfer between channels force() – guarantees I/O write to device

Page 18: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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); } } }}

Page 19: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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) {

}

Page 20: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

New Network I/O

• IPv6: e.g. 1080:0:0:0:8:800:200C:417A• SocketChannel: Non-blocking option

Connect() and finishConnect() Datagram- and ServerSocket- Channel

• Selector: A channel multiplexor channel.register(selector) – notification select(): blocks until channel activity,

wakeup(), timeout, thread interrupt selectedKeys(): channels with pending I/O Enables multiple channels per thread

Page 21: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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(); 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); }}

Page 22: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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); } }

Page 23: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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(); } . . .

Page 24: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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);}

Page 25: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

New I/O Strategy• Server development: “Must do”

Far more scalable – not thread-limited 50 – 100% performance improvement App servers – will be done for us

• Client development: New development Large and composite file processing Entire file, e.g. DOM XML, images, models

• Retrofit: Only as dictated by needs Application performance / profiling

Page 26: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Java Print Service• Discovery and selection of available printers

PrintServiceLookup Selection based on capabilities / properties

• DocFlavor – specifies destination and format Stream, reader, byte array, URL Format: MIME type constants

• Doc object: request attributes and print data• DocPrintJob: submits document to printer• Pluggable print services using spi

Page 27: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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 System.out.println("No printers can print this job"); }}

Page 28: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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");

Page 29: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Logging API• Facilitates analysis, application error reporting• Logger: logs application and error messages• LogRecord: information to be logged• Handler: Determines destination (1 or more)

File.. Console.. Stream.. Socket.. Memory..• Formatter: Determines format of info

SimpleFormatter, XMLFormatter• LogManager: Controls logging configuration

Provides default handling – config file

Page 30: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Logger functionality• Log messages are tagged with a level:

SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST

Severe(message), …, finest(message) Log(level, message)

• Additional information in log() methods: Class, method, an object, array of objects,

Throwable, Log(level, message, Object) System attempts to identify class/method

Page 31: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Logged information• A LogRecord contains attributes that include

Level, message, time, logger name,message parameters, class *, method *,thread id, exception details

• A Formatter formats these fields into a string SimpleFormatter – A string, inserts values XMLFormatter – XML using a fixed dtd Write your own formatter

A Filter includes/excludes based on tests

Page 32: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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"); }}

Page 33: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Console Log – Results of SimpleLogging

Apr 26, 2002 2:53:40 PM com.spadt.jdk14.SimpleLogging mainINFO: starting main

Apr 26, 2002 2:53:40 PM com.spadt.jdk14.SimpleLogging mainWARNING: Calculation errorjava.lang.ArithmeticException: / by zero at com.spadt.jdk14.SimpleLogging.main(SimpleLogging.java:13)

Apr 26, 2002 2:53:40 PM com.spadt.jdk14.SimpleLogging mainINFO: Completed

Page 34: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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"); }}

Page 35: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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>

Page 36: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Logging Strategy

• Specify logging.properties entries - each app• Logging config in properties file – not code• 2 lines of code to use in each class

• System.out.println() aficionados Start using java.util.logging now

• Log4j users Both solutions are appropriate Same hierarchical / declarative strategy Different keywords for level of detail

Page 37: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Debugging Features

• Full-speed debugging: for long-running progs• Hot-swap: runtime swap of classes• Validation of parameters/returns in JNI calls• Debug information for native code crashes• Chained exceptions (like EJBException)

throw new MyException(msg, cause);

• Garbage collection logging

Page 38: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Preferences API• Can replace Properties in most cases• Stores application and configuration data

Standard place for property data Storage of data is system-independent Facilitates moving to another machine You can implement any data store

• User and system-wide preferences• Store application and configuration data• Typed getters and setters …

Page 39: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Preferences functionality• 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 userNodeForPackage() per user/package

systemNodeForPackage() for all users

userRoot().node(name) user info

systemRoot().node(name) config info

Page 40: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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(); } }

Page 41: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Results from running Prefs

> java com.spadt.jdk14.Prefs

Greetings, sir/madam!Type your new greeting.Bad DogNew 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”

Page 42: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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."); }}

Page 43: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Results from running SysPrefs

> java com.spadt.jdk14.SysPrefs

Reply-to is now []Type updated [email protected] reply-to saved.

> java com.spadt.jdk14.SysPrefs

Reply-to is now [[email protected]]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: “[email protected]

Page 44: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Object Persistence• Solves serialization version problems• Long-term persistence

Independent of serial version Works with different JVM’s Object information saved in xml format

• XMLEncoder and XMLDecoder Constructors take input/output streams readObject() and writeObject() Reads/builds objects using get/set Object information saved in xml format

Page 45: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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( "Label2 text=[" + label2.getText() + "]"); }}

Page 46: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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>

Page 47: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

GUI Enhancements• New focus architecture

Fixes bugs, platform incompatibilities Can now identify who’s focused

• Mouse wheel support• Spinner widget• Windows 2000 look and feel• Improved JFileChooser• Much faster 2D rendering• Game support: accelerator cards

Page 48: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Swing Drag and Drop

• D-n-D is not new in 1.4 – just much easier• Two methods of data transfer

Drag and drop – not just text Clipboard transfer: cut, copy, and paste

• Platform independent: Java - Java transfer• Platform dependent – native implementation

Windows OLE drag-n-drop Motif and Mac OS implementations

• Data transfer model based on MIME types

Page 49: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Drag and Drop operations• Drag = press mouse button, drag a few pixels• Automatic support – setDragEnabled()

JColorChooser, JEditorPane, JFileChooser, JList, JTable, JTextArea, JTextField, JTree, JTextPane, JFormattedTextField

• Handle drag: exportAsDrag()• Add dnd support – TransferHandler

new TransferHandler(“text”) getCutAction(), getPasteAction()

Page 50: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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(); }

Page 51: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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");}

Page 52: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Java Web Start

• Launch full java applications automatically Web browser link to load/run over network Java Web Start application manager Windows: creates desktop icon

• Client systems cache the application code Checks server for latest version Runs application from disk

• Java 2 security model for required privileges

Page 53: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Java Web Start: Server Prep

• JNLP = Java Network Loading Protocol• Web server: recognize .jnlp file extension

Apache: Add a directive in httpd.confAddType application/x-java-jnlp-file .jnlp

Restart web server to activate• Create a .jnlp xml file to describe the app• Package jnlp file and all jars onto web server

Page 54: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

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>

Page 55: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Java Web Start: Client Prep• Do once:

Download Java Web Start from Sun: http://java.sun.com/products/ javawebstart/download-windows.html

Follow the instructions to download thejava runtime and Web Start

• To run: Navigate to a link that points to the jnlp file The program loads and runs automatically

• E.g.: www.accubase.com/java/dragdrop.jnlp

Page 56: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

API’s Moved into J2SE v1.4

• JAXP: Java API for XML Processing• JDBC-2, 2.1 and JDBC 3.0• CORBA enhancements• DNS Service Provider for JNDI• JCE: Java Cryptography Extensions• JSSE: Java Secure Socket Extension• JAAS: Java Authentication/Authorization• GSS-API: Kerberos Single sign-on

Page 57: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

JAXP : XML Processing

• SAX 2.0: Simple API for XML Processing org.xml.sax.* - sequential parsers javax.xml.parsers – Pluggable parsers

• DOM Level 2 – Document Object Model org.w3c.dom – Doc model interfaces

• XSLT – XML Document conversion javax.xml.transform

Page 58: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

JDBC-2, 2.1, and JDBC 3.0• JDBC-2 (javax.sql) is included now

DataSource: access through JNDI RowSet: caches result set on client Scrollable result sets (cursors) Batch updates: multiple sql statements

• JDBC 3.0 new features added to J2SE 1.4 Pooled datasources and statements Multiple result sets Update BLOB, CLOB, array, Ref’s Data types: BOOLEAN, DATALINK, UDT Savepoint support – restore to multiple savepoints

Page 59: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

CORBA Enhancements • POA – Portable Object Adapter support

Objects portable across CORBA impl• INS – Interoperable Naming Service

Resolve services using name strings URLs for CORBA object references

• GIOP: General IIOP – general wire protocol• Dynamic Anys: runtime type discovery• ORBD: An Object request broker daemon

implementation

Page 60: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

JNDI DNS Service Provider

• Allows JNDI applications to access DNS• Implements RFC-1034 and 1035• URL : dns://ns.who.com:53/domain.to.find.com• Retrieve attributes using directory context:

Hashtable env = new HashTable();env.put(“java.naming.provider.url”, “dns://ns.myisp.com/server.com”);DirContext c = new InitialDirContext(env);Attributes attr = c.getAttributes(“host” new String[] {“A”}));

• Retrieves ip address for host.server.com

Page 61: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

JCE: Java Cryptography

• Cryptography engines Message digests (hashes) Signatures (sign and verify) Key pair generation (public/private) Certificates (used to authenticate identities) Key stores ( a database of public/private keys) Random generator

• New in J2SE 1.4 Certificate path builder (cert chains) Certificate path validator Certificate store

Page 62: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

JSSE: Java Secure Socket

• Implements secure communication with SSL• SSL (client) and server sockets• Key and trust manager interfaces (X.509)• Secure HTTP URL connections• Public key certificate API• SunJSSE provider implementation

RSA support SSL 3.0 and TLS 1.0 Most common cipher suites RSA, DES, DES3, DES40, RC4, SHA, MD5

combinations are implemented.

Page 63: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

JAAS: Authentication/Authorization

• Authentication: Who are you, really?• Authorization: What will I allow you to do?• PAM: Pluggable authentication module

Add auth without changing application• Access control in 1.4 now based on:

CodeSource: code location and signers Principal: Represents a Subject at signon Subject: User (Principal(s) and credentials) Permission: What you can do Policy: grants use of CodeSource to Principal

Page 64: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Items Deferred to J2SE 1.5

• JSR-014 Generic Types List<String> list = Arrays.asList(args)

String argZero = list.get(0);

• JSR-051 printf/scanf capabilities • JSR-076 RMI Security for J2SE • JSR-078 RMI Custom Remote References • JSR-031 XML Data Binding Specification • XML: JAXM, JAXR• Additional Swing and 2D performance

Page 65: Philly Java Users Group What’s new in Java 2 Standard ... · Compiling: Assertions disabled >javac com\spadt\jdk14\Assert.java com\spadt\jdk14\Assert.java:7: warning: as of release

Philly Java Users Group

Kirk B. Spadt

What’s new inJava 2 Standard Edition 1.4

[email protected]