Download java.pa2

Document related concepts
no text concepts found
Transcript
Java Overview
About me


Peter Kriens
Work as a consultant
(mainly for for ERICSSON)




Finnasandsvagen 22
43933 Onsala, Sweden
+46 705950899
[email protected]
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
History

1990 SUN starts crash team under Patrick
Naughton




Carte blanche to clean up the software mess at SUN
Gosling created OAK for embedded devices (!)
Products all failed
1993 Mosaic, the first web browser was born


Somebody realized the combination: Applets
Language became the product
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
History

1996 JDK 1.0 released



Focused on Applets, lousy graphics
8 packages, 4Mb download
1997 JDK 1.1 released


Better graphics, reflection, security (try), beans,
RMI, ZIP files
22 Packages, 9 Mb download
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
History

1999 JDK 1.2 SE released



Lightweight UI (!), collections, security (again), JAR
files, Native interface change…
59 packages, 20 Mb download
2000 JDK 1.3 SE in beta


Improvements ...
77 packages (so far), 25 Mb download
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Quick Tour: Hello World

Getting started





Content of file: HelloWorld.java
/**
* Small hello world example class.
*
*/
public class HelloWorld {
public static void main( String args[] ) {
System.out.println( "Hello world"
+ (args.length >= 1 ? args[0] : "whoever") );
}
}
javac HelloWorld.java
java HelloWorld peter
Hello world peter
That is all ...
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Quick Tour: Objects

Creating a class


Content of file: Point.java
/**
* A Simple point class.
*/
public class Point {
double
_x;
// Instance variable
double
_y;
public Point() { this(0,0); }
public Point( double x, double y ) { _x=x; _y=y; }
public double getX() { return _x; }
public double getY() { return _y; }
public double getLength() {
return Math.sqrt( getX()*getX() + getY() * getY() ); }
public Point translate( Point t ) {
return new Point(getX() + t.getX(), getY() + t.getY() );}
}
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Quick Tour: Not to be an Object



Not all variables are objects like in Smalltalk
int, char, boolean, long, double, float, byte are
<primitive> types.
Each primitive type is represented by a class in
java.lang

public class HelloWorld {
public static void main( String args[] ) {
int length = args.length;
Point p = new Point( length, length );
}
}
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Quick Tour: Inner class


Everything had to be a class. Callbacks require
their own class
Too cumbersome to specify in other file, so
special syntax was wrought (ugly!):

