1 / 78

Review and Misc Topics

Learn about the basics of Java applets, including security issues and restrictions for untrusted applets. Explore sample applets provided with the JDK for interactive demonstrations.

gmccusker
Download Presentation

Review and Misc Topics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Review and Misc Topics CISC 6795, Spring 2011

  2. Outline • A couple of misc topics: • Basics of Java Applet • enum class • Packaging • Review of key concepts

  3. Introduction • Applets: Java programs that can be embedded in HyperText Markup Language (HTML) documents • Applet container: the browser that executes an applet • Applets are downloaded by browser • Applets are executed by Web browsers with embedded Java Virtual Machines (VMs) and runtime class libraries. • Applets are Java's most pervasive version of mobile code

  4. Security Issues on running Applet • Programs running on a personal computer usually have unlimited access to the machine's resources • e.g., ActiveX controls are omnipotent. • Java applets retrieved from Web have been written by someone else, you should not trust them to perform with integrity. • By default, Java downloaded from the Net is automatically considered untrusted code. • To ensure that untrusted code does nothing mischievous, it is important to limit what that untrusted code can do.

  5. Restriction on untrusted applet • An untrusted applet is not allowed to: • Read /write /delete /rename/obtain information about files on client file system. • Create/list a directory on client file system, check to see whether a file exists. • Create a network connection to any computer other than host from which it originated. • Listen for or accept network connections on any port on client system. • Create a top-level window without an untrusted window banner. • Obtain user's username or home directory name • Run any program on client system using Runtime.exec() methods. • Make Java interpreter exit, using either System.exit() or Runtime.exit(). • Load dynamic libraries on client system using load() or loadLibrary() methods of Runtime or System classes. • Create or manipulate any thread that is not part of same ThreadGroup as the applet. • ….

  6. Sample Applets Provided with the JDK • Demonstration applets provided with the JDK • Demonstration programs are located in directory demo • Default location in Windows:C:\Program Files\Java\jdk1.5.0\demo • Default location in UNIX/Linux/Mac OS X:the directory in which you install the JDK followed by jdk1.5.0/demo • JDK and the demos can be downloaded from the Sun Microsystems Java Web site • java.sun.com/j2se/5.0/

  7. TicTacToe applet • play Tic-Tac-Toe against the computer • Run applet with appletviewer command • In Command Prompt window , change directories to subdirectory TicTacToe • Type command appletviewerexample1.html • To play again • Click the Applet menu • Select the Reload menu item • To terminate the appletviewer • Click the Applet menu • Select the Quit menu item

  8. DrawTest applet • Allows you to draw lines and points in different colors • Run the applet with the appletviewer command • Change directories to subdirectory drawTest • Type command appletviewerexample1.html • Drag the mouse across the applet to draw lines • Select a color by clicking one of the radio buttons at the bottom of the applet • Select from red, green, blue, pink, orange and black • Change the shape to draw from Lines to Points by selecting Points from the combo box • Select Reload from the Applet menu to start a new drawing

  9. Drag the mouse in the white area to draw. SelectLinesor Points from the combo box to specify what will be drawn when you drag the mouse. Select the drawing color by clicking one of the radio buttons. DrawTest applet

  10. Simple Java Applet: Drawing a String • Creating applet class • An applet container can create only objects of classes that are public and extend JApplet • An applet container expects every Java applet class to have methods named init, start, paint, stop and destroy • These methods are inherited from class JApplet and can be overridden • When an applet container loads an applet class, the container creates an object of the class then calls methods init, start and paint

  11. Outline Import Graphics and JApplet Class WelcomeApplet extends class JApplet Call the superclass version of method paint Use Graphics method drawString to draw Welcome to Java Programming! • Overriding method paint for drawing • applet container calls method paint with a Graphics object as an argument to tell the applet where to draw

  12. WelcomeAppletexecuting in the appletviewer x-axis y-axis Upper-left corner of drawing area is location (0, 0). Drawing area extends from below the Applet menu to above the status bar. x- coordinates increase from left to right. y-coordinates increase from top to bottom. Appletmenu Status bar mimics what would be displayed in the browser’s status bar as the applet loads and begins executing. Pixel coordinates (25, 25) at which the string is displayed WelcomeAppletexecuting in Microsoft Internet Explorer Upper-leftcorner of drawing area Pixel coordinate (25, 25) Status bar

  13. Executing an Applet in appletviewer • Applets are embedded in Web pages for execution in an applet container • Before executing applet, must create an HTML document that specifies which applet to execute • Most HTML elements are delimited by pairs of tags • All HTML tags begin with <, and end with > • Starting tag: <html>, <table>, … • Ending tag: </html>, </table>,… • Attributes can be specified for HTML elements • E.g., <font color=red> Attention </font> • E.g., <img src=“./logo.gif” width=100 height=100></img>

  14. WelcomeApplet.html loads WelcomeApplet into an applet container. Applet element attributes Specify an applet element • An applet should generally be less than 1024 pixels wide and 768 pixels tall—dimensions supported by most computer screens. • Forgetting ending </applet> tag prevents applet from executing in some applet containers.

  15. Error-Prevention Tip • Test your applets in the appletviewer applet container before executing them in a Web browser. Browsers often save a copy of an applet in memory until all the browser’s windows are closed. If you change an applet, recompile it, then reload it in your browser, the browser may still execute the original version of the applet. Close all your browser windows to remove the old applet from memory. Open a new browser window and load the applet to see your changes.

  16. Executing an Applet in a Web Browser • To execute an applet in Internet Explorer: • Select Open… from the File menu • Click the Browse… button • Locate the directory containing the HTML document for the applet you wish to execute • Select the HTML document • Click the Open button • Click the OK button

  17.  Executing an Applet in a Web Browser (Cont.) • If your applet executes in the appletviewer but not in your Web browser • Java may not be installed and configured for your browser • Visit the Web site java.com and click the GetItNow button to install Java for your browser • You may need to manually configure Internet Explorer to use J2SE 5.0 • Click the Tools menu • Select InternetOptions… • Click the Advanced tab • Check the “Use JREv1.5.0 for <applet> (requires restart)” option • Click OK • Close all browser windows before attempting to execute another applet in the browser

  18. JApplet life cycle methods • called by an applet container during an applet’s execution • public void init(): • public void start(): • public void paint( Graphics g ), • public void stop(), • public void destroy() • Declaring methods init, start, paint, stop or destroy with method headers that differ from above results in methods that will not be called by applet container.

  19. JApplet life cycle methods: init • public void init(): called once by applet container when applet is loaded for execution • initializes an applet: initializing fields, creating GUI components, loading sounds to play, loading images to display and creating threads • The only statements that should be placed in an applet’s init method are those that should execute only once when the applet is initialized.

  20. JApplet life cycle methods: start • public void start(): called after method init completes execution. If user browses to another Web site and later returns to the applet’s HTML page, method start is called again. • Actions performed here might include starting an animation or starting other threads of execution

  21. JApplet life cycle methods : paint • public void paint( Graphics g ), called by applet container after methods init and start, or when applet needs to be repainted. • Graphics object g that is passed by applet container. • E.g., if user covers applet with another open window on the screen and later uncovers the applet • Typical actions : drawing using g

  22. JApplet life cycle methods : stop, destroy • public void stop(), called by applet container when user leaves applet’s Web page (browsing to another Web page) • User might return later, stop is used to suspend applet’s execution: to avoid using computer processing time when it is not displayed • Typical actions: stop execution of animations and threads. • public void destroy(), called by applet container when applet is being removed from memory, • when user exits browser session (i.e., closing all browser windows), or at browser’s discretion when user navigates to other Web pages. • Actions performed: clean up resources allocated to applet.

  23. AdditionApplet • Computes sum of two values input by user and displays result • Difference from Java programs seen so far: • Input/output are not through the terminal

  24. Declare instance variable sum of type double init method called once when the container loads this applet • sum is stored in an instance variable of class AdditionApplet,so it can be used in both method init and method paint

  25. Sum the values and assign the result to instance variable sum Call drawString to display sum

  26. Outline

  27. Enumerations • enum types: declared with an enum declaration • A comma-separated list of enum constants • Declares an enum class with following restrictions: • enum types are implicitly final • enum constants are implicitly static • Attempting to create an object of an enum type with new is a compilation error • enum constants can be used anywhere constants can • enum constructor • Like class constructors, can specify parameters and be overloaded

  28. Outline Declare sixenumconstants Arguments to pass to the enum constructor Declare instance variables Declare enum constructor Book In enum declaration, enum constants must be declared before constructors, fields and methods.

  29. Outline

  30. enum class static methods • static method values • Generated by compiler for every enum class • Returns an array of the enum’s constants in the order in which they were declared • static method range of class EnumSet • Takes two parameters, first and last enum constants in desired range • Returns an EnumSet containing constants in that range, inclusively • An enhanced for statement can iterate over an EnumSet as it can over an array

  31. Outline Enhanced for loop iterates for each enum constant in array returned by value Enhanced for loop iterates for each enum constant in EnumSet returned by method range

  32. final Instance Variables • final instance variables, variables that are not modifiable, e.g., • private final string title; • can be initialized at their declaration • If they are not initialized in their declarations, they must be initialized in all constructors (otherwise, compilation error) • Principle of least privilege • Code should have only privilege of access it needs to accomplish its task, but no more • Declaring an instance variable as final helps enforce principle of least privilege • If an instance variable should not be modified, declare it to be final to prevent modification.

  33. Outline Declare final instance variable Initialize final instance variable inside a constructor

  34. Outline Create an Increment object Call method addIncrementToTotal

  35. final static fields • If a final field is initialized in its declaration, then it should also be declared static • Once it’s initialized (in its declaration), its value can never change => not necessary to have separate copy of the field for every object of the class. • Making it static enables all objects of class to share the final field.

  36. Package for organizing codes • So far, we put all java files for our small project in one single directory. • By default, Java searches for classes under current directory… • For bigger projects, there are a large number of files, putting all into same directory would be a nightmare for us. • In Java, we can avoid this sort of problem by using Packages. • Organize files into different directories according to their functionality, usability as well as category they should belong to • E.g. a directory named "ui“ for files related to user interface; a directory called "engine“ for files related to core functionality

  37. Sun JDK Packages • files in one directory (or package) have different functionality from those of another directory. • Files in java.io package do something related to I/O • Files in java.net package deal with Network.

  38. Package avoid name collision • Packaging help to avoid class name collision when we use same class name as that of others. • E.g., if we have a class name called "Vector", its name would crash with Vector class from JDK. • JDK use java.util as a package name for Vector class (java.util.Vector). • Our Vector class can be named as "Vector" and put it into another package like com.mycompany.Vector • Using package: ease of maintenance, organization, and increase collaboration among developers.

  39.  Creating Packages • Add a package declaration to the source-code file • Must be the very first executable statement in the file • package name should consist of your Internet domain name in reverse order followed by other names for the package • example: com.deitel.jhtp6.ch08 • package name is part of the fully qualified class name • Distinguishes between multiple classes with the same name belonging to different packages • Prevents name conflict (also called name collision) • Class name without package name is the simple name

  40. Outline package declaration Time1 is a public class so it can be used by importers of this package

  41. Outline

  42. Creating Packages (Cont.) • Create subdirectories to represent package hierarchy of class • E.g., put Time1.java file in directory com/deitel/jhtp6/ch08, and compile it • Or use javac -d option to set destination directory • -ddirectory If a class is part of a package, javac puts class file in a subdirectory reflecting package name, creating directories as needed. • e.g., if -d c:\myclasses is used to compile a class named com.mypackage.MyClass, then class file is saved in c:\myclasses\com\mypackage\MyClass.class. • Without -d option, javac puts class file in same directory as source file.

  43. Import Packages • Import package or class into a program • Single-type-import declaration: imports a single class • Example: importjava.util.Random; • Type-import-on-demand declaration: imports all classes in a package • Example: importjava.util.*;

  44. Outline Single-type import declaration Refer to the Time1 class by its simple name

  45. Using Packages • Class loader: locates classes that compiler needs • First searches standard Java classes bundled with the JDK • Then searches for optional packages • These are enabled by Java’s extension mechanism • Finally searches classpath • List of directories or archive files separated by directory separators • These files normally end with .jar or .zip • Standard classes are in the archive file rt.jar • To specify classpath • -classpath option for javac compiler • java -classpath C:\java\MyClasses;C:\java\OtherClasses • Set CLASSPATH environment variable using set command

  46. Using Packages • JVM must locate classes just as the compiler does • The java command can use other classpathes by using the same techniques that the javac command uses • Specifying an explicit classpath eliminates current directory from classpath, i.e., classes in current directory (including packages in current directory) cannot be loaded • Include a dot (.) in classpath to specify current directory.

  47. Package Access • Methods and variables declared without any access modifier are given package access • This has no effect if program consists of one class • If program contains multiple classes from same package • Package-access members can be directly accessed through appropriate references to objects in other classes belonging to same package

More Related