Java Programing

June 17, 2007

That’s better, but suppose that the application actually

Filed under: Java Programming — webmaster @ 5:23 pm

That’s better, but suppose that the application actually has a legitimate reason to make its network connection. We’d like to leave the default security manager in place, just to be safe, but we’d like to grant this application permission to make a network connection. 3.2.2 The policytool Utility To permit our EvilEmpire example to make a network connection, we need to create a policy file that contains the appropriate permission. A handy utility called policytool , included in SDK 1.2 and later, helps you make policy files. Fire it up from a command line like this: C:> policytool You may get an error message when policytool starts up about not finding a default policy file. Don’t worry about this; just click OK to make the message go away. We want to add a network permission for the EvilEmpire application. The application is identified by its origin, also called a codebase . A codebase is described by a URL. In this case, it will be a file: URL that points to the location of the EvilEmpire application on your disk. If you started up policytool, you should be looking at its main window, shown in Figure 3.2. Click on Add Policy Entry. Another window pops up, like the one shown in Figure 3.3 (but with the fields empty). Figure 3.2. The policytool window Figure 3.3. Adding a policy entry First, fill in the codebase with the URL of the directory containing EvilEmpire as shown in the figure. Then click on Add Permission. Yet another window pops up, shown in Figure 3.4. Figure 3.4. Creating a new permission - 57

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services

malicious program from disabling your computer or erasing

Filed under: Java Programming — webmaster @ 7:24 am

malicious program from disabling your computer or erasing data on your disk? Most computing platforms have no answer for these questions. Java 2 offers powerful ways to limit the actions of running code. Before Java 2, much of the buzz about security had to do with the security of applets. The applet ran with security restrictions that prevented the applet from doing questionable things like reading from or writing to the disk or contacting arbitrary computers on the network. In Java 2, it’s just as easy to apply applet-style security to applications. Furthermore, it’s easy to fine-tune the access you allow applications. For example, you can allow an application to access the disk, but only in a specific directory, or you can allow network access to certain addresses. Why is this important? Let’s suppose that you need a certain application, like a calendar or an address manager. You go to your favorite Internet search engine and find a promising-looking Java application that does just what you want. You download and run it. But it’s entirely possible that what you’ve downloaded is not what you wanted. It could be a computer virus that infects your computer. Or it could simply be a malicious program that erases files from your disk. In this case, it would have been a really good idea to restrict the application’s actions. 3.2.1 The Default Security Manager You can use an option of the java interpreter to install a default security manager. This security manager enforces many of the same rules as for applets. To see how this works, let’s write a little program that does something questionable, making a network connection to some computer on the Internet. (We’ll cover the specifics of network programming later, in Chapter 11 and Chapter 12.) //file: EvilEmpire.javaimport java.net.*; public class EvilEmpire { public static void main(String[] args) throws Exception{ try { Socket s = new Socket(”207.46.131.13″, 80); System.out.println(”Connected!”); } catch (SecurityException e) { System.out.println(”SecurityException: could not connect.”); } } } If you just run this program with the Java interpreter, it will make the network connection: C:> java EvilEmpireConnected! C:> This is kind of scary. Let’s install the default security manager, like this: C:> java -Djava.security.manager EvilEmpireSecurityException: could not connect. C:> - 56

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services

June 16, 2007

The interpreter searches for the class in the

Filed under: Java Programming — webmaster @ 6:31 pm

The interpreter searches for the class in the class path , a list of directories where packages of classes are stored. We’ll discuss the class path in detail in the next section. The class path is typically specified by an environment variable, which you can override with the command-line option -classpath . After loading the class specified on the command line, the interpreter executes the class’s main( ) method. From there, the application can start additional threads, reference other classes, and create its user interface or other structures, as shown in Figure 3.1. Figure 3.1. Starting a Java application The main( ) method must have the right method signature . A method signature is a collection of information about the method, like a C prototype or a forward function declaration in other languages. It includes the method’s name, type, and visibility, as well as its arguments and return type. The main( ) method must be a public, static method that takes an array of String objects as its argument and does not return any value (void): public static void main ( String [] myArgs ) Because main( ) is a public and static method, it can be accessed directly from another class using the name of the class that contains it. We’ll discuss the implications of visibility modifiers such as public and the meaning of static in through Chapter 6. The main( ) method’s single argument, the array of String objects, holds the command-line arguments passed to the application. As in C, the name that we give the parameter doesn’t matter; only the type is important. Unlike C, the content of myArgs is a true array. There’s no need for an argument count parameter, because myArgs knows how many arguments it contains and can happily provide that information: int argc = myArgs.length; Java also differs from C in another respect here: myArgs[0] is the first command-line argument, not the name of the application. If you’re accustomed to parsing C command-line arguments, you’ll need to be careful not to trip over this difference. The Java interpreter continues to run until the main( )method of the initial class file has returned, and until any threads that it started are complete. Special threads designated as “daemon” threads are silently killed when the rest of the application has completed. .2 Policy Files Java 2 provides a simple mechanism for protecting your computer from evil programs like viruses. If you download a program from somewhere on the Internet, how can you prevent it from stealing information on your computer and sending it back out into the Internet? How can you prevent a - 55

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services