public static void main( String args[] ) {
Point p = new Point()
{
public double getX() { return super.getX() * 2; }
};
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Quick Tour: Garbage Collection

Java cleans up after you



/* GC */
...
Point
p = new Point();
p = p.translate( new Point(10,10) );
...
Previous code creates 3 new objects
No need for destructor. No need for delete
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Quick Tour: Inheritance

Classes can be extended



/* Extending point class */
public class Point3 extends Point {
double
_z;
public Point3() { _z=0; super(0,0); }
public double getZ() { return _z; }
public double getLength() {
return Math.sqrt(
getX()*getX() + getY()*getY() + getZ() * getZ() ); }
...
}
Only use it for an "is-a" relationship
Powerful but easy to overdo
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Quick Tour: Inheritance



Single inheritance only
All classes inherit from class Object
A Class is a an instance of class Class


Class objects can be used as normal objects



So the class Class is an instance of Class (!)
Reflection
ClassLoaders
"super" keyword to access super class
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Quick Tour: Interfaces

Used for specifications

/* Interfaces */
public interface Compare {
public int compare( Compare t );
}
class CPoint extends Point implements Compare {
public int compare( Compare t ) {
Point tt = (Point) t;
return getLength() - t.getLength();
}
}


Decouples using from implementation
Very popular with specifications
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Quick Tour: Interfaces
public interface Log {
public void log(String s);
}
client
uses
public class SimpleLog {
public void log(String s) {
System.out.println( s );
}
}
Simple
Log
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
interface
Log
implements
IBM
Log
Motorola
Log
Quick Tour: Exceptions


Exceptions are used to separate normal flow of
program from error cases
Runtime exceptions:

public class HelloWorld {
public static void main( String args[] ) {
System.out.println( "Hello world"
+ args[0] );
}
}
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Quick Tour: Exceptions

Checked exceptions:


public class HelloWorld {
public static void main(String args[]) throws IOException {
FileOutputStream out = new FileOutputStream( "temp" );
out.write( args[0].getBytes() );
out.close();
}
}
Exceptions can be very messy
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Quick Tour: Exceptions

Handling exceptions:



public class HelloWorld {
public static void main( String args[] ) {
FileOutputStream out;
try {
out = new FileOutputStream( "temp" );
out.write( args[0].getBytes() );
out.close();
} catch( IOException e ) {
System.out.println( "Exception " + e );
e.printStackTrace();
}
finally { try { out.close(); } catch(Exception ee) {} }
}}
Never ignore exceptions: catch(...) {}
Easy to overdo exceptions
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Quick Tour: Packages

Name spaces for Java




package = add a class to a package
import = use classes from a package
Encapsulate a number of related classes
Used for access control


Content of file: ../se/aQute/plane/Point.java
package se.aQute. plane;
import se.aQute.basictest.*;
public class Point {
double
_x;
double
_y;
public Point() { clear(); }
...
}
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Quick Tour: Equality



Equal and identical are different concepts
Identity check is ==
Class Object has method equals(Object
method that is identity




o)
3 == 3; // YES
"three" == new String("three"); // NO
"three".equals( new String("three") ); // YES
Classes can override equals(Object o) for their
semantics

Watch hashCode() when overriding equals() !!!
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Quick Tour: toString()



toString() is a useful method for debugging
Each object inherits a default implementation
from Object
Overriding can be very, very useful during
debugging

public class Point {
. . .
public String toString() { return getX() + "," + getY(); }
. . .
}
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The Java VM


Java is compiled to byte codes
Byte codes are interpreted by the VM
File: HelloWorld.java
public class HelloWorld {
public static void main( String args[] ) {
System.out.println( "Hello world" );
}
}
javac
compiler
rt.jar
or
classes.zip
File: HelloWorld.class
0xCA 0xFE 0xBA 0xBE 0x01 0xF7 0x76 0x41 0x23
. . .
java
VM
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Hello world
Native code interface


Native code interface through JNI
Native interface defined in Java class


class Native {
int var;
public native int foo();
}
Translated via javah into C header file

#include <native.h>
typedef struct ClassNative { long var; } ClassNative;
HandleTo(Native);
extern long Native_foo(struct HNative *);
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The Java VM: The good news




Portable format allows execution on many
different computer types
Hundreds of VMs available from different
vendors
Optimized for certain applications
Inherently safe
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The Java VM: The bad news



Interpretation requires CPU cycles
Instruction set not optimized for target machines
Byte format is rather verbose
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Is Java Cool?

Nothing particularly innovative





Portable object code from Pascal (P-code!)
Syntax from C++
Object model from Smalltalk
Garbage Collection from Lisp
Reasons for success:



People were getting fed up with C++
Java looked much simpler
Applets kick started it (but no longer drive it)
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The runtime library

The runtime library is Java's best asset



Library has grown very hard



Single implementation of common code
Some implementations are pretty bad (AWT!)
From 8 packages to 77 packages!
Need for profiles
There is an amazing amount of code to be found
on the net
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The runtime library: java.lang


Basic package which is always included
Contains primitive type classes for Boolean,
Integer, Double, Float, Byte, Character, Void




number <-> string conversions
number <-> number conversions
Max/Min values
Used in reflection
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The runtime library: java.lang

Process, Runtime and System for access to
system resources






Running of external processes and linking of
external libraries
Debugging
Memory interface
Time
System properties
Utiltity functions like arraycopy
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The runtime library: java.lang

Thread, ThreadGroup for threads





A Thread is like an internal process
Run multiple threads at the same time
Combine threads in a group for security control
Monitors are used to manage shared resources
Math = Math library


Contains mathematical routines
sqrt, cos, sin, log, ln ...
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The runtime library: java.lang

Throwable


Base class for Exceptions and Error
SecurityManager for security


Performs security checks (when installed)
Access to call stack
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The runtime library: java.lang


String
Unicode!


16 bit char = 65536 possible characters
Functions

String can be concatenated with +




System.out.println( "File : " + file + " : " + exception );
substring, indexOf, trimming
Conversion from number to String
Symbols (unique value with intern() )
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The runtime library: java.lang


StringBuffer
Used to concatenate strings




Expensive:
String concat = "";
for ( int i=0; i<10; i++ ) concat = concat + i;
Less Expensive
StringBuffer sb = new StringBuffer();
for ( int i=0; i<10; i++ ) sb.append( "" + i );
String concat = sb.toString();
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The runtime library: java.io



Streams are used for byte access to files
Readers/Writers are used for Unicode access
Streams, Readers, Writers can be used as pipes





Buffering
Data access (e.g. getInt(), getShort() )
Between threads (PipeXXXXX)
Conversion from stream to reader/writer
ObjectStreams
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The runtime library: java.net

Access to the net (TCP/IP)


Stream connections: Socket, ServerSocket


Extendable: SocketImplFactory
URL, URLConnection


InetAddress
Extendable: URLStreamHandlerFactory
Datagrams

Unicast/Multicast
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The runtime library: java.util

Useful classes







Collections: Vector, Hashtable, BitSet, Properties,
Stack, Enumeration, Map, Array, Iterator
Time: Date, Calendars, TimeZones
Locale: Locale, ResourceBundles
Random
Observable
StringTokenizer
EventObject, EventListener
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The runtime library: other

java.rmi


Remote method invocation support
java.math

Big Integer (unlimited digits) for private/public key
calculations
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The runtime library: more other

java.security


java.sql


Access support to SQL databases
java.text


Classes for certificates, principals, permissions
Support for language independent messages
java.util.zip

Access to zip files which are the preferred delivery
vehicle for java applications.
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The runtime library: more other

java.util.jar


java.lang.reflect


Access to jar files and their manifest
Access to objects in runtime via reflection on their
interfaces
java.beans

Support for Java beans
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The runtime libraries: GUI





Original AWT in 1.0 was … well, awful
JDK 1.1 at start 1997 improved significantly
Netscape released lightweight GUI called IFC at
that time
SUN decided to develop their own lightweight
GUI at the end of 1997
Netscape joined them SUN team and stopped
support for IFC
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
GUI: AWT

Uses peer model



Event model:




A widget controls a native widget
Supports "native look and feel"
first based on single dispatching method
handleEvent
Today based on listeners
Layout managers
LightWeight components
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
GUI: AWT looks
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
GUI: IFC







Derived from NeXT, adopted by Netscape
Lightweight components
Very clean code, small, reliable and included in
Netscape Communicator
Internal windows, drag & drop
Event handling via strings
Powerful GUI builder called Constructor
Available (including source) but not maintained
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
GUI: IFC example, full control
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
GUI: JFC


Derived from IFC (same people [@ start])
Lightweight components, listeners





JButton top = new JButton("Top");
top.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
System.out.println("top");
}
} );
Compare Smalltalk, there it would be:
Button top = Button new: 'top'.
top action: [ Transcript print: 'top' ].
HUGE
Based on Model-View paradigm & Pluggable UI
Easier to use than it looks
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
GUI: JFC complexity, the button
L&F
...
Button
UI
Abstract
Button
Button
Model
Default
Button
Model
JButton
JToggle
Button
JRadio
Button
JCheck
Box
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
JMenu
Item
JCheckBox
MenuItem
JMenu
JRadioButton
MenuItem
JFC: The good and changing looks
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Components: Beans




