|
Plattformunabhängigkeit | Bytecode |
Sicherheit | Sandbox der Applets, Bytecodeverifizierung ExceptionHandling |
Einfachheit für Programmierer und Anwender | Anlehnung an C++ Gut stukturierte Klassenbibo Einheitliches Look&Feel |
1.02: Compiler, Interpreter, Appletviewer, Dokumentierer,
Decompilierer, Header-Generator, Debugger
1.1: Jartools, Keygenerator, RMIRegistryServer
1.2: Neuer Javadoc, Servletrunner, ORB-Server
Jede Java Klasse gehört einem Package an. Packages sorgen für logische Ordnung der Klassen. Außerdem wird eine übersichtlichere Programmierung möglich.
Name | 1.0 | 1.1 | 1.2 | Beschreibung |
applet | x | x | x | Klasse Applet |
awt | x | x | x | GUI Komponenten |
awt.accessibility | x | Funtionalität für Behinderte | ||
awt.color | x | ICC-Farbverwaltung | ||
awt.datatransfer | x | x | Clipboard (auch native) | |
awt.dnd | x | Drag&Drop | ||
awt.event | x | x | Delegation Event Model | |
awt.font | x | Graphische Textmanipulation | ||
awt.geom | x | Beschreibung von 2D Figuren (Ellipse, Polygon, Rechteck, ...) | ||
awt.im | x | Input Methods | ||
awt.image | x | x | x | Bildbearbeitung (in 1.2 erheblich verbessert) |
awt.print | x | Drucklayouts (Drucken selbst geht mit java.awt.PrintJob) | ||
awt.swing | x | Java-Foundation-Classes von Netscape und Sun (GUI) | ||
awt.swing.basic | x | Einfacher Look and Feel | ||
awt.swing.beaninfo | x | Beaninfo Klassen für Swing Komponenten | ||
awt.swing.border | x | Klassen für Rahmen um GUI-Elemente | ||
awt.swing.event | x | Events für Swing | ||
awt.swing.jlf | x | Java Look and Feel | ||
awt.swing.motif | x | Motif Look and Feel | ||
awt.swing.multi | x | Windows Look and Feel | ||
awt.swing.plaf | x | Plugable Look&Feel | ||
awt.swing.table | x | Tabellen Klassen | ||
awt.swing.target | x | "Zielverwaltung" | ||
awt.swing.text | x | Klassen für Texteditoren | ||
awt.swing.undo | x | Undo-Klassen | ||
awt.peer | x | Native-Peers der GUI-Elemente | ||
beans | x | JavaBeans Package (GUI-Elemente) | ||
beans.beancontext | x | Container für Beans | ||
io | x | x | x | generelle IO-Operationen, Streams |
lang | x | x | x | Standardpackage: Wrapper, String, Thread, Object, System, Runtime |
lang.ref | x | Weak references | ||
lang.reflect | x | x | Reflection API | |
math | x | x | BigDecimal, BigInteger | |
net | x | x | x | Netzwerk: Sockets, URL, InetAddress |
rmi | x | x | Remote Method Invocation | |
rmi.activation | x | Aktivierung von Objekten durch RMI | ||
rmi.dgc | x | x | Distributed Garbage Collection | |
rmi.registry | x | x | RMI Registry (als Klasse für rmiregistry) | |
rmi.server | x | x | Serverklassen für RMI | |
security | x | x | Security-API (in 1.2 erweitert) | |
security.acl | x | x | Verwaltung von Access Control Lists | |
security.cert | x | Zertifikate | ||
security.interfaces | x | x | DSA Interfaces (Keys) | |
security.spec | x | x | Spezifikationen für Security Algorithmen | |
sql | x | x | SQL-Anbindung | |
text | x | x | Internationale Formatierungen und Vergleiche | |
util | x | x | x | Vektoren, Datum, BitSet, ... (ständig erweitert) |
util.jar | x | Arbeit mit JARs (Java Archieves) | ||
util.mime | x | Mime-Typ (u.a. für Clipboard) | ||
util.zip | x | x | Zugriff auf Zip-Files sowie Komprimierung und CRC | |
org.omg.* | x | CORBA Implementation und ORB |
InputStream | OutputStream | Reader | Writer | |
Quellenorientiert | ||||
File | FileInputStream | FileOutputStream | FileReader | FileWriter |
Byte/Char-Array | ByteArrayInputStream | ByteArrayOutputStream | CharArrayReader | ByteArrayWriter |
Pipes | PipedInputStream | PipedOutputStream | PipedReader | PipedWriter |
String | StringBufferInputStream | - (StringBuffer verwenden) | StringReader | StringWriter |
Stream | - | - | InputStreamReader | OutputStreamWriter |
Sockets, URLs, Zips, Processe | Liefern Instanzen von Input/OutputStreams zurück | |||
Übertragungsorientiert | ||||
Bufferung | BufferedInputStream | BufferedOutputStream | BufferedReader | BuferedWriter |
Zeilenorientiert | LineNumberInputStream | - | LineNumberReader | - |
Pushback | PushbackInputStream | - | PushbackReader | - |
Deflate | DeflateInputStream | DeflateOutputStream | - | - |
Zip | ZipInputStream | ZipOutputStream | - | - |
GZip | GZipInputStream | GZipOutputStream | - | - |
Digest (security) | DigestInputStream | DigestOutputStream | - | - |
Sequentiell | SequenceInputStream | - | - | - |
Formatorientiert | ||||
Java-Datentypen | DataInputStream | DataOutputStream PrintStream |
- | - |
Objekte | ObjectInputStream | ObjectOutputStream |
//Achtung: Keinerlei Exception-Handling!! //Socket erzeugen
Socket sock = new Socket(hostName, port); // oder InetAddress host = InetAddress.getByName(hostName); Socket sock = new Socket(host, port);
//Streams an Socket binden
DataOutputStream dos = new DataOutputStream(sock.getOutputStream()); DataInputSream dis = new DataInputStream(sock.getInputStream());
//lesen mit
xxx = dis.readXXX();
//schreiben mit
dos.writeXXX(xxx);
//Achtung: Keinerlei Exception-Handling!! //ServerSocket erzeugen
ServerSocket serv = new ServerSocket(port);
//einmal auf Client warten -> Single-Client-Server
Socket client = serv.accept();
//Streams an Socket binden
DataInputSream dis = new DataInputStream(client.getInputStream()); DataOutputStream dos = new DataOutputStream(client.getOutputStream());
//Alternative für Multiclient-Server
while (true) { Socket client = serv.accept(); new ClientHandlerThread(client).start(); //Sockets binden und Kommunikation im Thread }
//Achtung: Eingeschränkt vollständiges Exception-Handling!! //Socket erzeugen
Socket sock = new Socket(hostName, port); // oder InetAddress host = InetAddress.getByName(hostName); Socket sock = new Socket(host, port);
//Streams an Socket binden
ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream()); ObjectInputSream ois = new ObjectInputStream(sock.getInputStream());
//lesen mit
try { Object o = ois.readObject(); } catch (ClassNotFoundExceptin ex1) { //die übermittelte Klasse wurde nicht gefunden } catch (InvalidClassException ex2) { //etwas mit der Klasse stimmt nicht } catch (OptionalDataException ex3) { //Java-Primitive wurden gefunden, obwohl Objekt erwartet wurde } catch (IOExcpetion ex4) { //Irgendwas anderes ging schief }
//schreiben mit
try { oos.writeObject(o); } catch (InvalidClassException ex1) { //etwas mit der Klasse stimmt nicht } catch (NoSerializableException ex2) { //Objekt kann nicht serialisiert werden } catch (IOExcpetion ex3) { //Irgendwas anders ist nicht in Ordnung }
//Achtung: Keinerlei Exception-Handling!! //ServerSocket erzeugen
ServerSocket serv = new ServerSocket(port);
//einmal auf Client warten -> Single-Client-Server
Socket client = serv.accept();
//Streams an Socket binden
ObjectInputSream ois = new ObjectInputStream(client.getInputStream()); ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
//Alternative für Multiclient-Server
while (true) { Socket client = serv.accept(); new ClientHandlerThread(client).start(); //Sockets binden und Kommunikation im Thread }
FileOutputStream ostream = new FileOutputStream("t.tmp"); ObjectOutputStream p = new ObjectOutputStream(ostream); p.writeInt(12345); p.writeObject("Today"); p.writeObject(new Date()); p.flush(); ostream.close();
FileInputStream istream = new FileInputStream("t.tmp"); ObjectInputStream p = new ObjectInputStream(istream); int i = p.readInt(); String today = (String)p.readObject(); Date date = (Date)p.readObject(); istream.close();
Interface der remote aufrufbaren Klasse beschreiben. Muß java.rmi.Remote erweitern.
public interface Manager extends java.rmi.Remote { String getName() throws java.rmi.RemoteException; Date getDate() throws java.rmi.RemoteException; int calculate(int a, double b, Long c) throws java.rmi.RemoteException; }
Implementation für das Interface schreiben.
public ManagerImpl extends java.rmi.server.UnicastRemoteObject implements Manager {
String name = null;
public ManagerImpl (String aName) throws java.rmi.RemoteException { name = aName; }
public String getName () throws java.rmi.RemoteException { return name; }
//....
}
Einen Server schreiben.
public class RMIServer {
public static void main (String args[]) { //neuen Security Manager einstellen System.setSecurityManager(new java.rmi.RMISecurityManager());
try { //RMI-Objekt erzeugen ManagerImpl obj = new ManagerImpl("Manager"); //an Registry binden Naming.rebind("/ManagerServer", obj); System.out.println("ManagerServerbound in registry"); } catch (Exception e) { System.out.println("ManagerServer err: " + e.getMessage()); e.printStackTrace(); }
}
Verwendung des RMI-Servers im Client (Applet oder Application).
Manager remoteManager = null;
public void initRMI() { try { String hostName = (isApplet)?getCodeBase().getHost():"anyHost": remoteManager = (Manager)Naming.lookup("//" + hostName + "/ManagerServer"); } catch (Exception e) { System.out.println("ManagerClient exception: " + e.getMessage()); e.printStackTrace(); } }
public void useRMI() { try { System.out.println(remoteManager.getName()); System.out.println(remoteManager.getDate()); System.out.println(remoteManager.calculate(2, 3.4, new Long(4352342342))); } catch (RemoteException e) { System.err.println(e); } }
Compilierung
OMG-IDL Beschreibung (hello.idl) des Objektes schreiben:
module HelloApp { interface Hello { string sayHello(); }; };
Hello.idl mit idltojava compilieren -> Java-Files zur Weiterbearbeitung
Server schreiben:
import HelloApp.*; import org.omg.CosNaming.*; import org.omg.CosNaming.NamingContextPackage.*; import org.omg.CORBA.*; class HelloServant extends _HelloImplBase { public String sayHello() { return "\nHello world !!\n"; } } public class HelloServer { public static void main(String args[]) { try{ // create and initialize the ORB ORB orb = ORB.init(args, null); // create servant and register it with the ORB HelloServant HelloRef = new HelloServant(); orb.connect(HelloRef); // get the root naming context org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); NamingContext ncRef = NamingContextHelper.narrow(objRef); // bind the Object Reference in Naming NameComponent nc = new NameComponent("Hello", ""); NameComponent path[] = {nc}; ncRef.rebind(path, HelloRef); // wait for invocations from clients java.lang.Object sync = new java.lang.Object(); synchronized (sync) { sync.wait(); } } catch (Exception e) { System.err.println("ERROR: " + e); e.printStackTrace(System.out); } } }
Client als Applet oder Application schreiben:
import HelloApp.*; import org.omg.CosNaming.*; import org.omg.CORBA.*; public class HelloClient { public static void main(String args[]) { try{ // create and initialize the ORB ORB orb = ORB.init(args, null); // get the root naming context org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); NamingContext ncRef = NamingContextHelper.narrow(objRef); // resolve the Object Reference in Naming NameComponent nc = new NameComponent("Hello", ""); NameComponent path[] = {nc}; Hello HelloRef = HelloHelper.narrow(ncRef.resolve(path)); // call the Hello server object and print results String hello = HelloRef.sayHello(); System.out.println(hello); } catch (Exception e) { System.out.println("ERROR : " + e) ; e.printStackTrace(System.out); } } }[TOP]
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; /** * A sample single-threaded servlet that takes input from a form * and writes it out to a file. It is single threaded to serialize * access to the file. After the results are written to the file, * the servlet returns a "thank you" to the user. * * <p>You can run the servlet as provided, and only one thread will run * a service method at a time. There are no thread synchronization * issues with this type of servlet, even though the service method * writes to a file. (Writing to a file within a service method * requires synchronization in a typical servlet.) * * <p>You can also run the servlet without using the single thread * model by removing the <tt>implements</tt> statement. Because the * service method does not synchronize access to the file, multiple * threads can write to it at the same time. When multiple threads try * to write to the file concurrently, the data from one survey does not * follow the data from another survey in an orderly fashion. * * <p>To see interaction (or lack of interaction) between threads, use * at least two browser windows and have them access the servlet as * close to simultaneously as possible. Expect correct results (that * is, expect no interference between threads) only when the servlet * implements the <code>SingleThreadedModel</code> interface. */ public class SurveyServlet extends HttpServlet implements SingleThreadModel { String resultsDir; public void init(ServletConfig config) throws ServletException { super.init(config); resultsDir = getInitParameter("resultsDir"); if (resultsDir == null) { Enumeration initParams = getInitParameterNames(); System.err.println("The init parameters were: "); while (initParams.hasMoreElements()) { System.err.println(initParams.nextElement()); } System.err.println("Should have seen one parameter name"); throw new UnavailableException (this, "Not given a directory to write survey results!"); } } /** * Write survey results to output file in response to the POSTed * form. Write a "thank you" to the client. */ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // first, set the "content type" header of the response res.setContentType("text/html"); //Get the response's PrintWriter to return text to the client. PrintWriter toClient = res.getWriter(); try { //Open the file for writing the survey results. String surveyName = req.getParameterValues("survey")[0]; FileWriter resultsFile = new FileWriter(resultsDir + System.getProperty("file.separator") + surveyName + ".txt", true); PrintWriter toFile = new PrintWriter(resultsFile); // Get client's form data & store it in the file toFile.println("<BEGIN>"); Enumeration values = req.getParameterNames(); while(values.hasMoreElements()) { String name = (String)values.nextElement(); String value = req.getParameterValues(name)[0]; if(name.compareTo("submit") != 0) { toFile.println(name + ": " + value); } } toFile.println("<END>"); //Close the file. resultsFile.close(); // Respond to client with a thank you toClient.println("<html>"); toClient.println("<title>Thank you!</title>"); toClient.println("Thank you for participating"); toClient.println("</html>"); } catch(IOException e) { e.printStackTrace(); toClient.println( "A problem occured while recording your answers. " + "Please try again."); } // Close the writer; the response is done. toClient.close(); } }[TOP]