You have many options for Java development environments,

Filed under: Java Programming — webmaster @ 6:29 am

You have many options for Java development environments, from the traditional text-editor-andcommand- line environment to IDEs like WebGain’s Visual Caf , Inprise’s JBuilder, Tek-Tools’ KAWA, or Sun’s Forte for Java. The examples in this book were developed using the Solaris and Windows versions of the Java Software Development Kit (SDK), so we will describe those tools here. When we refer to the compiler or interpreter, we’ll be referring to the command-line versions of these tools, so the book is decidedly biased toward those of you who are working in a Unix or DOS-like environment with a shell and filesystem. However, the basic features we’ll be describing for Sun’s Java interpreter and compiler should be applicable to other Java environments as well. In this chapter, we’ll describe the tools you’ll need to compile and run Java applications. The last part of the chapter discusses how to pack Java class files into Java archives ( JAR files). Chapter 20, describes the ability to “sign” classes within a JAR file, and to give greater privileges to classes with a signature that you trust. 3.1 The Java Interpreter A Java interpreter is software that implements the Java virtual machine and runs Java applications. It can be a standalone application like the SDK’s java program, or part of a larger application like the Netscape Navigator web browser. It’s likely that the interpreter itself is written in a native, compiled language for your particular platform. Other tools, like Java compilers and development environments, can be written in Java (and should be, we’d argue, in order to maximize the portability of the Java development environment). Sun’s Forte for Java is one example of a pure- Java IDE. The Java interpreter performs all of the activities of the Java runtime system. It loads Java class files and interprets the compiled byte-code. It verifies compiled classes that are loaded from untrusted sources. In an implementation that supports dynamic, or just-in-time, compilation, the interpreter also serves as a specialized compiler that turns Java byte-code into native machine instructions. Throughout the rest of this book, we’ll be building both standalone Java programs and applets. Both are kinds of Java applications run by a Java interpreter. The difference is that a standalone Java application has all of its parts; it’s a complete program that runs independently. An applet is more like an embeddable program module. The Java interpreter can’t run an applet directly, because it is used as part of a larger application. To run an applet, you can use a web browser like Sun’s HotJava or Netscape Navigator, or the appletviewer tool that comes with the SDK. Both HotJava and appletviewer are standalone Java applications run directly by the Java interpreter; these programs implement the additional structure needed to run Java applets. Sun’s Java interpreter is called java. In a standalone Java application, one class includes a main( ) method, which contains the statements to be executed upon startup. To run the application, execute the interpreter, specifying that class as an argument. You can also specify options to the interpreter, as well as arguments to be passed to the application: % java [interpreter options ] class_name [program arguments ] The class should be specified as a fully qualified class name, including the package name, if any. Note, however, that you don’t include the .class file extension. Here are a few examples: % java animals.birds.BigBird% java test - 54

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services

June 15, 2007

So, why do we need a try/catch clause

Filed under: Java Programming — webmaster @ 8:01 pm