Components are wrapped objects
Access via reflection
Allows runtime composition of systems (via end
users?): Visual Programming
Properties can
be set via
Methods
Events
strings
Bean
Properties
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Java Beans

Events follow the listener model


Properties are defined via methods that start with
get/set


SomeBean bean = new SomeBean();
bean.addTickEventListener(new TickEventListener() {
public void tick(TickEvent e) {
System.out.println("tick");
}});
E.g. property "tickCount"
public class SomeBean {
public long getTickCount() { … }
public void setTickCount() { … }
}
Bean programmer can override defaults with an
Introspector
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
The Bean Box
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Enterprise Java Beans





SUN's attempt to enter the enterprise computing
market
Mainframe connectivity
Application Servers
Message Queues
Transactions
EJB
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
client
Servlets





Very popular way to create WWW pages
Offers: User sessions, Parameters, Cookies
Not always easy to setup in web server
Life cycle managed by web server
A simple servlet:


import javax.servlet.http.*;
import javax.servlet.*;
public class HelloServlet extends HttpServlet {
public void doGet( HttpServletRequest rq, HttpServletResponse rsp ){
rsp.setContentType( "text/plain" );
PrintWriter out = rsp.getWriter();
out.println( "Hello world " + rq.getParameter("name") );
}
}
http://host/servlets/HelloServlet?name=peter
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Servlets
http://a.com/servlets/A?name=peter
Web
Server
Client
Mime typed data, e.g. HTML
Java
VM
HttpRequest
Servlet
A
HttpResponse
Servlet
B
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Java Server Pages