So, why do we need a try/catch clause in the run( ) method? What kind of exception can Thread’s sleep( ) method throw and why do we care about it, when we don’t seem to check for exceptions anywhere else? Under some circumstances, Thread’s sleep( ) method can throw an InterruptedException , indicating that it was interrupted by another thread. Since the run( ) method specified in the Runnable interface doesn’t declare it can throw an InterruptedException, we must catch it ourselves, or the compiler will complain. The try/catch statement in our example has an empty catch clause, which means that it handles the exception by ignoring it. In this case, our thread’s functionality is so simple it doesn’t matter if it’s interrupted. All of the other methods we have used either handle their own exceptions or throw only general-purpose exceptions that are assumed to be possible everywhere and don’t need to be explicitly declared. 2.4.7 A Word About Synchronization At any given time, there can be a number of threads running in the Java runtime system. Unless we explicitly coordinate them, these threads will be executing methods without any regard for what the other threads are doing. Problems can arise when these methods share the same data. If one method is changing the value of some variables at the same time that another method is reading these variables, it’s possible that the reading thread might catch things in the middle and get some variables with old values and some with new. Depending on the application, this situation could cause a critical error. In our HelloJava examples, both our paintComponent( ) and mouseDragged( ) methods access the messageX and messageY variables. Without knowing the implementation of our particular Java environment, we have to assume that these methods could conceivably be called by different threads and run concurrently. paintComponent( ) could be called while mouseDragged( ) is in the midst of updating messageX and messageY. At that point, the data is in an inconsistent state and if paintComponent( ) gets lucky, it could get the new x value with the old y value. Fortunately, in this case, we probably would not even notice if this were to happen in our application. We did, however, see another case, in our changeColor( ) and currentColor( ) methods, where there is the potential for a more serious “out of bounds” error. The synchronized modifier tells Java to acquire a lock for the class that contains the method before executing that method. Only one method can have the lock on a class at any given time, which means that only one synchronized method in that class can be running at a time. This allows a method to alter data and leave it in a consistent state before a concurrently running method is allowed to access it. When the method is done, it releases the lock on the class. Unlike synchronization in other languages, the synchronized keyword in Java provides locking at the language level. This means there is no way that you can forget to unlock a class. Even if the method throws an exception or the thread is terminated, Java will release the lock. This feature makes programming with threads in Java much easier than in other languages. See Chapter 8 for more details on coordinating threads and shared data. Whew! Now it’s time to say goodbye to HelloJava. We hope that you have developed a feel for the major features of the Java language, and that this will help you as you go on to explore the details of programming with Java. Chapter 3. Tools of the Trade - 53

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Java Web Hosting services

while(true) { blinkState = !blinkState; repaint( ); Thread.sleep(500);

Filed under: Java Programming — webmaster @ 10:14 am

while(true) { blinkState = !blinkState; repaint( ); Thread.sleep(500); } } catch (InterruptedException ie) {} } Basically, run( ) is an infinite while loop. This means the method will run continuously until the thread is terminated by a call to the controlling Thread object’s interrupt( ) method. The body of the loop does three things on each pass: Flips the value of blinkState to its opposite value using the not operator, “!” Calls repaint( ) to redraw the text Sleeps for 500 milliseconds (half a second) sleep( ) is a static method of the Thread class. The method can be invoked from anywhere and has the effect of putting the current thread to sleep for the specified number of milliseconds. The effect here is to give us approximately two blinks per second. The try/catch construct, described in the next section, traps any errors in the call to the sleep( ) method of the Thread class. 2.4.6 Exceptions The try/catch statement in Java is used to handle special conditions called exceptions . An exception is a message that is sent, normally in response to an error, during the execution of a statement or a method. When an exceptional condition arises, an object is created that contains information about the particular problem or condition. Exceptions act somewhat like events. Java stops execution at the place where the exception occurred, and the exception object is said to be thrown by that section of code. Like an event, an exception must be delivered somewhere and handled. The section of code that receives the exception object is said to catch the exception. An exception causes the execution of the instigating section of code to stop abruptly and transfers control to the code that receives the exception object. The try/catch construct allows you to catch exceptions for a section of code. If an exception is caused by any statement inside of a try clause, Java attempts to deliver the exception to the appropriate catch clause. A catch clause looks like a method declaration with one argument and no return type. If Java finds a catch clause with an argument type that matches the type of the exception, that catch clause is invoked. A try clause can have multiple catch clauses with different argument types; Java chooses the appropriate one in a way that is analogous to the selection of overloaded methods. You can catch multiple types of exceptions from a block of code. Depending on the type of exception thrown, the appropriate catch clause will be executed. If there is no try/catch clause surrounding the code, or a matching catch clause is not found, the exception is thrown up the call stack to the calling method. If the exception is not caught there, it’s thrown up another level, and so on until the exception is handled. This provides a very flexible error-handling mechanism, so that exceptions in deeply nested calls can bubble up to the surface of the call stack for handling. As a programmer, you need to know what exceptions a particular statement can generate, so methods in Java are required to declare the exceptions they can throw. If a method doesn’t handle an exception itself, it must specify that it can throw that exception, so that its calling method knows that it may have to handle it. See Chapter 4, for a complete discussion of exceptions and the try/catch clause. - 52

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services