HTML pages contain embedded Java code
Uses bean standard
Beans can be page local, session local or global
Pages are pre-processed for speed
Easy to design good looking pages with standard
tools
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Distributed Programming



Remote Method Invocation RMI
Common Object Request Broker Architecture
CORBA
Voyager (ObjectSpace)
String s = foo("bar")
Process A
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Process B
RMI



Strongly based on Remote Procedure Call
Uses serialization of objects for parameters
Name server
Client
Stub
Remote
Unicast
Remote
Object
Compute
Engine
rmic
Skeleton
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Connection made via
name server
RMI


Not all objects are serializable
Code transfer awkward




Current RMI does only do class transfer via HTTP
(biggest problem in JINI)
Stub skeleton model cumbersome
All methods MUST throw RemoteException
Built in to all Java VMs
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
CORBA

Language independent standard for interprocess
communication defined by OMG
Uses Interface Description Language (IDL)
Every VM has an Object Request Broker built in
Java is a very good match for CORBA

But is it needed?
No class loading




aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
CORBA
IDL
Helper
idltojava
Holder
Client
module HelloApp {
interface Hello {
string sayHello();
};
};
Corba
Object
Stub
Compute
Skeleton
Confused?
Impl.
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Voyager





Simple implementation using proxy generation
on the fly (standardized in Java 1.3)
Runs on all Java VM's: ~270K
Does not require pre-processor
Does inline class loading
Advanced distributed even mechanism
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Database interfaces

JDBC



Traditional interface to SQL like databases
Very much like Microsoft's ODBC
OO Databases



PSE from Objectstore
POET
POS from Oracle
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Service Discovery

Discover services available on the local net


JINI


Pure java, cumbersome, big. Type based
SLP


Broadcast/Multicast, Communication
Simple
Universal PNP with SSDP

HTTP based, declarative with XML
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Media API's




Java 2D
Java 3D
Java Media Framework
JTAPI, Telephony API
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Interesting developments








JavaSpaces
Infobus
Java OS
Java shared data toolkit
Java Embedded Server / OSGi
Java mail
Java Activation Framework
……………..
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
Conclusion






Java is a simple but powerful language
It has grown too fast too big
Library support is extensive
Not all APIs are well designed
Performance is an issue
Significant improvement over C++
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
References






Java: www.javasoft.com
Java Developers Connection:
http://developer.java.sun.com
IBM source code: alphaworks.ibm.com
Voyager: www.objectspace.com
PSE Pro: www.odi.com
Links to java related:
http://www.taxon.demon.nl/JW
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
References

Java in a Nutshell


Java Secrets


David Flanagan. ISBN 1-56592-183-6
Elliote Rusty Harold.ISBN 0-7645-8007-8
Java 2 Performance and idiom guide

Craig Larman, Rhett Guthrie. ISBN 0-13-014260-3
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON
References

The Java Virtual Machine Specification


Java Security


Scott Oaks. ISBN 1-56592-403-7
Java Developers Almanac


Tim Lindholm, Frank Yellin, ISBN 0-201-63452-X
Patrick Chan. ISBN 0-201-37967-8
Late night IFC

Jason Beaver, Jamie Costa, Jason Wehling. ISBN 156276-540-X
aQute Copyright © 1999 All rights reserved presentation 10/01/2000 ERICSSON