2.4.3 The Runnable Interface We’ve used the second

Filed under: Java Programming — webmaster @ 1:12 am

2.4.3 The Runnable Interface We’ve used the second technique in the HelloJava4 example. To create a thread, a HelloJava4 object passes itself (this) to the Thread constructor. This means that HelloJava4 itself must implement the Runnable interface, by implementing the run( ) method. This method is called automatically when the runtime system needs to start the thread. We indicate that the class implements the interface in our class declaration: public class HelloJava4 extends JComponent implements MouseMotionListener, ActionListener, Runnable {…} At compile time, the Java compiler checks to make sure we abide by this statement. We have carried through by adding an appropriate run( ) method to HelloJava4. It takes no arguments and returns no value. Our run( ) method accomplishes blinking by changing the color of our text a couple of times a second. It’s a very short routine, but we’re going to delay looking at it until we tie up some loose ends in dealing with the Thread itself. 2.4.4 Starting the Thread We want the blinking to begin when the application starts. So we’ll start the thread in the initialization code in HelloJava4’s constructor. It takes only two lines: Thread t = new Thread(this); t.start( ); First, the constructor creates a new instance of Thread , passing it the object that contains the run( ) method to the constructor. Since HelloJava4 itself contains our run( ) method, we pass the special variable this to the constructor. this always refers to our object. After creating the new Thread, we call its start( ) method to begin execution. This, in turn, invokes HelloJava4’s run( ) method in a separate thread. 2.4.5 Running Code in the Thread Our run( ) method does its job by setting the value of the variable blinkState. We have added blinkState, a boolean value, to represent whether we are currently blinking on or off: boolean blinkState; A setColor( ) call has been added to our paintComponent( ) method to handle blinking. When blinkState is true, the call to setColor( ) draws the text in the background color, making it disappear: g.setColor(blinkState ? getBackground() : currentColor( )); Here we are being somewhat terse, using the C-like ternary operator to return one of two alternative color values based on the value of blinkState. Finally, we come to the run( ) method itself: public void run( ) { try { - 51

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services

June 14, 2007

can be downloading an image. Multithreading is especially

Filed under: Java Programming — webmaster @ 3:05 pm

can be downloading an image. Multithreading is especially useful in GUI-based applications, as it improves the interactive performance of these applications. Unfortunately for us, programming with multiple threads can be quite a headache. The difficulty lies in making sure routines are implemented so they can be run by multiple concurrent threads. If a routine changes the value of a state variable, for example, then only one thread should be executing the routine at a time. Later in this section, we’ll examine briefly the issue of coordinating multiple threads’ access to shared data. In other languages, synchronization of threads can be extremely complex and error-prone. You’ll see that Java gives you a few simple tools that help you deal with many of these problems. Java threads can be started, stopped, suspended, and prioritized. Threads are preemptive, so a higher priority thread can interrupt a lower priority thread when vying for processor time. See Chapter 8, for a complete discussion of threads. The Java runtime system creates and manages a number of threads. (Exactly how varies with the implementation.) We’ve already mentioned the repaint thread, which manages repaint( ) requests and event processing for GUI components that belong to the java.awt and javax.swing packages. Our example applications have done most of their work in one thread. Methods like mouseDragged( ) and actionPerformed( ) are invoked by the windowing thread and run on its time. Similarly, our constructor runs as part of the main application thread. This means we are somewhat limited in the amount of processing we do within these methods. If we were, for instance, to go into an endless loop in our constructor, our application would never appear, as it would never finish initializing. If we want an application to perform any extensive processing, such as animation, a lengthy calculation, or communication, we should create separate threads for these tasks. 2.4.2 The Thread Class As you might have guessed, threads are created and controlled as Thread objects. An instance of the Thread class corresponds to a single thread. It contains methods to start, control, and stop the thread’s execution. Our basic plan is to create a Thread object to handle our blinking code. We call the Thread’s start( ) method to begin execution. Once the thread starts, it continues to run until we call the Thread’s interrupt( ) method to terminate it. So how do we tell the thread which method to run? Well, the Thread object is rather picky; it always expects to execute a method called run( ) to perform the action of the thread. The run( ) method can, however, with a little persuasion, be located in any class we desire. We specify the location of the run( ) method in one of two ways. First, the Thread class itself has a method called run( ). One way to execute some Java code in a separate thread is to subclass Thread and override its run( ) method to do our bidding. Invoking the start( ) method of the subclass object causes its run( ) method to execute in a separate thread. It’s not always desirable or possible to create a subclass of Thread to contain our run( ) method. The Thread class has a constructor that takes an object reference as its argument. If we create a Thread object using this constructor and call its start( ) method, the Thread executes the run( ) method of the argument object, rather than its own. In order to accomplish this, Java needs a guarantee that the object we are passing it does indeed contain a compatible run( ) method. We already know how to make such a guarantee: we use an interface. Java provides an interface named Runnable that must be implemented by any class that wants to become a Thread. - 50

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Java Web Hosting services

public void actionPerformed(ActionEvent e) { // Did somebody

Filed under: Java Programming — webmaster @ 4:29 am

public void actionPerformed(ActionEvent e) { // Did somebody push our button? if (e.getSource( ) == theButton) changeColor( ); } synchronized private void changeColor( ) { // Change the index to the next color. if (++colorIndex == someColors.length) colorIndex = 0; setForeground(currentColor( )); // Use the new color. repaint( ); // Paint again so we can see the change. } synchronized private Color currentColor( ) { return someColors[colorIndex]; } public void run( ) { try { while(true) { blinkState = !blinkState; // Toggle blinkState. repaint( ); // Show the change. Thread.sleep(500); } } catch (InterruptedException ie) {} } public static void main(String[] args) { JFrame f = new JFrame(”HelloJava4″); // Make the application exit when the window is closed. f.addWindowListener(new WindowAdapter( ) { public void windowClosing(WindowEvent we) { System.exit(0); } }); f.setSize(300, 300); f.getContentPane( ).add(new HelloJava4(”Hello, Java!”)); f.setVisible(true); } } Compile and run this version of HelloJava just like the others. You’ll see that the text does in fact blink. Our apologies if you don’t like blinking text we’re not overly fond of it either but it does make for a simple, instructive example. 2.4.1 Threads All the changes we’ve made in HelloJava4 have to do with setting up a separate thread of execution to make the text blink. Java is a multithreaded language, which means there can be many threads running at the same time. A thread is a separate flow of control within a program. Conceptually, threads are similar to processes, except that unlike processes, multiple threads share the same address space, which means that they can share variables and methods (but also have their own local variables). Threads are also quite lightweight in comparison to processes, so it’s conceivable for a single application to be running hundreds of threads concurrently. Multithreading provides a way for an application to handle many different tasks at the same time. It’s easy to imagine multiple things going on at the same time in an application like a web browser. The user could be listening to an audio clip while scrolling an image; at the same time, the browser - 49

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services

June 13, 2007

The reason is that in changeColor( ) we

Filed under: Java Programming — webmaster @ 11:10 am

The reason is that in changeColor( ) we increment colorIndex before testing its value. That means that for some brief period of time while Java is running through our code, colorIndex can have a value that is past the end of our array. If our currentColor( ) method happened to run at that same moment, we would see a runtime “array out of bounds” error. There are, of course, ways in which we could fudge around the problem in this case, but this simple example is representative of more general synchronization issues we need to address. In the next section, you’ll see that Java makes dealing with these problems easy through language-level synchronization support. .4 HelloJava4: Netscape’s Revenge We have explored quite a few features of Java with the first three versions of the HelloJava application. But until now, our application has been rather passive; it has waited patiently for events to come its way and responded to the whims of the user. Now our application is going to take some initiative HelloJava4 will blink! Here is the code for our latest version: //file: HelloJava4.javaimport java.awt.*; import java.awt.event.*; import javax.swing.*; public class HelloJava4extends JComponentimplements MouseMotionListener, ActionListener, Runnable { // Coordinates for the message int messageX = 125, messageY = 95; String theMessage; JButton theButton; int colorIndex; // Current index into someColors. static Color[] someColors = { Color.black, Color.red, Color.green, Color.blue, Color.magenta }; boolean blinkState; public HelloJava4(String message) { theMessage = message; theButton = new JButton(”Change Color”); setLayout(new FlowLayout( )); add(theButton); theButton.addActionListener(this); addMouseMotionListener(this); Thread t = new Thread(this); t.start( ); } public void paintComponent(Graphics g) { g.setColor(blinkState ? getBackground() : currentColor( )); g.drawString(theMessage, messageX, messageY); } public void mouseDragged(MouseEvent e) { messageX = e.getX( ); messageY = e.getY( ); repaint( ); } public void mouseMoved(MouseEvent e) {} - 48

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services

« Previous PageNext Page »

Powered by Java Web Hosting