<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.3/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.3/ http://www.mediawiki.org/xml/export-0.3.xsd" version="0.3" xml:lang="en">
  <siteinfo>
    <sitename>Cs3773</sitename>
    <base>https://domex.nps.edu/cs3773/wiki/index.php/Main_Page</base>
    <generator>MediaWiki 1.11.0</generator>
    <case>first-letter</case>
      <namespaces>
      <namespace key="-2">Media</namespace>
      <namespace key="-1">Special</namespace>
      <namespace key="0" />
      <namespace key="1">Talk</namespace>
      <namespace key="2">User</namespace>
      <namespace key="3">User talk</namespace>
      <namespace key="4">Cs3773</namespace>
      <namespace key="5">Cs3773 talk</namespace>
      <namespace key="6">Image</namespace>
      <namespace key="7">Image talk</namespace>
      <namespace key="8">MediaWiki</namespace>
      <namespace key="9">MediaWiki talk</namespace>
      <namespace key="10">Template</namespace>
      <namespace key="11">Template talk</namespace>
      <namespace key="12">Help</namespace>
      <namespace key="13">Help talk</namespace>
      <namespace key="14">Category</namespace>
      <namespace key="15">Category talk</namespace>
    </namespaces>
  </siteinfo>
  <page>
    <title>Annotations</title>
    <id>63</id>
    <revision>
      <id>306</id>
      <timestamp>2007-12-09T19:24:06Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <comment>/* See Also */</comment>
      <text xml:space="preserve">Java '''annotations''' give compilers and humans information about the code in which the annotations appear.

The common annotations that are used include:
  @Author
  @Override
  @Deprecated
  

Other annotations you may run across include::
  @SuppressWarnings
  @ClassPreamble
  @Documented

Annotations may appear pretty much anywhere in your code, but are typically placed before class and method definitions.

==@Override==
Indicates that this method or element overrides another one in the hiearcy. The compiler will check to make sure that this is true; if it isn't, it will issue a warning. That's useful, because the compiler has no other way of catching a spelling error in an override method (the compiler just thinks that you are creating a new method.)


==@Author==

=See Also=
* [http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html Java Tutorial on Annotations]
* [http://www.ibm.com/developerworks/library/j-annotate1/ IBM Developer network article on Annotations]</text>
    </revision>
  </page>
  <page>
    <title>ArffSQL</title>
    <id>162</id>
    <revision>
      <id>1104</id>
      <timestamp>2008-03-18T06:19:36Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>New page: Here is some SQL code I wrote: &lt;pre&gt; import java.io.*; import java.sql.*; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; import weka.core.Utils;  // See...</comment>
      <text xml:space="preserve">Here is some SQL code I wrote:
&lt;pre&gt;
import java.io.*;
import java.sql.*;
import weka.core.Attribute;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Utils;

// See http://www.ling.ohio-state.edu/~jansche/src/weka/c45/ExportC45.java


// upload an ARFF system to 

class MyDataset extends Instances {
    public MyDataset(Reader reader) throws IOException{
        super(reader);
    }
    public void info(PrintStream out) {
        out.printf(&quot;Number of Attributes: %d%n&quot;,numAttributes());
        out.printf(&quot;Class Index: %d%n&quot;,classIndex());
        out.printf(&quot;Relation Name: %s%n&quot;,relationName());
        out.printf(&quot;Names: %n&quot;);
        for(int i=0;i&lt;numAttributes();i++){
            Attribute a = attribute(i);
            out.printf(&quot;  %s : %n&quot;,a.name());
        }
        out.printf(&quot;%n&quot;);
        out.printf(&quot;Values: %n&quot;);
        for(int i=0;i&lt;numInstances();i++){
            Instance inst = instance(i);
            for(int j=0;j&lt;numAttributes();j++){
                if(j&gt;0) out.printf(&quot;, &quot;);
                if(inst.isMissing(j)){
                    out.printf(&quot;? &quot;);
                } else if(inst.attribute(j).isNumeric()){
                    double g = inst.value(j);
                    if(Math.floor(g)==g) out.printf(&quot;%d &quot;,(int)g);
                    else out.printf(&quot;%f &quot;,g);
                } else {
                    out.printf(&quot;%s &quot;,inst.stringValue(j));
                }
            }
            out.printf(&quot;%n&quot;);
        }
        out.printf(&quot;%n&quot;);
    }
}

public class ArffSQL {
    public static void usage(){
        System.err.println(&quot;Usage java ArffTest database table filename.arff ; use - for stdin&quot;);
        System.exit(-1);
    }

    public static Connection mysql_connect() {
        String MP = System.getenv(&quot;DOMEX_MYSQL_PASSWORD&quot;);
        if(MP==null) throw new RuntimeException(&quot;DOMEX_MYSQL_PASSWORD not set&quot;);

        String username = System.getenv(&quot;DOMEX_MYSQL_USERNAME&quot;);
        if(username==null) throw new RuntimeException(&quot;DOMEX_MYSQL_USERNAME not set&quot;);

        System.out.printf(&quot;Mysql username/password is %s/%s%n&quot;,username,MP);

        try {
            Class.forName(&quot;com.mysql.jdbc.Driver&quot;);
            String url = &quot;jdbc:mysql://&quot; + System.getenv(&quot;DOMEX_MYSQL_HOSTNAME&quot;)+&quot;:3306/mysql&quot;;
            Connection con = DriverManager.getConnection(url,username,MP);
            return con;
        } catch( Exception e ) {
            e.printStackTrace();
            return null;
        }//end catch 
    }

    /** for each attribute in dataset d, add the field to the current database
     * of Connection con if the field is not there...
     */
    public static void add_missing_fields(MyDataset d,Connection con,String table){
        java.util.HashSet&lt;String&gt; fields = new java.util.HashSet&lt;String&gt;();
        rs = stmt.executeQuery(&quot;describe &quot;+table);
        while(rs.next()){
            String fname = rs.getString(&quot;Field&quot;);
            System.out.println(fname);
            fields.add(fname);
        }
        System.out.println(&quot;fields: &quot;+fields);
    }
        

    public void process(String db,String table,String fn){
        mysql_connect();

        try {
            Reader in = new FileReader(fn);
            MyDataset d = new MyDataset(in);
            Connection con = mysql_connect();
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(&quot;use &quot;+db);

            add_missing_fields(d,con);
            rs.close();
            con.close();
        } catch (FileNotFoundException e){
            System.err.printf(&quot;%s: file not found&quot;,fn);
        } catch (IOException e){
            System.err.printf(&quot;%s: IOException reading file&quot;,fn);
        } catch (java.sql.SQLException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        if(args.length &lt; 3){
                usage();
        }
        ArffSQL worker = new ArffSQL();
        worker.process(args[0],args[1],args[2]);
    }
}
&lt;/pre&gt;</text>
    </revision>
  </page>
  <page>
    <title>Assignment 1</title>
    <id>3</id>
    <revision>
      <id>418</id>
      <timestamp>2008-01-11T17:14:25Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <comment>/* Contest */</comment>
      <text xml:space="preserve">JavaTM Programming Tools and Documentation

Due date: Sunday, January 13, 6pm Pacific Time

=Purpose=
To set up the Java programming environment, learn the compilation process, and practice the submission process.

=Grading=
Assignment 1 is a chance to learn the grading process without having mistakes counted against you.  This assignment is graded pass/fail. If you turn it in, you get an &quot;A&quot;. If you don't, you get an &quot;F&quot;.  It is suggested that you take this opportunity to familiarize yourself with the Java development environment, the assignment submission process, and the stringency of coding-style requirements.

One of the nice things about Java is that virtually all of the tools you need to develop Java programs available for free. What's more, there are many different free tools from different sources. Sun Microsystems invented Java and distributes a version called the Java Development Kit. The current JDK is number 6. The JDK includes a Java compiler (javac), the Java interpreter (java) a debugger (jdb), a documentation tool (javadoc) and many other tools. Unlike other development environments you may have used, these tools are designed to be used from the command line, like a DOS console, or UNIX xterm. 

In addition to these command-line tools, there are a number of integrated development environments (IDEs) available for Java. These include NetBeans from Sun, Eclipse from the Eclipse Foundation, and EMACS, a text-mode editor distributed by the Free Software Foundation. 

The purpose of this lab is to have you locate and install JDK 6 and other relevant tools on your computer. 

Note:
* If you are using a Macintosh, JDK5 is pre-installed and JDK6 is not available.
* The PCs in the lab should have JDK 6 pre-installed.

=Download the Software=
# Download and install [http://java.sun.com/javase/downloads/index.jsp JDK 6 Update 3] from Sun's website.  (Note: if you have a Mac, then you will be using JDK 5, and it's pre-installed.)
# Download and install [http://www.netbeans.org/ NetBeans 6.0] from the NetBeans site.
# The standard install places the JDK in the directory '''c:\Program Files\Java\jdk1.6._03'''. In order to use your newly installed JDK, you must ensure that your system is configured properly. There are three environment variable that must be properly setup in order to locate JDK components:  '''JAVA_HOME''', '''PATH''' and '''CLASSPATH'''.

==Setting up Environment Variables on Windows==
Once you have the JDK installed, you need to set up your computer's Environment Variables so that the JDK installation can be found. For reasons that defy comprehension these environment variables are not set up automatically but must be manually configured. On Windows this is done through the Environment Variables control panel which is reached by clicking the &quot;Environment Variables&quot; button on the Advanced tab of the System Properties panel. (On Mac/Unix/Linux this is done by modifying your .bash_profile, .cshrc, or .profile startup scripts.)

# Right-click on the My Computer icon on your desktop and select '''properties'''
# Click the Advanced Tab
# Click the Environment Variables button
# Assure that the following environment variables are set up:
{|
|JAVA_HOME 
|''your JDK installation directory''
|-
|PATH
| ''your JDK bin directory'' needs to be in the PATH. 
|-
| CLASSPATH
| ''You'll use this to tell your system where additional classes are installed.''
|}


[[Information on setting JAVA_HOME and CLASSPATH on Windows 95/98]]

=Subversion=
Install [[Subversion]] on your computer and check out the repository from &lt;tt&gt;http://domex.nps.edu/cs3773/svn/&lt;/tt&gt;.


=Hello World=
Using a text editor (like Notepad or EMACS), enter the following Java program. Remember, Java is case sensitive so watch your capitalization.

&lt;pre&gt;
/**
 * My first Java Program.
 *
 * @author Simson Garfinkel (change to your name)
 */

public class Assign1 {
   public static void main(String args[]) {
      System.out.println(&quot;Hello World!&quot;);
   }
}
&lt;/pre&gt;

Save the file as Assign1.java in the src directory.  Open a command window. Change directories to the directory containing the source file you just created. Issue the following command, from the base &lt;your login&gt; directory, to compile your program:

  javac Assign1.java

A successful compilation will create a Java class file named Assign1.class, consisting of Java byte codes. The “-d classes” directive tells the compiler to place compiled class files into the classes directory.  This is the Java version of an object file created by other language compilers. You may execute this class file by invoking the Java interpreter (java) with the following command:

  java Assign1

The Java interpreter searches the CLASSPATH list to find the Assign1.class file.  It should find it in the classes directory.  If you have any problems performing these two steps, you need to ensure that your PATH and CLASSPATH variable are set properly. In a DOS window you can see the values of all system variables by typing set. 

Finally, we want to use the automatic documentation facility, javadoc.  We want documentation of all files from the src directory to be in the docs directory, so run the command as follows:

  javadoc –d docs *.java

All java commands can be run with –help, as  javac –help to get a list of possible arguments.

=Assign1 with the Add method=
Some of the programs that you submit for this course will be graded with an automatic web-based grading system. Neat, huh? To get the sense of how it works, we want you to add a method called '''calc''' to your Assign1 class. The calc method should take two integer arguments and return a new integer.  

Modify your class so it looks like this:

&lt;pre&gt;
/**
 * My second Java Program.
 *
 * @author Simson Garfinkel (change to your name)
 */

public class Assign1 {
    public static int calc(int a,int b){
	return a+b;
    }
    public static void main(String args[]) {
	System.out.println(&quot;Hello World!&quot;);
	System.out.printf(&quot;3 + 4 = %d %n&quot;,Assign1.calc(3,4));
    }
}
&lt;/pre&gt;


The new '''calc''' method will add a+b and return the result. The new lines that we added to the '''main()''' static method will create an '''Assign1''' object and then run it's calc method with (3,4). The printf method looks a lot like the C printf method, with the exception that we use '''%n''' instead of '''\n''' as a newline.

=Counter=
Create a program called Counter which outputs the numbers 1 through 10. The program should be in a file called ''Counter.java'' and compiled into a file called ''Counter.class''. Your output should look like this:
&lt;pre&gt;
1
2
3
4
5
6
7
8
9
10
&lt;/pre&gt;

=Primes=
Create a program called Primes which accepts an argument on the command line and prints the prime numbers between 1 and that number. For example, if your program is called with the command:
  java Primes 20
The output should be:
&lt;pre&gt;
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
&lt;/pre&gt;

=Upload=
Bundle all of your files together into a JAR file with your username. 

You can do this with the jar command, like this:

&lt;pre&gt;
$ jar cvf slgarfin.jar *.java *.class 
added manifest
adding: Assign1.java(in = 316) (out= 223)(deflated 29%)
adding: Counter.java(in = 268) (out= 199)(deflated 25%)
adding: Primes.java(in = 311) (out= 201)(deflated 35%)
adding: Assign1.class(in = 684) (out= 422)(deflated 38%)
adding: Counter.class(in = 406) (out= 295)(deflated 27%)
adding: Primes.class(in = 984) (out= 561)(deflated 42%)
$ 
&lt;/pre&gt;

'''Note: The dollar sign ($) is the prompt for the computer that I'm using.'''

Notice that we can run all of the programs out of the jar file by using the -classpath argument:

&lt;pre&gt;
$ java -classpath slgarfin.jar Assign1
Hello World!
3 + 4 = 7 
$ java -classpath slgarfin.jar Counter
1
2
3
4
5
6
7
8
9
10
$ java -classpath slgarfin.jar Primes 20
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
$ 
&lt;/pre&gt;

Here is what happens if you ask to run a function that isn't present:

&lt;pre&gt;
$ java -classpath slgarfin.jar Count
Exception in thread &quot;main&quot; java.lang.NoClassDefFoundError: Count
&lt;/pre&gt;

=Contest=
For the contest, create Primes to print the number of primes between 1 and N, where N is an argument on the command line, if the &quot;-total&quot; argument is given. (This way you don't need to have two copies of Primes.java)

For example:
&lt;pre&gt;
% java Primes -total 10
4

% java Primes -total 20
8


&lt;/pre&gt;

=See Also=
[[Assignments]]

[[Category:Assignments]]</text>
    </revision>
  </page>
  <page>
    <title>Assignment 2</title>
    <id>13</id>
    <revision>
      <id>521</id>
      <timestamp>2008-01-18T00:31:04Z</timestamp>
      <contributor>
        <username>Bmhawkin</username>
        <id>7</id>
      </contributor>
      <minor/>
      <comment>/* Get Ready */</comment>
      <text xml:space="preserve">In Week 2 we are learning all about Java classes. 

=Get Ready=
Download the jarfile from https://domex.nps.edu/cs3773/week2/week2.jar
* Note: if you are using Internet Explorer, the week2.jar file may download as week2.zip; you will need to rename it.

You can unpack the file if you wish. It will have the following in it:
; Flatland.java &amp; Flatland.class
: Source code and Bytecode for the Flatland class
; FlatlandComponent.java &amp; FlatlandComponent.class
: Source code and byte code for the FlatlandComponent class (this is the GUI)
; FlatlandDelegate.java &amp; FlatlandDelegate.class
: The interface that allows Flatland to communicate with the FlatlandComponent
; FlatlandObject.java &amp; FlatlandObject.class
: Source code and byte code for the abstract superclass
; Location.java &amp; Location.class
: Simple class that implements a place
; Size.java &amp; Size.class
: Simple class that implements a size.

=Build a Bot=
In the assignment you will start with a class we have created called [https://domex.nps.edu/cs3773/week2/doc/Bot.html Bot]. The Bot is a class for a simple robot. These area ideal robots which are 1 meter square. We'll be doing a lot with these little robots. 

Our Bots live on a 2-dimensional plane called Flatland.  The Flatland class keeps track of all of the objects that are in it, including the Bots, the Walls, and other objects that we haven't even thought about!

Your Bot class needs to have the following internal state:
* A location
* A size
* A speed
* A heading (0 = north, 90 = east, 180 = south, 270 = west)
* Color 
* Speed

Your Bot class needs to implement the following methods:

* getCenter() (returns the Location of the center)
* getSize() (returns the size)
* setSpeed(double speed)
* setHeading(double heading)
* tick() (time passes)
* Bot(center,size) (constructor)
* toString() - turns it into a string

This specification can be packaged into either a FlatlandObject interface, which your Bot could implement, or a FlatlandObject abstract class, which your Bot would subclass. ''What are the advantages or disadvantages of each?''

We have provided the javadoc output for the instructor's Bot class.

==Test Your Bot==
The Flatland class contains a '''main()''' function that you can use to test your Bot class. The simulation will create four bots with a starting location and move them around.  If you unpack all of the files in the JAR file, you can run your simulation with this command:
  java Flatland
Alternatively, you can run the simulation out of the jar file. Use this command:
  java -classpath week2.jar:. Flatland
On Windows, I had to use this command:
  java -classpath week2.jar;. Flatland

Note that you do not need to put your Bot.class file into the week2.jar file; you can have the Bot.class file in the current directory and the jar file specified by the classpath.

If you wish, you can visualize the simulation as well. This is done with the '''FlatlandComponent''' class. The class has a public static method called '''launch'''. Call it with the Flatland object as its argument and the simulation will start off; we won't discuss how the visualiation works for a few weeks.

This code automatically launches the visualization when the -gui flag is given to the Flatland class:

	if(args.length==1 &amp;&amp; args[0].equals(&quot;-gui&quot;)){
            FlatlandComponent.launch(fl);
        }

Get it?

=Bounce 1=
# Modify the Flatland class so that the simulation runs for 1000 seconds.
# Modify your Bot class so that the bots bounce when they hit the walls of Flatland.
#* Hint: your '''tick''' object will need to inspect the size argument of what's passed in.
#* If the object is going to exceed the bounds, you could just reverse the direction. (Can you do this in a line of code?)
#* Will this work for objects moving at angles?

=RandomBot=
Create a subclass of your Bot Class called RandomBot. This bot should randomly change direction every 10 seconds. 

Now, how are you going to get a RandomBot onto the playing field? You'll do this by creating a new simulation class called Simulation. Copy out the '''main()''' function in Flatland and create a Simulation.main(). This Simulation class should create a Flatland object, add a RandomBot to it, and then set the whole thing going.

=Extra Credit=
If you want, create a third class, add it to your simulation, and let it go. Here are some ideas:

* Have a bot that chases the RandomBot. 
** How will your Chaser instance find and pursue the RandomBot?
** What will your chaser do when it finds the RandomBot?

* Right now the RandomBot will go through the other bots. How would you make it bounce off them? 

*  Give every object a mass. Compute the mutual attraction using Newton
** How will you create the next step? (Hint: split the '''tick()''' method into two methods: '''tick()''' and '''toc()'''.

=Deliverables=
Your entire deliverable is a jar file containing Bot.java, Bot.class, RandomBot.java, RandomBot.class, Simulation.java, and Simulation.class. You can make this file with the ''jar'' command:

  jar -cf Bot.jar Bot.java Bot.class RandomBot.java RandomBot.class Simulation.java Simulation.class

You should upload it to our the class server. Hopefully there will be some kind of automated testing by Friday.

=Notes=
* All submissions must be in compliance with the [[CS3773_Java_Style_Guide]] (JavaDoc, Naming Conventions, etc.)
* Your program should be robust:  for example, inappropriate inputs should cause graceful failure.

=See Also=
[[Assignments]]</text>
    </revision>
  </page>
  <page>
    <title>Assignment 3</title>
    <id>14</id>
    <revision>
      <id>778</id>
      <timestamp>2008-02-04T01:53:05Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">The goals of this week's assignment is to continue your exposure to object oriented design and programming. 

We will be building upon the Flatland with two new simulations:

* Snake
* Electrostatics

The extra simulation will be:
* Shelling

=Snake=
In Week2 you created a Bot and RandomBot. In class we also created a ChaserBot.

For Week3 we will be creating yet another subclass of Bot called the AffinityBot. The AffinityBot will look in the world for bots that have a certain tag and will try to move closer to it. 

We will start by adding '''Tags''' to the FlatlandObject. A tag is an integer attribute that can be added to any object. In the original version of this problem set we suggested using a Tag interface, like this:

&lt;pre&gt;
interface Tag {
   public int tag();
   public void setTag(int newTag);
}
&lt;/pre&gt;

And here is another interface, the Tag Search interface:
&lt;pre&gt;
interface TagSearch {
   public ArrayList&lt;TaggedFlatlandObject&gt; search(int tag);
}
&lt;/pre&gt;

But this turned out to make the code really complicated, so we decided instead to just build the '''Tag''' functionality into the FlatlandObject abstract object, with these three methods:

&lt;pre&gt;
    private int myTag=0;
    /** Tags are a way of keeping track of objects */
    public void setTag(int tag){
        this.myTag = tag;
    }
    public int tag(){
        return myTag;
    }
&lt;/pre&gt;

Either one works.

We have [https://domex.nps.edu/cs3773/svn/week3/ posted code] with the new classes, which we will describe in class on Thursday. Here are the major changes:

# Flatland now supports Tags.
# We have modified the Flatland class to make the names more sensible.
# We have modified the Flatland class to make it clear which methods and fields are private and which are public.
# Flatland's '''tick()''' method no longer sends a '''tick()''' method to each of the objects; it now sends a '''calculateNextPosition()''' message then a '''updatePosition()''' message.
# Flatland now includes a '''run()''' method which runs the simulation indefinitely. 
# The Bot() implementation has been cleaned up.
# The ChaseBot() implementation is now given to you. It's pretty clean too.
# The AffinityBot() implement is given to you, but you need to finish it off.

You are welcome to use your own classes, the classes from the original version of this assignment, or the final version of this assignment. You need to turn in a set of .class and .java files that makes the snake work, as demonstrated in class. You are welcome to add additional functionality as you wish. The only requirement for this part is that you have a snake, that it work, and that your code be beautiful.

=Electrostatics=
Rework your simulation so that there is just one kind of Bot, a ChargedBot bot.
* Every bot gets an electric charge, either +1 or -1.
* Give bots that have a +1 charge the color Blue, -1 charge the color Red.
* By the way --- if a +1 and a -1 charge get too close, they should stick but not fuse and become the same with exactly the same center. That is, if they both have a radius of 1, one should go to (1,0) and one go to (3,0), but both should not go to (2,0) and (2,0).
* Calculate each Bot's future position by calculating the force vector to every other bot and adding together all of the force vectors. 
* Create an interesting initial configuration and watch what happens.

=Schelling=
Schelling is a simulation of self-segregation. It's played on an n x m grid. Only one object can be in each grid location at a time.

* There are Red bots and Blue Bots.
* Every clock tick, 10% of the Reds and 10% of the Blues decide to move to another grid location; of course, they can only move to an empty one.
* A Red bot is happy to live next to the same number of Reds and Blues, or is happy to live with more Reds. It would rather not live with more Blues.
* A Blue bot is happy to live next to the same number of Reds and Blues, but would rather not live with more Reds.  (ie: same rules as the Blues, but reversed.)

Run the simulation. See what happens.

Hints on implementing Schelling:

* Have Flatland maintain a grid of [x][y] coordinates with a two-dimensional array that is sized 50x50 or 100x100 (the same as your initial size).
* Go back to a single tick() method; it will be too hard to have every Bot figure out where they are moving and then all move at the same time.  (Or have the bots calculate their move and move on the second update method.)
* Remember, this part is extra work, not necessary to turn in.

Check out Peter Wayner's schelling simulation: http://www.wayner.org/texts/seg/012298segregate-sim2.html

=What to turn in=
Turn in a jar file with your '''username.jar'''. The jar file should run each simulation when the simulation's name is provided as the first argument. eg:

&lt;pre&gt;
java -classpath slgarfin.jar snake
java -classpath slgarfin.jar electrostatic
java -classpath slgarfin.jar schelling
&lt;/pre&gt;

=See Also=
* [[Assignments]]
* [[Week 3 Grading Rubrick]]</text>
    </revision>
  </page>
  <page>
    <title>Assignment 4</title>
    <id>15</id>
    <revision>
      <id>936</id>
      <timestamp>2008-02-29T16:47:55Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">This week we are learning about input, output, and persistent data. 

* We will dramatically simplify the simulation to avoid the threading problem that we've discovered.
* We will modify the so that the bot can take its commands from a file.
* You will run your simulation.
* You will then modify your simulation so that the commands can be taken from an SQL database over the network.
* We will develop this simulation over the week in class, learning about exceptions and remote database access.

And one last thing:

* We will start using packages. In this case, package hw4.

=Problem 1=
Download these two Java files to your computer:
*  https://domex.nps.edu/cs3773/svn/week4/B.java
*  https://domex.nps.edu/cs3773/svn/week4/BTest.java

Here is BTest.java:
&lt;pre&gt;
package hw4;
public class BTest {
    public static void main(String[] args){
	B b = new B(1);
	System.out.printf(&quot;The value of the B function at 1 is: %d %n&quot;,b.calc());
    }
}
&lt;/pre&gt;

When BTest.main is run, the program prints out the value of the B function when calculated at 1.

Add a new static method to BTest called number_of_exceptions(int n)
which returns the number of exceptions that the B function generates when evaluated between 1 and n. The pseudocode for this function looks something like this:
&lt;pre&gt;
    public int number_of_exceptions(int n){
       for(int i=1;i&lt;=n;i++){
           // some sort of try here
           B b = new B(i);
           b.calc();
           // some sort of catch here
       }
       return the number of exceptions that happened;
     }
&lt;/pre&gt;


So the following values should hold:

  BTest.number_of_exceptions(1) should return 0
  BTest.number_of_exceptions(2) should return 0
  BTest.number_of_exceptions(3) should return 1

Modify BTest.main so that it prints the number of exceptions generated between 1 and 100 
using your static method number_of_exceptions()

=Problem 2 - Throw an exception=

Download this Java file to your computer:

   https://domex.nps.edu/cs3773/svn/week4/CTest.java
   https://domex.nps.edu/cs3773/svn/week4/CInterface.java
   https://domex.nps.edu/cs3773/svn/week4/CException.java

CTest.java wants a class called C which implements the CInterface.

Create C.java on your computer. It's going to look a bit like this:

&lt;pre&gt;
public class C implements CInterface {
    // todo: add your code here
}
&lt;/pre&gt;

There is also

Your C class needs to implement a single method called calc(int). Here are the rules for the C.calc
function:

# C.calc(n) for any even number should throw an &lt;tt&gt;ArithmeticException&lt;/tt&gt;.
#  C.calc(99) should throw a CException with the exception's value set to be 33.
# Otherwise, return n.

Both of these are tested by the CTest.java

Test this with:
  java CTest

=Problem 3 - Create a File =
Here is a program that puts &quot;Hello World!&quot; into a file called output.txt:
&lt;pre&gt;
package hw4;
import java.io.*;
public class HelloToFile {
    public static void main(String[] args){
        try{
            PrintWriter out = new PrintWriter(new FileWriter(&quot;output.txt&quot;));
            out.println(&quot;Hello World!&quot;);
            out.close();
        } catch (IOException e){
            System.out.println(&quot;Could not open output.txt&quot;);
            e.printStackTrace();
        }
    }
}
&lt;/pre&gt;
 
Because this class is called HelloToFile it should be stored in a file called HelloToFile.java.

1. Add a public static method to this file with the following signature:
&lt;pre&gt;
   public static void makeHelloFile(String filename) throws IOException;
&lt;/pre&gt;

When &lt;tt&gt;makeHelloFile&lt;/tt&gt; is called, it should put 'Hi Mom!' (followed by a newline) into the file named by '''filename'''.

2. Modify the '''main''' static method so that, instead of putting '''Hello World!''' into the file called '''output.txt''', the program calls the &lt;tt&gt;makeHelloFile&lt;/tt&gt; method 10 times with the filenames ''file''1.txt through ''file''10.txt  where ''file'' is specified on the command line. That is, this invocation should create the files foobar1.txt, foobar2.txt, etc.:

  java HelloToFile foobar

And this should create nosmis1.txt, nosmis2.txt, etc:

  java HelloToFile nosmis

;note -- if your main method encounters an exception on file N, it should continue with file N+1. 

You may find the following web pages helpful in performing this question:

* [http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintWriter.html Java PrintWriter documentation]
* [http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileWriter.html Java FileWriter documentation]
* [http://www.cs.carleton.edu/faculty/dmusican/cs117s03/iocheat.html Java Console and File Input/Output Cheat Sheet]
* [http://www.cis.upenn.edu/~matuszek/cit591-2003/Lectures/35-java_io.ppt PowerPoint deck on file I/o]

If you want, you may also read:
* Day 15, Working with Input and Output, in Teach Yourself Java 6 in 21 days.

=Problem 4 - Download a web page=
Here is some code that will not compile. The code should download a web page called http://domex.nps.edu/cs3773/hello.txt and print it line-by-line. This code introduces three classes you have not seen before: '''InputStream''', '''InputStreamReader''', and '''BufferedReader'''.
&lt;pre&gt;
package hw4;

import java.io.*;
import java.net.*;


public class WebCalc {
    static public void main(String[] args){
        URL u = new URL(&quot;http://domex.nps.edu/cs3773/hello.txt&quot;);
        URLConnection con = u.openConnection();
        if(con instanceof HttpURLConnection){
            int code = ((HttpURLConnection) con).getResponseCode();
            if(code!=HttpURLConnection.HTTP_OK){
                System.out.println(&quot;Error code: &quot;+code);
                return;
            }
        }
        InputStream is = con.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        while(true){
            String s = br.readLine();
            if(s==null) break;
            System.out.println(s);
        }
        br.close();
        is.close();
    }
}
&lt;/pre&gt;

1. Fix this code so that it compiles. Your output should look like this:

&lt;pre&gt;
$ java hw4.WebCalc
Hello World!
&lt;/pre&gt;

2. Modify this program so that, if an argument is provided, the provided argument is treated as a URL and that page is downloaded and printed.  Your output should look like this:

&lt;pre&gt;
$ java hw4.WebCalc http://domex.nps.edu/cs3773/mom.txt
Hi Mom!
&lt;/pre&gt;

3. Modify the program so that a &quot;-sum&quot; option before the URL causes the program to add up all of the numbers on the web page (assuming each number is on its own line).  Here are two sample outputs you should get:

&lt;pre&gt;
$ java hw4.WebCalc -sum http://domex.nps.edu/cs3773/numbers.txt
6


$ java hw4.WebCalc -sum http://domex.nps.edu/cs3773/numbers2.txt
line 4: &quot;foobar&quot; is not a number.
&lt;/pre&gt;

=Problem 5 - The Web Crawler=
This problem is extra credit...

Create a new class called WebCrawler.

Give it a public static method called crawl(String url) which does the following:
* Opens up the url '''url'''
* Reads each line
* Prints the line
* If the line contains a URL, calls '''crawl(url)''' with the URL on the line.
* Returns the contents of the web page
* Increments a static instance variable keeping track of the total number of lines printed and URLs visited.

Create a public static method called main(String args[]) which:
* Calls crawl(&quot;http://domex.nps.edu/cs3773/hw4/one.txt&quot;)
* Prints the total number of pages printed and exits.

  Total lines: 29 total URLs: 6 


This is really fun. If you can get it to work, try to add the following:

* A global variable that keeps track of each page visited and doesn't visit the same page twice. (Very Important!!! You can test this with the url http://domex.nps.edu/cs3773/hw4/here.txt which points to http://domex.nps.edu/cs3773/hw4/there.txt and vice-versa).
** Hint: You want to use a [http://java.sun.com/j2se/1.5.0/docs/api/java/util/Hashtable.html Hashtable] which maps the string URLs to a boolean flag.
** Better Hint: Use a HashSet instead of a Hastable. Declare it as HashSet&lt;String&gt;; put strings into it and then see if you were at the page by seeing if the HashSet contains the specified key.


* A global counter which keeps track of the total number of pages visted; print this when you are done.
* Try printing the pages completely, rather than line by line. Hint: do this with a StringBuilder.
* Question: how could you make your program work with actual HTML rather than with these text files?

=HINT=
If you are using NetBeans, you can keep track of each of these different commands with the run profiles.

If you tell NetBeans not to exclude the *.java files, it will automatically include them.

Change this:
[[Image:Include_java.png]]

to this:

[[Image:Include_java2.png]]

=What to turn in=
Turn in a jar file containing at least the following:

&lt;pre&gt;
hw4/BTest.java
hw4/BTest.class
hw4/C.java
hw4/C.class
hw4/HelloToFile.java
hw4/HelloToFile.class
hw4/WebCalc.java
hw4/WebCalc.class
hw4/WebCrawler.java
hw4/WebCrawler.class
&lt;/pre&gt;

* [https://domex.nps.edu/cs3773/submit/submit.cgi Homework Submission Link].

=Grading==
Problems 1-4 are worth 25 points each; Problem 5 is worth 20.
=See Also=
* [http://www.ibm.com/developerworks/java/library/j-jtp05254.html The exceptions debate]
[[Assignments]]</text>
    </revision>
  </page>
  <page>
    <title>Assignment 5</title>
    <id>40</id>
    <revision>
      <id>818</id>
      <timestamp>2008-02-06T06:44:23Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>/* Part 2: Flatland GUI */</comment>
      <text xml:space="preserve">This week's assignment involves a code-cleaning exercise and extensions to the Flatland GUI. You are to submit a jar file, but the assignment will not be graded automatically.

=Part 1: Newton=
In the week5 subversion repository you will find two fractal programs: Mandelbrot and Newton. 
* Download a copy of the subversion repository from http://domex.nps.edu/cs3773/svn/
* Fix Newton.java. Turn it into beautiful code. Be especially aware of:
** Dupliate code that can be cleaned up.
** Variable names that can be clarified.
** Dead code that can be removed (is there any?)
** Hard-coded constants that should be clarified.
** Comments that should be improved.
* At the beginning of Newton.java, put a summary of the code cleaning you did.

Plan on spending 2-3 hours cleaning this up. 


=Part 2: Flatland GUI=
In the week5 subversion repository you will find a reworked version of Flatland. This version uses just a single thread and, as a result, it does not throw the exception that troubled is in Week 3. This version also implements the clean architecture that we discussed in the homework.

Study the code that you have been given. Add at least four of the following features:
* Buttons to start and stop the simulation
* Rework the simulation layout and make it more attractive.
* Make the simulation run in a JApplet instead of a JFrame
* Add walls to the inside simulation which the random objects bounce off
* Let the user draw new walls with the mouse.
* Let the user select a bot with the mouse and:
** Control it with the keyboard
** Watch where it moves (show its trail)
** Change its properties by right-clicking on it.
* Make the bots bigger and draw the bot's tag in the middle of the bot.
* Draw a line between the ChaseBot and its target.
* Annotate the target line with the length.

[[Category:Assignments]]</text>
    </revision>
  </page>
  <page>
    <title>Assignment 6</title>
    <id>115</id>
    <revision>
      <id>856</id>
      <timestamp>2008-02-13T01:14:10Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">Assignment #6 will be due on '''Monday, February 18th.'''

Re-implement the Flatland from HW5. This time create the FlatlandControlPanel using the NetBeans GUI builder.

Extra credit: Add and document some new functionality. Here are some ideas:

* A bot you can steer 
* A bot that creates new bots.
* A bot that destroys bots.
* A bot that changes colors
* A bot that displays an image</text>
    </revision>
  </page>
  <page>
    <title>Assignment 7</title>
    <id>118</id>
    <revision>
      <id>952</id>
      <timestamp>2008-03-03T07:06:32Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">Assignment 7 is optional. Please make your Flatland run as an applet. 

When you upload Assignment 7, you will be given a URL for your applet.</text>
    </revision>
  </page>
  <page>
    <title>Assignment 8</title>
    <id>41</id>
    <revision>
      <id>955</id>
      <timestamp>2008-03-03T07:07:55Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">For this assignment, you are to create a simple application that communicates with the Othello Server using the XML RPC API.

Here is the Othello Server:
* http://othello.nitroba.org/game.cgi

Here are some code snippets:
* [[joinGameButtonActionPerformed]]

We will discuss this API in greater depth in class and sample code will be provided by Wednesday.

Here is how you implement the chat program:
* Join a game by calling joinGame() with your name as the playerID
* This will give you a gameID, which is an integer
* Every second, you must call stillAlive(playerID,gameID) to tell the server that you are still alive.
* Every second, you should call getMessages(gameID,playerID) to see if there are any messages for you. If there are, display them.
* Every second, you should call getGameState(gameID) to find out if someone else has joined the game, and to find out if you are white or black, and to find out if it is your turn to move.
* If you want to send a message to someone, call sendMessage(gameID, senderID, recipientID, message)

To implement a full-blown game, you would need to do this:
* Display the game board after getGameState() is called
* If it is your turn, pick up a mouse click on the game board and send it to the server as a submitMove() function call.

Here is a sample screenshot:
[[Image:Othelloscreen.PNG]]

Assignment #8 is due on Friday, March 7th.

Grading will be as follows:
* 50% credit - turning in a jar file that connects to the othello server and displays the current status (updated every second) in a text window.
* 25% credit - connects to the server, joins a game, and displays chat messages as they are received.
* 25% credit - allows the user to send chat messages to the other user.
* 25% extra credit - displays the blank othello board.
* 25% extra credit - lets you click on board positions and send the moves
* 25% extra credit - gets boards from the othello server and displays them
* 25% extra credit - properly handles game over.</text>
    </revision>
  </page>
  <page>
    <title>Assignment 9</title>
    <id>135</id>
    <revision>
      <id>957</id>
      <timestamp>2008-03-03T07:08:53Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>New page: There is no spoon.</comment>
      <text xml:space="preserve">There is no spoon.</text>
    </revision>
  </page>
  <page>
    <title>Assignments</title>
    <id>4</id>
    <revision>
      <id>1069</id>
      <timestamp>2008-03-15T22:59:00Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">[[Assignment 1]] - Hello World!

[[Assignment 2]] - Building and validating a simple class '''Bot''; Javadoc. 

[[Assignment 3]] - Abstract classes, packages, interfaces and more behaviors. 

[[Assignment 4]] - I/O and Exceptions. Some exercises involving exceptions, reading from the network, writing into an SQL database, and having fun with Java. 

[[Assignment 5]] - Flatland with a new GUI.

[[Assignment 6]] - Reimplement the Flatland Control Panel with the GUI created with the Swing Builder..

[[Assignment 7]] - '''optional''' Make your Flatland (or anything else) run as an applet.. 

[[Assignment 8]] - Chat program with the Othello Server (due March 7th) . 


[[Final Project]] - You create your own project.  mini project. See the web page for ideas.</text>
    </revision>
  </page>
  <page>
    <title>Ayers final project proposal</title>
    <id>154</id>
    <revision>
      <id>1053</id>
      <timestamp>2008-03-12T17:59:25Z</timestamp>
      <contributor>
        <username>Swayers</username>
        <id>18</id>
      </contributor>
      <comment>New page: Project Proposal:  	For the final project I want to create a game application similar to the 1980’s game of Centipede.  I will use the Flatland files and modify them to create this proje...</comment>
      <text xml:space="preserve">Project Proposal:

	For the final project I want to create a game application similar to the 1980’s game of Centipede.  I will use the Flatland files and modify them to create this project.  The summary of the game follows.  A playing filed that replicates a garden with be the playing surfaces.  The two antagonists are the player/destroyerBot and the system/centipedeBot.  The centipede’s objective is to maneuver from the top of the playing field to the bottom of the playing field and “bite’ which is make contact with the player/destroyerBot.  The centipede will encounter 8 randomly placed mushroom objects that will change the course of the centipede as well as its speed.   If the centipede achieves its objective the player will lose the game.  The players objective is to maneuver the player/destroyerBot with the keyboard arrow keys (left, right, up, down) in order to destroy the centipede.  The player/destroyerBot will have limited movement in that it will only move vertical or horizontal in the bottom 3 rows.  The player will be allowed to have a hot key “F” in order to fire a charge at the centipede.  The player will maneuver and fire attempting to destroy body segments of the centipede.  For each hit 1 body piece will be removed from the centipede.  

Critical Classes:

	For this project I will need to create the following classes.

FlatLand:  I will modify the current version of Flatland and change the size to create a matrix of 20 rows and 24 columns.  

	mushroomObstacle:  I want to create and place 8 mushrooms in random locations on the FlatLand surface.  However the mushrooms will be excluded from occupying the bottom 3 rows so that they do impede the destroyerBot.  Their purpose is to alter the course and speed of the centipede.

centHeadBot:  This is the head of the centipede and it will lead the body segments through the playing field.  It will travel from position (0,0) until its reaches a bound (Flatland wall) where it will then drop down 1 row and reverse course.

centBodyBot:  These are the body segments of the centipede, 11 in total at the start.  They will function similar to AffinityBot from my assignment 3, Snake program.  They will follow the centHeadBot through the playing field.  

DestroyerBot:  this is the player in the Flatland.  This Bot will be controlled with the arrows keys (left, right, up, down).  Its movement will be limited to vertical and horizontal movement in the bottom 3 rows.  The “F” key will be set to fire cartridgeBot that when it contacts a cent object it will “destroy” remove the cent object part form the game.  
	
	NOTE1:  As discussed this is a creation that I may not have time to complete.  I will attempt to build this function however I would like to make an agreement will the professor that this functionality is a “bonus” of my design not a requirement for submission purposes.  If time does not allow completion of this function, this performance measure will be added to the continued work section.  

Deliverables:  I will submit a completed jar file with the required files, ( .class and .java) in order to execute the basic functions of the centipede game.  With this proposal I want to have my program achieve the following capabilities.

1.	Create a FlatLand object playing field of size 20,24 and be populated with 8 randomly located mushroom objects.
2.	Create a centipede object that will maneuver from position 0,0 and travel in a horizontal direction until it makes contact with a course modifier.  These are the Flatland walls or the mushroom objects.  When contact is made with a wall the centipede will drop down 1 row and reverse direction, no change in speed.  When contact is made with a mushroom object the centipede will drop down 1 row, reverse direction, and increase speed by 5% of the original speed.  I fit makes contact with the player’s destroyerBot the centipede will stop movement.
3.	Create a destroyerBot that the player will control with the arrows keys (left, right, up, down).  The object will move vertically and horizontally in the bottom 3 rows only. 

Additional work if time permits.

1.	Add a hot key “F” for the destroyerBot that will create a cartridgeBot object that will maneuver from the row and column of the destroyerBot vertically until it makes contact with a centipede object or Flatland object.  After contact the cartridgeBot will be removed from Flatland.
2.	Add a barrier object to help protect the destroyerBot.  Create 4 barrier objects size (1,2) randomly placed in rows 15 and 16 to help protect the destroyerBot from contact with the centipede.  Add functionality so that when the centipede makes contact with a barrier object it changes course by going up 1 row, reverse course, and decrease speed by 10% of the current speed.  








[[Category:Final Projects]]</text>
    </revision>
  </page>
  <page>
    <title>BLindberg Project</title>
    <id>169</id>
    <revision>
      <id>1173</id>
      <timestamp>2008-03-21T04:41:09Z</timestamp>
      <contributor>
        <username>Bdlindbe</username>
        <id>10</id>
      </contributor>
      <text xml:space="preserve"> Title: Live Video Texture Mapping using JOGL and Java Media Framework

Program File: 

Author: Brett D Lindberg, MAJ, USA

Description: This project is intended to explore live video texturing onto three dimensional objects using OpenGL and Java

Requirements:

Basic

1) Receive streaming video from a camera attached to the computer

2) Create a texture from the video

3) Map the texture onto a three-dimensional model (sphere or cube) and display


Follow-on
 
4) Create an object inside the textured object

5) Use the created 3D texture as an environment map

6) Implement lighting and user interactivity to the model
 

Material Requirements for Use: Any computer with a Webcam, Java 1.5, Java Media Framework, Java3d and JOGL (Java for OpenGL)

Performance Requirements: 

Quality Considerations: 

[[Category:Final Projects]]</text>
    </revision>
  </page>
  <page>
    <title>Beautiful Code</title>
    <id>93</id>
    <revision>
      <id>698</id>
      <timestamp>2008-01-29T05:07:46Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <text xml:space="preserve">What do we mean by the phrase '''Beautiful Code?'''

Here's what I mean:

* A clean design where the controls are ''orthogonal'' --- that is, changing one element causes that element to change and nothing else.
* Low code duplication. You don't see the same code in multiple places.
* Built for maintenance --- so when you come back to the code in the future, you can maintain it.
* Clean, simple documentation. Not too little, not too much. 
* Variables that are long enough so that it's clear what they mean, but not so long that they are a pain to type.


=Other Sources=
* [http://www.oreilly.com/catalog/9780596510046/ O'Reilly Media has a book on Beautiful Code] that you can purchase or download from Safari. (NPS has a Safari account.)
* There is a [http://beautifulcode.oreillynet.com/ Beautiful Code Blog]
* You may enjoy reading this [http://slashdot.org/askslashdot/01/01/25/0230208.shtml Slashdot article from 2001], but don't expect to learn a lot from it on first reading.
* Here is a [http://css-tricks.com/what-beautiful-html-code-looks-like/ Good article on beautiful HTML]
* [http://portal.acm.org/citation.cfm?id=1308450.1309096&amp;coll=guide&amp;dl= Rebecca J. Wirfs-Brock], Does Beautiful Code Imply Beautiful Design, November 2007.   Not quite sure why we can't download this from NPS...</text>
    </revision>
  </page>
  <page>
    <title>Blog</title>
    <id>78</id>
    <revision>
      <id>440</id>
      <timestamp>2008-01-14T01:37:22Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <comment>New page: Welcome to the CS3773 blog. Please look at the discussion page.</comment>
      <text xml:space="preserve">Welcome to the CS3773 blog. Please look at the discussion page.</text>
    </revision>
  </page>
  <page>
    <title>Brian Hawkins' Final Project</title>
    <id>164</id>
    <revision>
      <id>1200</id>
      <timestamp>2008-03-30T20:07:58Z</timestamp>
      <contributor>
        <username>Bmhawkin</username>
        <id>7</id>
      </contributor>
      <text xml:space="preserve">= Final Project – HyperGraph WebCrawler =


== Purpose ==

The purpose of my project is to develop a web crawler that builds a HyperGraph sitemap of the given URL.  The intent of the project is to accomplish this without the use of any external html parser or xml generator.

See http://hypergraph.sourceforge.net/



== Interface ==


The program has a basic GUI interface developed by the NetBeans IDE 6.0 GUI builder.  The user specifies the domain to crawl, the depth for the crawler, and the names of the html and xml files to generate.  The user can type the &lt;Enter&gt; key from any of the input fields or click the “Crawl!” button to start the crawl.  

 
When the program begins to crawl it provides the user with a couple of status messages and starts the progress bar.

Bug Alert - The progress bar, however, does not continue to update while the program crawls.

When the crawl is complete, the progress bar is filled, and the program attempts to launch Mozilla FireFox on the created html file to display the HyperGraph.  

Note: Currently, launching Mozilla Firefox will only work on a Windows operating system; assuming that it is installed.

If Mozilla Firefox fails to launch, the user is notified with an appropriate status message.


== Theory of Operation ==


'''The Basic Crawler'''
* 1. The crawler opens a connection and gets the raw html text of the URL entered in the GUI.  This URL is known as the root.
* 2. The crawler parses each line of html text looking for hyperlinks.
* 3. The crawler creates a HashSet of all of the hyperlinks found on the page; hyperlinks that navigate outside the domain of the root URL are ignored.
* 4. Once all of the page’s text has been parsed, the crawler adds the current page and it’s HashSet into a master HashTable that keeps track of all URLs that have been crawled.  
* 5. It then recursively calls itself on each of the hyperlinks found on the current page.
* 6. The crawler keeps track of how far away from the root it is crawling, and stops when the depth limit is exceeded.


'''The HyperGraph Generator'''
* 1. Once the crawler is complete, the HyperGraph is generated using the master HashTable.
* 2. The generator creates the html and xml files provided in the fields of the GUI, such that, the html file loads the HyperGraph applet which uses the xml file to display the HyperGraph.
* 3. The generator first goes through the HashTable, adding each URL as a node in the xml file.
* 4. The generator then goes through the HashTable a second time, adding an edge in the xml file from each URL to each hyperlink found on its page.
* 5. Once all the edges have been added, the generator is complete; all that remains is to open the html file with a web browser.



== Code Source ==


The only code not developed by the author is the code required to display the HyperGraph. These files are:

* GraphXML.dtd
* hyperapplet.jar

They can be downloaded from http://hypergraph.sourceforge.net/

These files must be in the same directory as the html and xml files in order for the HyperGraph to display in the web browser.
 
Note: Some code snippets may have originated from Sun’s Java Tutorial web pages at http://java.sun.com/docs/books/tutorial/

 

== Future Work ==


1.	Force the root URL to be the center of the graph.
Due to the under-documented nature of the HyperGraph source; there is not a known method to force a particular node to be the center of the HyperGraph when it is displayed. As a result when the applet is loaded, the root will not likely be the center of graph for any depth larger than zero, and the user will have to click and drag the HyperGraph display in order to find the root. I would like a future version to not have this quirk.

2.	Get the progress bar to display properly.
As noted in the Interface section, the progress bar freezes while the crawler is working. A future version would have a progress bar that moves until the crawl is complete. 

3.	Integrate a web browser into the program.
Currently, the program relies on the operating system to have an installed web browser in order to view the html and associated java applet. A future version should have an imbedded browser for displaying the HyperGraph.

4.	Clean up the output.
Currently the crawler is generating output to System.out and a log file. I have left these statements in the code so that I can watch the progress of the crawler. In future versions, in conjunction with fixing the progress bar, these should be removed.


[[Category:Final Projects]]</text>
    </revision>
  </page>
  <page>
    <title>Bug in Week 02 code</title>
    <id>84</id>
    <revision>
      <id>526</id>
      <timestamp>2008-01-18T02:39:39Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <text xml:space="preserve">Here is the old code for FlatlandObject.java:

&lt;pre&gt;
    public void paint(Graphics g){
	Graphics2D g2 = (Graphics2D) g;
	Size sz = getSize();
        int x = (int)(getCenter().x - sz.width/2.0);
        int y = (int)(getCenter().y - sz.height/2.0);
        g2.setStroke(new BasicStroke(3.0f));
        g2.setPaint(color!=null ? color : Color.BLACK);
        g2.draw(new Rectangle(x,y,(int)sz.width,(int)sz.height));
    }
&lt;/pre&gt;

here is the new code:

At the top of the file add:
  java.awt.geom.Rectangle2D

Then change paint() to be:

&lt;pre&gt;
    public void paint(Graphics g){
        Graphics2D g2 = (Graphics2D) g;
        Size sz = getSize();
        double x = (getCenter().x - sz.width/2.0);
        double y = (getCenter().y - sz.height/2.0);
        g2.setStroke(new BasicStroke(3.0f));
        g2.setPaint(color!=null ? color : Color.BLACK);
        g2.draw(new Rectangle2D.Double(x,y,sz.width,sz.height));
    }
&lt;/pre&gt;

Notice that the new code is easier-to-read.</text>
    </revision>
  </page>
  <page>
    <title>Bumped Readings</title>
    <id>103</id>
    <revision>
      <id>789</id>
      <timestamp>2008-02-04T15:59:08Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>New page: Readings that were bumped and may need to be integrated elsewhere:  * [[Media:P11-barowski.pdf|From C to Java: A Case Study in Portability, Efficiency, and Maintenance]] , Larry A. Barowsk...</comment>
      <text xml:space="preserve">Readings that were bumped and may need to be integrated elsewhere:

* [[Media:P11-barowski.pdf|From C to Java: A Case Study in Portability, Efficiency, and Maintenance]] , Larry A. Barowski, James H. Cross II, and T. Dean Hendrix, 2000</text>
    </revision>
  </page>
  <page>
    <title>CS3773 Java Style Guide</title>
    <id>2</id>
    <revision>
      <id>569</id>
      <timestamp>2008-01-22T04:33:18Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <comment>/* Naming */</comment>
      <text xml:space="preserve">=General=
The purpose of the style guide is not to restrict your programming. Instead, our goal is to establish a consistent format for your programs and to teach you about good programming style. This will help you debug and maintain your programs, and help others (including your instructor) to understand them. In the long run this will help you, since it can be just as hard to understand one's own code (especially after several months or years) as to understand something written by someone else.

=Visual Layout=
You should format your program source code by making use of blank lines and comments to separate code groups, functions and groups of logically related blocks.  As a general guideline, no block should be longer than one page.  

Output from a program should be both informative and professionally formatted. A person reading the output should be able to determine whether the program works reasonably, without knowing the internal details of the program.

For printed code, use 8.5 x 11 inch paper with 1 inch margins.  Use a fixed-width font (Courier, or Courier New works well) with a font size between 10 and 12 points.

=Indentation and Whitespace=
Indentation is used to highlight the block structure of the code and should be used consistently. The proper use of whitespace and indentation makes the structure of the program evident from the layout of the code.  

* Tabs should be set to 8, because that is standard. 
* Set indentation for 4, because it's easier to read than 2 or 8. 

In other words, your editor will need to automatically translate between the indentation level (4, 8, 12 characters) and what it should be indenting with (4 spaces, a tab, a tab and 4 spaces, etc). All modern editors can do this. Unfortunately, many programmers don't realize this and continue to do things such as setting their tab stops every 4 characters and then using tabs for indent. Don't model such behavior. 

Vertical whitespace is the use of blank lines to help set off blocks of code and increases readability of the program. Code with no vertical whitespace is difficult to follow.

No line of code should wrap beyond the right margin. If a line of code becomes too long, break it up into pieces with carriage returns.  Remember the Java compiler largely ignores extra whitespace in your programs (but be careful with strings).

The only text that should follow an opening brace (‘{‘) on a line of code is a comment. The exception to this rule is when you have a series of if statements and it's just easier to put all of the code on one line, like this:

&lt;pre&gt;
if (a==b) {c=3;d=6;}
if (a==f) {c=4; d=17;}
if (a==z) {c=32;jumpStart(3);}
&lt;/pre&gt;


The block of code enclosed by a set of braces must be indented inside the enclosing braces. A closing brace must always be on a line by itself and must be at the same level of indentation as the line containing the corresponding opening brace. 

==Comments==
Comments should be indented consistently with the block of code they describe.  

Comments can be divided into two general categories: strategic and tactical.  

'''Strategic comments''' are used to give the reader a general overview of what is going on.  These comments appear at the beginning of files and preceding class, method, and class variable declarations.  Strategic comments tend to be written in sentences with an emphasis on explaining the big picture of what the block of code is designed to do. 

'''Tactical comments''' are designed to explain tricky areas of code, what parameters do, and hints about the control flow of the program. These comments should be intermixed in the code when needed.  They should be shorter and in bullet format, and may be in inline format.

If you use sensible and informative naming, block structure, indentation, and straightforward programming, your code will be mostly self documenting. This is what you should strive for.  Keep comments simple.  Do not attempt to explain what is obvious from the code itself. 

Comments are the same as C++:  
* // comments to the end of the current line
* multiple line comments begin with /* and and with */.  

However, there is a new comment construct in Java:

* /** introduces a '''javadoc''' comment.  Javadoc comments are used for Java's automatic documentation system. You will be making a lot of use of this system in this course.

Numerical constants must have a comment explaining the value if this is not self-evident.  (And numerical constants should only be specified at the beginning of your class files, never within the code. See below.)

=== File Headers===
Each file should have a descriptive comment header block at the beginning as follows:
&lt;pre&gt;
/**                                                                                                                                                
 *  A single sentence describing the purpose of the class.                                                                                         
 *  Any additional info describing the class                                                                                                       
 *                                                                                                                                                 
 *   @filename    myfile.java   (or your file name)                                                                                                
 *   @date        2007-01-01  (or whatever the date is)                                                                                            
 *   @course      CS3773                                                                                                                           
 *   @homework    Week #                                                                                                                           
 *   @author      Your name                                                                                                                        
 */
&lt;/pre&gt;

===Header Comments -- classes===
Each class definition should have an appropriate “comment header” giving a brief description using the following format:

  /** 
   *  A single sentence describing the purpose of the class.
   *  Any additional info describing the class
   *
   *  @author &lt;your name&gt;
   */

The javadoc documentation tool that can automatically generate html documentation pages for your source code recognizes this style of comment. Sun’s Java API documentation was created using the javadoc tool.

===Header Comments -- methods===
Each method declaration or definition should have an appropriate “comment header” giving a brief description using the following format:
&lt;pre&gt;
/**                                                                                                                                                
 *  Return the square root of the specified value.                                                                                                 
 *                                                                                                                                                 
 *  @param     &lt;param-name&gt; &lt;param purpose&gt;.                                                                                     
 *  @return    &lt;describe the value returned&gt;.                                                                                                      
 *  @exception &lt;class name of any exception thrown by themethod&gt;                                                                                                  
 */

public float squareRoot(float value) throws ArithmeticException {
    . .	.
}
&lt;/pre&gt;

 
EXAMPLE:
&lt;pre&gt;
/**                                                                                                                                                
 *  Return the square root of the specified value.                                                                                                 
 *                                                                                                                                                 
 *  @param     value  the value to take the square root of.                                                                                        
 *  @return    the square root of the number.                                                                                                      
 *  @exception ArithmeticException                                                                                                                 
 */

public float squareRoot(float value) throws ArithmeticException {
    . .	.
}


&lt;/pre&gt;
===Header Comments – class variables===
Each class variable declaration must have an appropriate “comment header” giving a brief description using the following format:
  /**
   *  A single sentence describing the purpose of the variable.
   */

=Control Structures=
The use of braces is required (for style purposes, not syntax purposes) for all control structures, including those with a single statement in the body. Avoid the overuse of continue and break in loops.  Always use a default case in switch statements.  The use of // end if, // end while, and // end switch comments after the corresponding ending right brace is optional but suggested.

Indentation and formats for control structures are as follows.  Note the opening brace on the same line as the keyword.

The if statement:
  //left brace on same line
  if (boolean expression) {
     // statement(s);
  } else if (boolean expression) { // else if is optional
     // statement(s);
  } else {                         // else is optional
     // statement(s);
  } // end if &lt;optional comment&gt;

The for statement:
  //left brace on same line
  for (expression; expression; expression) {
     //statement(s);
  } //end for &lt;optional comment&gt;

The do/while statement:
  //left brace on same line
  do {
     //statement(s);
  } while (boolean expression);

 
The while statement:
  //left brace on same line
  while (boolean expression) {
     //statement(s);
  } //end while &lt;optional comment&gt;

The switch statement:
//left brace on same line
switch (expression) {
   case &lt;constant expression&gt;:
      //statement(s);
      break;
   case &lt;constant expression&gt;:
      //statement(s);
      break;
   case &lt;constant expression&gt;:
      //statement(s);
      //falls through          //a case with no break needs this comment
   default:                    //all switch statement should have default
      //statement(s);          //these statements are optional
      break;                   //all cases should have a break
  } //end switch &lt;optional comment&gt;

=Naming=
Variables must have meaningful names/identifiers. This must be balanced against using names which are too long, which can obscure the code. (Fifteen or so characters approaches the “too long” limit.) 

Single letter variables or constants should not be used. An exception to this rule is when it is common practice to identify some thing with a single letter. An example of this is the coordinate system (X, Y, and Z).  A second exception occurs in the use of loop counter variables where it is common practice to use variables like i and j as counters in for loops

Only class names should begin with a capital letter, all other identifiers (package names, method names, and variable names) should begin with a lower case letter. An identifier consisting of multiple names shall have each name distinguished by making the first letter of each name part upper case (e.g. redCarColor). Package names should be all lower case. 

Examples:
  package redcarcolor;
  class RedCarColor
  int redCarColor;

Names of constant (i.e. final) data members, as well as enumerated types, should be in all CAPITAL LETTERS.

Do not use the lower case letter `L’, or the letter `O’ in names unless they are part of normal words and it is necessary. This is to avoid confusion with the numbers 1 and 0.  For example, is “Cel1” C- e - l – ONE or C – e – l – l ?

Avoid names that differ only in case, look similar, or differ only slightly.  For example, InputData, InData and DataInput will certainly be confusing if used in the same program.

Names of methods should reflect what they do (printArray), or what they return (getAge). Boolean variable names should sound like Yes/No things – “isEmpty”  and “isFinished” are possible examples.

=Classes=
Class definitions should be ordered as follows:

* public data members
* protected data members
* private data members

* nested class definitions

* constructors

* public methods
* protected methods
* private methods

* main( )

= Functions=
Each function (starting with the function comment) must be separated from other code by at least two blank lines.

Functions may have one or more return statement, depending on what is appropriate.

=Files =
==Source Files==
Each source file must include all the necessary information to support its independent compilation.  
Do not add additional dependencies.   Each file must include only the necessary information to support independent compilation. Do not “import” the universe to see if that might help.
All Java source files will have a “.java” extension.
==Data Files==
If you open a data file for reading/writing, close the file as soon as you are done reading/writing to it.  Minimize multiple file opening/resets/closing if it can reasonably be avoided, as disk access times can be time-intensive and prone to failures.  Avoid using absolute path addressing when referring to data files unless referring to a file on the floppy disk drive. Use relative addressing based upon the location of the executable if possible. 
=Miscellaneous Important Stuff=
Always use the most appropriate operator or construct for the work you want it to do. Good design and clarity take precedence over optimization.  Do not declare or use more variables than are necessary.

Always use the principle of least privilege (grant only that access necessary to do the desired work and no more).
Use the ‘try’, ‘throw’, and ‘catch’ exception handling mechanisms where appropriate.  Additionally, use specific exceptions (IOException, for instance) rather than the more general Exception where possible.

Numerical constants (&quot;magic numbers&quot;) must not be coded directly.  The only allowable exceptions are for 0, 1 or -1, and those which are not &quot;likely&quot; to change; for example code determining if a number is even can use the number &quot;2&quot; since it would not be likely to change. Numerical constants must have a comment explaining the value if it is not evident from the name.
You should test floating point numbers with &lt;= or &gt;=. Never use exact comparisons with floating point numbers, even when comparing to 0.0. The appropriate means of comparison is to define a value (in engineering lingo, “epsilon” ) that represents the maximum difference two values may differ and be considered equal.

If you use any public domain or shareware code, or code from one of the textbooks, there are two requirements:  First, you must credit the source in the header block and be specific as to where it comes from.  Second, if it is going into your program, you MUST understand it completely.  If you cannot explain what it is doing, then it does NOT go into a program that you turn in for grading.  If asked to explain it and you cannot do so to the instructor’s satisfaction, you will not get credit for it and will have your grade adjusted accordingly.  The goal is to have you understand what is going on in the program.  Other student’s code does NOT qualify as “shareware” or public domain code for the purposes of this paragraph.
You should test your code. It should produce the correct results for normal test conditions as well as boundary conditions like short or empty lists.

DO NOT modify project specifications without explicit permission from your customer (the instructor)!
Even if you think you have explicit permission to modify project specifications, modifications from the written assignment provided must be clearly and completely documented in your code and in your “Readme.txt” file.

=Project Guidance: What to turn in=
You must turn in the following information for each project:

# A jar file which is uploaded to the class website. This should contain your source code, your class files (if the code complies), and an (optional) README.txt file that has anything you want me to read.  
# If you use any packages other than the standard Java packages, you should package them into your jar file as well. Put them in the jar file AFTER your materials.

=Additional Information=
Additional information on style issues can be found at:

http://java.sun.com/docs/codeconv/html/CodeConventionsTOC.doc.html</text>
    </revision>
  </page>
  <page>
    <title>Christian Fitzpatrick's Final Proposal</title>
    <id>146</id>
    <revision>
      <id>1175</id>
      <timestamp>2008-03-26T19:14:37Z</timestamp>
      <contributor>
        <username>Crfitzpa</username>
        <id>16</id>
      </contributor>
      <text xml:space="preserve">Title: The Interactive Periodic Table Learning Tool

Program File: ElementUI.java

Creator:  Major Christian Fitzpatrick, USMC (CS 3773 Student, Naval Postgraduate School)

Advisor: Professor Simson Garfinkel, PhD.

Description:  The Interactive Periodic Table Learning Tool is a graphical user interface that will allow students to quickly access interesting information about all elements in the periodic table.  

The GUI will be manually created in the Java NetBeans GUI Builder set up in the shape of the periodic table with each element having its own JButton.  

When the program begins, it:
•	downloads http://simple.wikipedia.org/wiki/List_of_elements, 
•	parses the wiki list,
•	creates an instance of the element description class, and puts the data into a hash table.  

Buttons have been created in the JPanel.

Once the hash table is loaded, the program will iterate through each button in the JPanel and then pressing any button will display information in a text area below the periodic table.  


Test Methods: Upon completion, the program will be checked by two users on two different computers.  Program will be checked for proper loading of the wiki, correct parsing, and proper button operation by all users on all computers.

Material Requirements for Use: Any computer or laptop with the NetBeans IDE 6.0 or the Eclipse IDE.

Performance Requirements: The http://simple.wikipedia.org/wiki/List_of_elements will be properly parsed to a hash table.  Each JButton will be properly linked to the hash table and the appropriate information will be displayed in each text area.

Quality Considerations:  It is inteded that this program could be used at the high school level for quick reference while students complete homework problems.  It is also expected that this program can be updated as students become more advanced.  The first release will contain limited information about each element.

Completion Delivery: 27 March 2008

Provision for Inspection/Rejection/Corrective Measures:  ElementUI.java will be submitted to advisor 3 days prior to completion delivery for review and inspection.  Student will await feedback and be ready to make corrections as needed.
[[Category:Final Projects]]</text>
    </revision>
  </page>
  <page>
    <title>Coming Attactions</title>
    <id>132</id>
    <revision>
      <id>943</id>
      <timestamp>2008-02-29T17:02:52Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <comment>[[Coming Attactions]] moved to [[Coming Attractions]]</comment>
      <text xml:space="preserve">#REDIRECT [[Coming Attractions]]</text>
    </revision>
  </page>
  <page>
    <title>Coming Attractions</title>
    <id>131</id>
    <revision>
      <id>964</id>
      <timestamp>2008-03-03T08:33:53Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">Please feel free to add to this page things that you would like to see taught or demonstrated in class in the remaining weeks.


* Making the Flatland wall actually bounce balls.
* Java Security Policy and security policy files.
* Drawing text in screen coordinates when the graphics context has been scaled to world coordinates.
* Click on Flatland objects to move them around.
* Comparison of double and float performance
* How IEEE floating point actually works
* Reflection
*</text>
    </revision>
  </page>
  <page>
    <title>Compiling files in a project</title>
    <id>99</id>
    <revision>
      <id>766</id>
      <timestamp>2008-02-01T16:12:41Z</timestamp>
      <contributor>
        <username>Kjmaroon</username>
        <id>6</id>
      </contributor>
      <comment>New page: If you are compiling from the command line dont forget to set the classpath if you are working from something other than the default directory.  For example if I want to compile CTest in t...</comment>
      <text xml:space="preserve">If you are compiling from the command line dont forget to set the classpath if you are working from something other than the default directory.

For example if I want to compile CTest in the hw4 package:

C:Documents and Settings\localadmin\My Documents\CS3773\Assignemtnt 4\src\hw4 javac CTest.java

the line above will give me an error because it is looking for files in  \hw4

instead, set the classpath (as long as the other files are in the same directory) with &quot;..&quot; as below

C:Documents and Settings\localadmin\My Documents\CS3773\Assignemtnt 4\src\hw4 javac -classpath .. CTest.java</text>
    </revision>
  </page>
  <page>
    <title>Crschwet &quot;final project proposal&quot;</title>
    <id>147</id>
    <revision>
      <id>1144</id>
      <timestamp>2008-03-20T02:19:55Z</timestamp>
      <contributor>
        <username>Crschwet</username>
        <id>15</id>
      </contributor>
      <comment>/* TDG #3 - Military Functions in Civil Disturbances */</comment>
      <text xml:space="preserve">I would like to create an interactive Java-based Tactical Decision Game.  


'''Tactical Decision Games (TDGs)''' are exercises designed to increase the understanding of military tactics and decision-making.  


'''TDG TOOLS include some of the following:'''

'''BAMCIS (Troop Leading Steps)'''

- Begin the planning

- Arrange reconnaissance

- Make the reconnaissance

- Complete the plan

- Issue orders

- Supervise

'''SMEAC (5-Paragraph Order)'''

- Situation

- Mission

- Execution

- Admin and Logistics

- Command and Signals
		

Here is an example of how a Tactical Decision Game works from http://www.militaryspot.com/tdg.htm :



== TDG #3 - Military Functions in Civil Disturbances ==


'''First you get the situation -'''

It's early 1993 and you are Attorney General Janet Reno. A situation at a religious compound near Waco, Texas is necessitating your attention. A federal raid on the compound has gone bad. Armed militants within the compound have repulsed the raid and killed several federal agents. Inside the compound are approximately 80 people. About 15 people are thought to be armed and dangerous. The rest - women, children and the elderly - are not considered dangerous, though they are considered to be brainwashed by David Koresh, the charismatic and demented leader of the compound. 

The standoff is now dragging into the second month, and federal authorities on the scene want a resolution to the crisis. They want you to authorize military force against the compound to end the siege. Specifically, the authorities want you to authorize the use of military CS riot control agents within the walls of the compound. Do you authorize or deny the use of CS riot control agents within the compound?
 
(Hint: The solution to this TDG has a very specific military textbook answer.)


'''A time limit to solve the problem could be placed (i.e. 2–10 minutes or a clock counting up to give a plan.)'''


'''Maps and images can also be added to create better situational awareness.'''
*These images relate to another TDG scenario and are only included here to show what can be added to the game.
[[Image:tdg.jpg]]

[[Image:tdg2.jpg]]

'''The player then gives their solution before the time runs out or they could stop the timer before the time runs out (similar to a freeze technique used by an instructor during a  training evolution):'''


According to the situation, I won't use CS or other chemicals. Rationale: Most of the people in the compound are &quot;victims&quot;, and the use of these agents wouldn't be the right choice to cope with this situation.
According to the Law in Hungary for example, the military does NOT have responsibilities in Civil Disturbance operations, unless the President calls for State of Emergency.
So in this situation the State Police and the Feds should work only, not the military. The use of military in this situation would be very nasty, and the political echo would be detrimenal for the Governor of that State, and even for the POTUS.
In conclusion:
Military can be used as a last resolution, but normally it should be used abroad, on theaters of operations (Afghanistan, Iraq etc.) for coping with Civil Disturbance operations.
We have a good place for training these situation, called the National Education Centre within the Ministry of Internal Affairs, where for some deployments military personnel receives training.


'''The player could then check their answer with a recommended solution:'''


According to U.S. Military manuals available at the time, riot control agents should not be used in closed structures except under extreme circumstances. According to FM 19-15:

&quot;Generally, persons reacting to CS are incapable of executing organized and concerted actions and excessive exposure to CS may make them incapable of vacating the area.&quot;

&quot; The riot control agent dispersers should not be used to introduce a riot control agent directly into a closed structure except under extreme circumstances.&quot;

Therefore, there are no justifications for the use of CS riot control agents in this scenario.


'''There could then be links to any referenced manuals as was the case here in this example and the player could compare answers.  This could be a very useful interactive learning tool which provides immediate feedback.'''

== Here is a possible layout: ==
[[Image:Final Project_possible layout.jpg]]
[[Category:Final Projects]]

----

--[[User:Crschwet|Crschwet]] 21:47, 11 March 2008 (PDT)</text>
    </revision>
  </page>
  <page>
    <title>Equals</title>
    <id>62</id>
    <revision>
      <id>297</id>
      <timestamp>2007-12-09T18:48:34Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <comment>New page: =References= * [http://www.ibm.com/developerworks/java/library/j-jtp05273.html hashCode() and equals()] disussed on IBM's developer network.</comment>
      <text xml:space="preserve">=References=
* [http://www.ibm.com/developerworks/java/library/j-jtp05273.html hashCode() and equals()] disussed on IBM's developer network.</text>
    </revision>
  </page>
  <page>
    <title>Equations of Motion</title>
    <id>90</id>
    <revision>
      <id>624</id>
      <timestamp>2008-01-27T04:19:37Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <comment>/* Electrostatics */</comment>
      <text xml:space="preserve">If you are creating a simulation where objects can move, you need to create ''equations of motion'' that will describe how they move over time.

=Basic Motion=
Every object that can move needs to have a few ''state variables'' that keep track of the object's current state. These state variables are typically implemented as double precession instance variables of an object, where the class of the object corresponds to the object that is being modeled. Here are some variables:
&lt;pre&gt;
double x,y;        // current position  (might be implemented as a Location object)
double heading;
double speed
&lt;/pre&gt;

Every clock tick of the simulation, you need to calculate how the motion vector (heading &amp; speed) will affect x and y. The typical equations used here are:

&lt;pre&gt;
   newX = x + sin(heading) * speed;
   newY = y  + cos(heading) *speed;
&lt;/pre&gt;

Of course, in our Flatland simulation, y is flipped, so the equations that we've been using are actually:
&lt;pre&gt;
   newX = x + sin(heading) * speed;
   newY = y  - cos(heading) *speed;
&lt;/pre&gt;

Which we have actually implemented with dx,dy and the Location object: 

&lt;pre&gt;
   double dx = sin(heading) * speed;
   double dy = - cos(heading) *speed;
   Location newLocation = new Location(currentLocation.x + dx, currentLocation.y + dy);
&lt;/pre&gt;

=Electrostatics=
In the electrostatic simulation, you have the situation where ''every'' object in Flatland affects every other object.  They do this through charge. Objects with the same charges repel, while objects with different charges attract.

The electrostatic force between any two objects is described by [http://en.wikipedia.org/wiki/Coulomb's_law Coulomb's Law]. In our Flatland world, this can be approximated as:

&lt;pre&gt;
force = - scaleFactor * (charge1) * (charge2) / (distance*distance);
&lt;/pre&gt;

Where '''charge1''' is the charge of the first object and '''charge2''' is the charge of the second object and '''distance''' is the distance between them, and '''scaleFactor''' is a factor that you'll need to fiddle with to make things look good.

force is a vector force which is going to have x and y components:

&lt;pre&gt;
forceX = sin(bearing) * force;
forceY = -cos(bearing) * foce;
&lt;/pre&gt;
where bearing is bearing of object#2 from object#1.

To calculate the total force on object#1, you could simply calculate the sum of all the forceX's and the forceY's for all of the other objects. The pseudo-code would look something like this:

&lt;pre&gt;
totalDVX = 0;
totalDVY = 0;
for(FlatlandObject o: objects){
   if(object1 == o) continue;
   bearing = (bearing of object2 from object1)
   distance = (distance of object2 from object1)
   force = -scaleFactor * (charge1) * (charge2) / (distance*distance);
   forceX = sin(bearing) * force;
   forceY = -cos(bearing) * force;
   totalDVX += forceX;
   totalDVY += forceY;
}
&lt;/pre&gt;

Now the thing to note here is that totalDVX and totalDVY is the total force acting on the object (object1; we'll repeat this for object2). But it's not the change position (dx,dy) --- it's the change in velocity. So you really need to take the old velocity, turn it into a movement vector, and then add totalDVX,totalDVY to this vector, and turn it back into heading and speed. You would do it something like this:

&lt;pre&gt;
   double dx = sin(heading) * speed;
   double dy = - cos(heading) *speed;
   dx += totalDVX;
   dy += totalDVY;
   newSpeed = sqrt(dx*dx + dy*dy);
   newHeading = -atan2(dx,dy);
&lt;/pre&gt;

Make sense?  Now you need to turn the pseudocode into real code.</text>
    </revision>
  </page>
  <page>
    <title>Exercises 1</title>
    <id>130</id>
    <revision>
      <id>932</id>
      <timestamp>2008-02-29T05:35:35Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">You may substitute this set of three exercises for a previously-assigned homework:

=Adder=
Create a program using NetBeans and the Java GUI builder that has:
*  two editable text fields: fieldA and fieldB
* a push button: addButton
* and a text field that is not editable: fieldR

When the push button is pressed the numbers in fieldA and fieldB should be added together and the result placed in fieldR.

=4 Function=
* Modify the Adder program to have four push-buttons: ADD, SUB, MULT and DIV. 
* Implement the appropriate functions.

=Shape Drawer=
Create a program using NetBeans and the Java GUI builder that has:
* A JComponent where drawing takes place
* A text field: fieldSides

=Load &amp; Save for Flatland=
Using object serialization, implement load &amp; save for Flatland.</text>
    </revision>
  </page>
  <page>
    <title>Final Project</title>
    <id>136</id>
    <revision>
      <id>1195</id>
      <timestamp>2008-03-28T04:35:16Z</timestamp>
      <contributor>
        <username>Bdlindbe</username>
        <id>10</id>
      </contributor>
      <text xml:space="preserve">Final Projects are due on March 27th

Your final project must include:
* Final Project Proposal
* Java source code that is '''well-written''' and '''well-documented.'''
* A written specification of at least one page that describes:
** The program's purpose.
** The program's interface with the outside world.
** The program's theory-of-operation.
** What is original, and what (if anything) was developed by others.
** Future work that can be done.
* Screen shots.

=To Create Your Final Project Proposal=
If you wish, you may put your final project proposals on this wiki. If you would prefer not to, you may email the final project proposal to the course staff.


To enter the proposal on the wiki:
# Type your name and the words &quot;final project proposal&quot; into the Search box at the left of this window.
# MediaWiki will ask if you want to create a new page; click &quot;yes&quot;
# Enter your proposal.
# When you are done, please click &quot;save page&quot;

Note: You will be responsible for making sure that your final project matches what was promised in the proposal. If you put your proposal on the wiki it will be easier for you to keep the proposal up to date as the project changes.

=What to turn in=
* A jar file (please submit using the online system and e-mail a copy to the professor)
* A PDF file with your specification and screen shots (please upload separately and email to me if you can't get that to work.)
=See Also=
[[Final Project Ideas]]</text>
    </revision>
  </page>
  <page>
    <title>Final Project Ideas</title>
    <id>125</id>
    <revision>
      <id>950</id>
      <timestamp>2008-03-02T07:31:23Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">Here are what some of the students in CS3773 are thinking of doing for their final projects:

* Using Flatland as a basis, create an interactive map (or simulation) of the NPS campus.
* Using Flatland as a basis, create a simulation involving aircraft or boats with realistic behaviors.
* A system to visualize security and network health alerts in real time.

* A scientific calculator

* Visualize the periodic table of the elements with two different visualizations.

* Java-based Tactical Decision Games

* A web crawler that builds a [http://hypergraph.sourceforge.net/ hypergraph] in an applet when given a URL to crawl.

* Pong, the well known program from the 1980s. Initial implementation will have two players, one using the arrow keys, one using the a &amp; z key. Second implementation will use game controllers.

* Draw flatland in 3D.

* Implement a video game, using Flatland as a base:
** Space Invaders
** Lunar Lander 
Watch this page for updates.</text>
    </revision>
  </page>
  <page>
    <title>Final Project Proposal (Wyatt)</title>
    <id>159</id>
    <revision>
      <id>1082</id>
      <timestamp>2008-03-17T15:41:00Z</timestamp>
      <contributor>
        <username>Tdwyatt</username>
        <id>11</id>
      </contributor>
      <comment>[[Final Project Proposal (Wyatt)]] moved to [[Wyatt - Final Project Proposal]]: Updated title</comment>
      <text xml:space="preserve">#REDIRECT [[Wyatt - Final Project Proposal]]</text>
    </revision>
  </page>
  <page>
    <title>Fixed Newton</title>
    <id>119</id>
    <revision>
      <id>874</id>
      <timestamp>2008-02-15T17:57:07Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>New page: &lt;pre&gt; package JavaApplication3;  import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.awt.image.*;  public class Newton extends JPanel {      static JFrame frame; ...</comment>
      <text xml:space="preserve">&lt;pre&gt;
package JavaApplication3;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;

public class Newton extends JPanel {

    static JFrame frame;
    JLabel picture; // where the fractal is going to be drawn
    Dimension defaultSize = new Dimension(640,480);
    
    Dimension lastPaintSize = null;
    final int initialOrder = 4;
    
    public void paint(Graphics g){
        if(picture.getSize().equals(lastPaintSize)==false){
            computeFractal(fractalOrder);
        }
        super.paint(g);
    }
    
    public Newton() {
        JPanel radioPanel = new JPanel();
        radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));

        RadioListener myListener = new RadioListener();
        ButtonGroup group = new ButtonGroup();
        for (int i = 3; i &lt;= 9; i++) {
            String buttonText = &quot;&quot; + i;
            JRadioButton but = new JRadioButton(buttonText);
            but.addActionListener(myListener);
            but.setActionCommand(buttonText);
            if (i == initialOrder) {
                but.setSelected(true);
            }
            group.add(but);
            radioPanel.add(but);
        }
        picture = new JLabel();
        picture.setPreferredSize(defaultSize);
        setLayout(new BorderLayout());
        add(radioPanel, BorderLayout.WEST);
        add(picture, BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        computeFractal(initialOrder);
    }
    static Color[] colorArray = new Color[]{
        Color.GREEN,
        Color.BLUE,
        Color.BLACK,
        Color.CYAN,
        Color.RED,
        Color.MAGENTA,
        Color.ORANGE,
        Color.LIGHT_GRAY,
        Color.DARK_GRAY,
        new Color(84, 84, 255), // Light Blue
        new Color(84, 255, 84), // Light Green
        new Color(84, 255, 255), // Light Cyan
        Color.PINK,
        new Color(255, 84, 255), // Light Magenta 
        Color.YELLOW,
        Color.WHITE
    };

    
    public void computeFractal(int polynominalOrder) {
        int xsize = picture.getWidth();
        int ysize = picture.getHeight();
        //System.out.println(&quot;xsize=&quot;+xsize);
        int pixels[] = new int[xsize * (ysize + 1)];
        double left = -1.5;
        double right = 1.5;
        double top = 1.25;
        double bottom = -1.25;
        double deltaP = (right - left) / xsize;
        double deltaQ = (top - bottom) / ysize;
        final double errorTollerance = 1E-10;
        for (int col = 0; col &lt; xsize; col++) {
            for (int row = 0; row &lt; ysize; row++) {
                double x = left + col * deltaP;
                double y = top - row * deltaQ;
                double prev_x = 42;
                double prev_y = 42;
                int iterationCounter = 0;
                while (((Math.abs(prev_x - x) &gt; errorTollerance) || (Math.abs(prev_y - y) &gt; errorTollerance)) &amp;&amp; iterationCounter &lt; 512) {

                    double denom = Double.NaN;
                    double temp = 0;
                    prev_x = x;
                    prev_y = y;
                    switch (polynominalOrder) {
                        case 3:

                            double x2 = x * x;
                            double y2 = y * y;
                            denom = 3.0 * ((x2 - y2) * (x2 - y2) + 4.0 * x2 * y2);
                            if (denom == 0.0) {
                                denom = 0.00000001;
                            }
                            temp = .6666667 * x + (x2 - y2) / denom;
                            y = .6666667 * y - 2.0 * x * y / denom;
                            x = temp;
                            break;

                        case 4:
                            double w = x * x * x - 3.0 * x * y * y;
                            double v = 3.0 * x * x * y - y * y * y;
                            denom = 4.0 * (w * w + v * v);
                            if (denom == 0.0) {
                                denom = 0.00000001;
                            }
                            temp = .75 * x - w / denom;
                            y = .75 * y + v / denom;
                            x = temp;
                            break;

                        case 5:
                            w = x * x * x * x - 6.0 * x * x * y * y + y * y * y * y;
                            v = 4.0 * x * x * x * y - 4.0 * x * y * y * y;
                            denom = 5.0 * (w * w + v * v);
                            if (denom == 0.0) {
                                denom = 0.00000001;
                            }
                            temp = .8 * x - w / denom;
                            y = .8 * y + v / denom;
                            x = temp;
                            break;

                        case 6:
                            w = x * x * x * x * x - 10.0 * x * x * x * y * y + 5.0 * x * y * y * y * y;
                            v = 5.0 * x * x * x * x * y - 10.0 * x * x * y * y * y + y * y * y * y * y;
                            denom = 6.0 * (w * w + v * v);
                            if (denom == 0.0) {
                                denom = 0.00000001;
                            }
                            temp = .8333333 * x - w / denom;
                            y = .8333333 * y + v / denom;
                            x = temp;
                            break;

                        case 7:
                            w = x * x * x * x * x * x - 15.0 * x * x * x * x * y * y + 15.0 * x * x * y * y * y * y - y * y * y * y * y * y;
                            v = 6.0 * x * x * x * x * x * y - 20.0 * x * x * x * y * y * y + 6.0 * x * y * y * y * y * y;
                            denom = 7.0 * (w * w + v * v);
                            if (denom == 0.0) {
                                denom = 0.00000001;
                            }
                            temp = .85714285 * x - w / denom;
                            y = .85714285 * y + v / denom;
                            x = temp;
                            break;
                        case 8:
                            w = x * x * x * x * x * x * x - 21.0 * x * x * x * x * x * y * y + 35.0 * x * x * x * y * y * y * y - 7.0 * x * y * y * y * y * y * y;
                            v = 7.0 * x * x * x * x * x * x * y - 35.0 * x * x * x * x * y * y * y + 21.0 * x * x * y * y * y * y * y - y * y * y * y * y * y * y;
                            denom = 8.0 * (w * w + v * v);
                            if (denom == 0.0) {
                                denom = 0.00000001;
                            }
                            temp = .875 * x - w / denom;
                            y = .875 * y + v / denom;
                            x = temp;
                            break;

                        case 9:
                            x2 = x * x;
                            y2 = y * y;
                            double x3 = x * x2;
                            double x4 = x2 * x2;
                            double x5 = x4 * x;
                            double x6 = x4 * x2;
                            double x7 = x6 * x;
                            double x8 = x7 * x;
                            double y3 = y * y2;
                            double y4 = y2 * y2;
                            double y5 = y4 * y;
                            double y6 = y4 * y2;
                            double y7 = y6 * y;
                            double y8 = y7 * y;
                            double square_sum = x2 + y2;
                            double ss2 = square_sum * square_sum;
                            double ss4 = ss2 * ss2;
                            denom = 9.0 * ss4 * ss4;
                            if (denom == 0) {
                                denom = 0.0000001;
                            }
                            temp = 0.88888888 * y - (8.0 * x7 * y -
                                    56.0 * x5 * y3 + 56.0 * x3 * y5 - 8.0 * x * y7) / denom;
                            x = 0.88888888 * x + (x8 -
                                    28.0 * x6 * y2 + 70.0 * x4 * y4 -
                                    28.0 * x2 * y6 + y8) / denom;
                            y = temp;
                            break;
                    }
                    iterationCounter++;
                }
                pixels[row * xsize + col] = colorArray[iterationCounter % colorArray.length].getRGB();
            }
        }
        ImageIcon bp = new ImageIcon(createImage(new MemoryImageSource(xsize, ysize, pixels, 0, xsize)));
        picture.setIcon(bp);
        fractalOrder = polynominalOrder;
        lastPaintSize = picture.getSize();
    }

    int fractalOrder = initialOrder;
    class RadioListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            fractalOrder = Integer.parseInt(e.getActionCommand());
            computeFractal(fractalOrder);
        }
    }

    
    public static void main(String s[]) {
        frame = new JFrame(&quot;Newton's Method Fractals&quot;);
        frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        frame.getContentPane().add(new Newton(), BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }
}

&lt;/pre&gt;</text>
    </revision>
  </page>
  <page>
    <title>GUI Design</title>
    <id>67</id>
    <revision>
      <id>327</id>
      <timestamp>2007-12-10T06:49:09Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <text xml:space="preserve">=Custom subclasses with NetBeans GUI Builder=
You can create your own subclasses with the NetBeans GUI builder:

# Just create the java component that you'll want to subclass.
# Select the component, go to the Properties window, select Code tab, and enter a ''Custom Creation Code'' property that contains the Java code to create the object. For example, if you want to create a MyJLabel instead of a JLabel, enter:
  new MyJLabel();
note: Be sure that you create the MyJLabel() class and that it extends javax.swing.JLabel.

More details can be found at the NetBeans Wiki [http://wiki.netbeans.info/wiki/view/FaqFormUsingCustomComponent article on using Custom Components].

=References=
Tools for designing and coding GUIs:
* [http://java.sun.com/developer/technicalArticles/tools/nb_guibuilder/ Create Great-Looking GUIs with NetBeans IDE 5.5] (Sun Microsystems)
* [http://form.netbeans.org/NetBeans Form Creation Tool (Matisse)]
* [http://www.netbeans.org/kb/50/quickstart-gui.html NetBeans QuickStart]
* [http://www.netbeans.org/kb/articles/matisse.html Java GUIs and Project Matisse Learning Trail]
* [http://java.sun.com/docs/books/tutorial/uiswing/index.html The Java Tutorials: Creating a GUI with JFC/Swing]
* [http://www.netbeans.org/kb/articles/gui-functionality.html Adding Functionality to Buttons: A Beginners Guide (15 minutes)]</text>
    </revision>
  </page>
  <page>
    <title>Habel final project proposal</title>
    <id>152</id>
    <revision>
      <id>1052</id>
      <timestamp>2008-03-12T15:23:33Z</timestamp>
      <contributor>
        <username>Habel</username>
        <id>12</id>
      </contributor>
      <text xml:space="preserve">[[Category:Final Projects]]

Heiko Abel final project proposal - PONG

Professor advisor: S. Garfinkel


I would like to rebuild the game pong as seen on the first TV-console version.

The game will use Flatland as a building stone and add the game capability to it.
By the time of turn-in, the game will have the following features:

- a ball, bouncing off the top and bottom sidelines

- two rackets to play with, the ball bouncing off them depending on where it hits as seen
from the center of the racket. Maximum reflection is +- 45 degrees

- Rackets are controlled by keyboard, using (s,x) for the left and (Arrow_UP,Arrow_ DOWN) for the right player 

- Increasing difficulty levels

- a visual display as when the next level begins

- a visual display as how long the game takes

- an optional computer player for the left racket

- a player looses when the ball crosses beyond the x-position of the rackets


I hope to recreate a game that will be easily played and will take about five minutes to complete, just
long enough to unstress.

Test Methods: Upon completion, the program will be checked by three users on three different computers. Program will be checked for proper loading of the game, correct playing, and proper loosing algorithm operation by all users on all computers.

Material Requirements for Use: Any computer or laptop with the NetBeans IDE 6.0 or the Eclipse IDE.

Performance Requirements: Rackets move, ball bounces correctly, and the Game has an definitive endstate.

Quality Considerations: It is intended that this program could be used during any persons leisure time. It should be fun to play and
fun to loose to the computer player. 

Completion Delivery: 26 March 2008

Provision for Inspection/Rejection/Corrective Measures: Pong.jar will be submitted to advisor 3 days prior to completion delivery for review and inspection. Student will await feedback and be ready to make corrections as needed.

[[User:Habel|Habel]]</text>
    </revision>
  </page>
  <page>
    <title>Information on setting JAVA HOME and CLASSPATH on Windows 95/98</title>
    <id>43</id>
    <revision>
      <id>261</id>
      <timestamp>2007-12-05T07:01:06Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>2</id>
      </contributor>
      <comment>New page: If for some reason you are using a Windows95/98 system, you need to set up your environment variables in your autoexec.bat file.  The PATH informs your operating system which directories t...</comment>
      <text xml:space="preserve">If for some reason you are using a Windows95/98 system, you need to set up your environment variables in your autoexec.bat file.

The PATH informs your operating system which directories to search in to locate executable file. Your PATH variable must point to the location of your JDK tools. Include the following lines at the end of your autoexec.bat file to configure your PATH:

  SET JAVA_HOME=&quot;C:\Program Files\Java\jdk1.6.0_03&quot;
  SET PATH=%PATH%;%JAVA_HOME%\bin

JAVA_HOME is and environment variable that should point to the root directory of your Java installation. If you ever decide to use a different Java setup, you can simply change JAVA_HOME and your PATH will be automatically reflect the changes. The second line says that the bin subdirectory in your Java installation directory should be included in the your system search PATH.

The CLASSPATH environment variable is used by the JDK tools to locate pre-defined class files (object definitions) that you may use in your projects. Any directory that contains classes you wish to reuse should be listed in the CLASSPATH variable.  Java can automatically find the standard JDK classes.  Since we will often have our own classes residing in either the current or the classes directory, the current directory is also a nice thing to have in your CLASSPATH. To configure a minimum CLASSPATH, include the following line at the end of your autoexec.bat file:

  set CLASSPATH=.;classes

As you learn more about Java, you will from time to time need to temporarily add new directories to your CLASSPATH, you can do this with something like the following:

  set CLASSPATH=%CLASSPATH%;C:\some\new\dir

which appends a new directory C:\some\new\dir to the end of the existing CLASSPATH. This line should follow your initial CLASSPATH declaration.</text>
    </revision>
  </page>
  <page>
    <title>JAVA Security</title>
    <id>165</id>
    <revision>
      <id>1140</id>
      <timestamp>2008-03-19T15:41:47Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>/* References */</comment>
      <text xml:space="preserve">=Java Security Concepts=
* http://java.sun.com/javase/technologies/security/

# Java Designed for downloading code.
# Code designed to be &quot;safe&quot;
#* No buffer overflows
#* Safe types
#* Can't access private data with unsafe casts

; Sandbox: Applets run in the sandbox.
; Class Loader: Downloads the applets, verifies them, and puts them into the JVM.
; Byte Code Verifier: Check sfor:
* Properly formatted code.
* Internal stacks will not underflow
* No illegal type conversions
* Classes do not access private data of other classes.

; Security Manager: Controls what a program an do.
* Manages network sockets
* Guards access to protected resources
* Controls creation of and access to OS programs and processes
* Controls the class loader
* Manages threads
* Controls access to Java packages.

=Tools for Implementing Security=
* Type safety
* Bytecode verification at load time.
** Detects type violations
** Detects stack underflows and memory management violations.
** Not perfect.

==Java Security Providers and Permissions==
 java.security.Provider
* Controls access to system resources
* Pluggable

  java.security.Permissions
* Controls what code can do what.
* For example, access to certain files, directories, network ports.


==Java Cryptography==
* Full set of encryption routines
* Full PKI implementation
* SSL/TLS
* Code can be signed.


==Java Authentication Framework==
* Plugable framework supports Smartcard, Kerberos, Username/Password


==Java Security Policy==
The Java Policy file defines what Java programs are allowed to do when they run.
* No file: Wide open
* Applet: [[java.policy]]
* Policy for Webstart: [[javaws.policy]]

Specify an Additional Policy File at Runtime:
      java -Djava.security.manager -Djava.security.policy=someURL SomeApp

Specifying a different Policy file at runtime:
      java -Djava.security.manager -Djava.security.policy==someURL SomeApp

=References=
* [http://java.sun.com/developer/technicalArticles/Security/whitepaper/JS_White_Paper.pdf Java Security Overview WhitePaper]
* [http://java.sun.com/j2se/1.5.0/docs/guide/security/PolicyFiles.html Default Policy Implementation and Policy File Syntax]
* [http://oscar.objectweb.org/security.html Oscar Security]
* [http://ise.gmu.edu/~skaushik/courses/AL.ppt Adil Lahjouji's Slides (GMU)]
* [https://www28.cplan.com/cb_export/PS_TS-1660_277660_124-1_FIN_v2.pdf Brian Chess Slides] (username: contentbuilder; password: doc789)
* [http://www.tml.tkk.fi/Opinnot/T-110.7200/2007/slides/petriN-initial.pdf Petri Niska's slides]</text>
    </revision>
  </page>
  <page>
    <title>Java.policy</title>
    <id>166</id>
    <revision>
      <id>1125</id>
      <timestamp>2008-03-19T03:10:20Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>New page: &lt;pre&gt;  // Standard extensions get all permissions by default  grant codeBase &quot;file:${{java.ext.dirs}}/*&quot; { 	permission java.security.AllPermission; };  grant codeBase &quot;file:${user.home}/Li...</comment>
      <text xml:space="preserve">&lt;pre&gt;

// Standard extensions get all permissions by default

grant codeBase &quot;file:${{java.ext.dirs}}/*&quot; {
	permission java.security.AllPermission;
};

grant codeBase &quot;file:${user.home}/Library/Java/Extensions/*&quot; {
	permission java.security.AllPermission;
};

grant codeBase &quot;file:/Library/Java/Extensions/*&quot; {
	permission java.security.AllPermission;
};

grant codeBase &quot;file:/System/Library/Java/Extensions/*&quot; {
	permission java.security.AllPermission;
};

grant codeBase &quot;file:/Network/Library/Java/Extensions/*&quot; {
	permission java.security.AllPermission;
};

// default permissions granted to all domains

grant { 
	// Allows any thread to stop itself using the java.lang.Thread.stop()
	// method that takes no argument.
	// Note that this permission is granted by default only to remain
	// backwards compatible.
	// It is strongly recommended that you either remove this permission
	// from this policy file or further restrict it to code sources
	// that you specify, because Thread.stop() is potentially unsafe.
	// See &quot;http://java.sun.com/notes&quot; for more information.
	permission java.lang.RuntimePermission &quot;stopThread&quot;;

	// allows anyone to listen on un-privileged ports
	permission java.net.SocketPermission &quot;localhost:1024-&quot;, &quot;listen&quot;;

	// &quot;standard&quot; properies that can be read by anyone

	permission java.util.PropertyPermission &quot;java.version&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;java.vendor&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;java.vendor.url&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;java.class.version&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;os.name&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;os.version&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;os.arch&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;file.separator&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;path.separator&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;line.separator&quot;, &quot;read&quot;;

	permission java.util.PropertyPermission &quot;java.specification.version&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;java.specification.vendor&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;java.specification.name&quot;, &quot;read&quot;;

	permission java.util.PropertyPermission &quot;java.vm.specification.version&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;java.vm.specification.vendor&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;java.vm.specification.name&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;java.vm.version&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;java.vm.vendor&quot;, &quot;read&quot;;
	permission java.util.PropertyPermission &quot;java.vm.name&quot;, &quot;read&quot;;

	// All properties documented in http://developer.apple.com/documentation/Java/Reference/Java14SysProperties/index.html
	// can be set from an applet, or via the Java 1.4.2 Plugin Settings application.
	permission java.util.PropertyPermission &quot;apple.awt.*&quot;, &quot;read, write&quot;;
	permission java.util.PropertyPermission &quot;apple.laf.*&quot;, &quot;read, write&quot;;

	// Apple-specific properties
	permission java.util.PropertyPermission &quot;mrj.version&quot;, &quot;read&quot;;

	// Deprecated properties for compatibility with Java 1.3.1
	permission java.util.PropertyPermission &quot;com.apple.macos.useScreenMenuBar&quot;, &quot;read, write&quot;;
	permission java.util.PropertyPermission &quot;com.apple.hwaccel&quot;, &quot;read, write&quot;;
        
};
&lt;/pre&gt;</text>
    </revision>
  </page>
  <page>
    <title>Java Open Source Resources</title>
    <id>64</id>
    <revision>
      <id>305</id>
      <timestamp>2007-12-09T19:21:50Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <text xml:space="preserve">Feel free to add your own to this list:

* [http://code.google.com/webtoolkit/ Google GWT], a system for building JavaScript/AJAX applications in Java. You write your application in Java and GWT compiles it into JavaScript...</text>
    </revision>
  </page>
  <page>
    <title>Java Websites</title>
    <id>65</id>
    <revision>
      <id>307</id>
      <timestamp>2007-12-10T01:54:35Z</timestamp>
      <contributor>
        <ip>71.198.17.227</ip>
      </contributor>
      <comment>New page: A handy list of websites that have information about Java for people trying to learn the language.   * http://www.java-tips.org/</comment>
      <text xml:space="preserve">A handy list of websites that have information about Java for people trying to learn the language.


* http://www.java-tips.org/</text>
    </revision>
  </page>
  <page>
    <title>Java reserved keywords</title>
    <id>69</id>
    <revision>
      <id>504</id>
      <timestamp>2008-01-15T15:05:07Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <text xml:space="preserve">;abstract
;assert
;boolean
;break
;byte
;case
;catch
;char
;class
;const
;continue
;default
;do
;double
;else
;enum
;extends
;final
: [http://www.codeguru.com/java/tij/tij0071.shtml discussion at codeguru]
;finally
;float
;for
;goto
;if
;implements
;import
;instanceof
;int
;interface
;long
;native
;new
;package
;private
;protected
: [http://www.codeguru.com/java/tij/tij0068.shtml Discussion at CodeGuru]
;public
;return
;short
;static
;strictfp
;super
;switch
;synchronized
;this
;throw
;throws
;transient
;try
;void
;volatile
;while

=See Also=
* http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html</text>
    </revision>
  </page>
  <page>
    <title>Javadoc</title>
    <id>80</id>
    <revision>
      <id>473</id>
      <timestamp>2008-01-15T02:43:52Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <text xml:space="preserve">=Regular Tags=
;@author
;@deprecated
;@exception
;@param
;@return
;@see
;@serial
;@serialData
;@serialField
;@since
;@throws
;@version
=Macro-Expanding tags=
;{@code}
;{@docRoot}
;{@inheritDoc}
;{@link}
;{@linkplain}
;{@literal}
;{@value}


=See Also=
* [http://java.sun.com/j2se/javadoc/ JavaDoc Tool Homepage]
* [http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javadoc.html Sun's JavaDoc 1.5 Documentation]</text>
    </revision>
  </page>
  <page>
    <title>Javaws.policy</title>
    <id>167</id>
    <revision>
      <id>1127</id>
      <timestamp>2008-03-19T03:10:58Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">&lt;pre&gt;
// @(#)javaws.policy	1.7 00/09/18

grant codeBase &quot;file:${jnlpx.home}/lib/javaws.jar&quot; {
    permission java.security.AllPermission;
};

grant codeBase &quot;file:${jnlpx.home}/lib/deploy.jar&quot; {
    permission java.security.AllPermission;
};

&lt;/pre&gt;

[http://java.sun.com/developer/community/askxprt/sessions/2006/jl0410.jsp Confused?]</text>
    </revision>
  </page>
  <page>
    <title>JoinGameButtonActionPerformed</title>
    <id>134</id>
    <revision>
      <id>948</id>
      <timestamp>2008-02-29T17:54:37Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>New page: &lt;pre&gt; private void joinGameButtonActionPerformed(java.awt.event.ActionEvent evt) {         // TODO add your handling code here:           URL serverURL;         try {             serverURL...</comment>
      <text xml:space="preserve">&lt;pre&gt;
private void joinGameButtonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
 
        URL serverURL;
        try {
            serverURL = new java.net.URL(&quot;http://othello.nitroba.org/game.cgi&quot;);
        } catch (java.net.MalformedURLException e){
            throw new RuntimeException(&quot;bad URL&quot;);
        }

        XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();

        config.setServerURL(serverURL);
        client = new Client();
        client.setConfig(config);
        try {
            gameID = client.joinGame(myNameField.getText());
        } catch (XmlRpcException e){
            statusLabel.setText(&quot;Could not join game&quot;);
            return;
        }
        
        // Create the timer.

}
&lt;/pre&gt;</text>
    </revision>
  </page>
  <page>
    <title>Main Page</title>
    <id>1</id>
    <revision>
      <id>1107</id>
      <timestamp>2008-03-18T15:02:12Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">&lt;big&gt;'''Welcome to CS3773: Java as a Second Language.'''&lt;/big&gt;

This is the main page for CS3773, Spring 2008, taught by Simson Garfinkel at the Naval Postgraduate School.

We are currently on [[Week 11: The Big Finish]]

From here you can explore the following links:
* [[Syllabus]]
* [[Week-by-week Outline]]
* [[Assignments]]
* [[Things to do]] (if you want to hack the wiki)

=News=
==March 11==
* Final projects are now in the [[:Category:Final Projects|Final Projects Catagory]]

==March 10==
* Interesting in figuring out [[wall intersections in Flatland]]?  
* Please feel free to enter which [[Section of the Bloch Book]] you wish to discuss.

==March 9==
* [[Media:Quiz9-answers.pdf|Answers to Quiz 9]] have been uploaded.
* Quiz 9 stats: Minimum score: 40 ; Average: 58 ; Max Score: 80

==March 7==
* You should get assignment 8 in before the end of the quarter; shoot for Monday March 10th.

==March 3==
* Details regarding the [[Final Project]] have been posted
* Week7 can now be submitted; it will display as an applet on the validate page. (Code is experimental)
* Link to the short [http://www.warriorsofthe.net/ &quot;Warriors of the Web&quot;].
* An [[Office Hours Sign-Up]] page has been created.

==March 1st==
Quiz 8 grades have been posted. Class mean was 88; stddev was 25.81
==February 29==
Please enter your requests for topics over the next two weeks in the [[Coming Attractions]] section.

==February 25==
* [[Media:XMLRPC.pdf| Prof. Herzog provided these slides from his lecture on Friday.]]‎
* [https://domex.nps.edu/cs3773/spring99/ Slides from Spring 99 have been uploaded to this server]

==February 22==
* [[Final Project Ideas]] have been posted.
==February 21==
* Friday's class will be taught by Professor Jonathan Herzog. He will be discussing Othello, Timers, and XMLRPC.
* Next week we will be building a basic chat system using the XMLRPC system. Ambitious students may also build an Othello game.
* Please submit your 1-paragraph proposal for the final project by Friday. The ideas will be summarized and placed on a web page (without your name) for other students to see. 
* Homework #7, due February 24th, is now optional. You may submit your Homework #6 working in a web page. 
* Homework #8, due March 3, will be the Desktop Search application.
* Homework #9, due March 10th, will be the Chat/Othello program. This is your last homework.
* Final Projects will be due on March 27th.

==February 12==
* Apparently [http://www.defenselink.mil/webmasters/policy/dod_web_policy_12071998_with_amendments_and_corrections.html DoD policy] allows session-tracking cookies, just not persistent cookies.

==February 10==
* You are reminded to submit your homework through the [https://domex.nps.edu/cs3773/submit/submit.cgi class submission website].
* Be sure that there are no Subversion Conflicts in the code that you submit.
* Your homework should make it clear what you did that is special. One way to do this is by including a README file.

==February 6==
* A Layout Demo has been added to the week5 subversion repository.
* I found an interesting article about [http://www.developer.com/java/other/article.php/3300881 Java Anonymous Classes] at Developer.com.

==February 4==
* Homework #3 and #4 grades have gone out.
* If you are not submitting homework, you are missing out on free credit. Try to solve every problem.
* [[Media:Week5.pdf]] Week 5 slides are posted. 
==January 31==
* Homework #4 can now be [https://domex.nps.edu/cs3773/submit/submit.cgi submitted using the new submission system]
* Making the jarfile in the &quot;hw4&quot; package:

Because homework #4 is in the 'hw4' package, you must do the following:

# Put the line &quot;package hw4;&quot; at the beginning of each of your files.
# Put your files in a directory called &quot;hw4&quot;
# add the files to the jarfile with this command:

   jar cfv yourname.jar hw4/*.java hw4/*.class

==January 26==
* [[Equations of Motion]] have been posted to help you with the electrostatics.
* If you are willing to have your homework used as a class example on debugging on Monday, please drop me an email. Let me know if I can use your name or if you want to show your homework anonymously. [[User:Slgarfin|Slgarfin]] 09:46, 27 January 2008 (PST)
* If you are having Null reference exceptions, you may find [[Week_04:_I/O#Null_reference_exceptions|this discussion of null reference exceptions]] useful.
* If you haven't done it lately, be sure to update your netbeans 6.0 and get the new fixes.

==January 23==
* [http://domex.nps.edu/cs3773/svn/week3/ week3 source code] has been posted. You can check it out using this command line:
&lt;pre&gt;
   svn checkout http://domex.nps.edu/cs3773/svn/ cs3773
&lt;/pre&gt;

==January 18==
* There was a bug in the homework submission validation function, but it's fixed now.
==Old News==
* The [https://domex.nps.edu/cs3773/submit/submit.cgi Homework Submission Link] now works.
* Need a laptop for this class? Please send your requests to Professor Mantak Shing.
* [[Media:Week2.pdf|Week 2 slides (first draft)]] Are uploaded.
* [[Media:Week2b.pdf|Week 2 thursday slides]] are also uploaded.
* Please take a look at the [[Talk:Blog]]
* A [[Bug in Week 02 code]] has been discovered. Click on the wiki page for the fix.

=Main Page=
=Contributed Resources=
* [[Useful Websites]]

''Please feel free to contribute to this wiki, either by editing pages (as appropriate) or contributing to the web-based discussion. You can log into this wiki using your NPS username and password. ''</text>
    </revision>
  </page>
  <page>
    <title>Maroon final project proposal</title>
    <id>170</id>
    <revision>
      <id>1178</id>
      <timestamp>2008-03-27T17:39:53Z</timestamp>
      <contributor>
        <username>Kjmaroon</username>
        <id>6</id>
      </contributor>
      <text xml:space="preserve">[[Category:Final Projects]]

My project is to convert our flatland  program into 3D using Open GL bindings for JAVA or JOGL.

note I have been able to get flatland to work in JOGL, I'll leave in the code for it in the project, but it will not be part of the game.

Once I can get that working I'd like to implement a Pacman type game.
Ideally I'd like 4 ghosts covering each quadrent as well as a Swing panel that keeps track of levels and score.

The game will have five levels.

1. Level 1 - flat world

2. Level 2 - rotation around x

3. Level 3 - rotation around y

4. Level 4 - rotation around both

5. Level 5 - faster rotation

There are unlimited lives, but getting touched by a ghost will cost a player points.

Finally I'd like to be able to put walls in the flatland to give the game a real pacman type feel.

(note, I've been able to add the walls except that I can not get the bounce to work.  
I will leave them in though because as the world rotates they obscure what the player can see and add to the difficulty)

I've used code from my Graphics class as well as a gears example from the web.</text>
    </revision>
  </page>
  <page>
    <title>Mime.types</title>
    <id>114</id>
    <revision>
      <id>847</id>
      <timestamp>2008-02-12T15:51:09Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>New page: &lt;pre&gt; # This is a comment. I love comments.  # This file controls what Internet media types are sent to the client for # given file extension(s).  Sending the correct media type to the cli...</comment>
      <text xml:space="preserve">&lt;pre&gt;
# This is a comment. I love comments.

# This file controls what Internet media types are sent to the client for
# given file extension(s).  Sending the correct media type to the client
# is important so they know how to handle the content of the file.
# Extra types can either be added here or by using an AddType directive
# in your config files. For more information about Internet media types,
# please read RFC 2045, 2046, 2047, 2048, and 2077.  The Internet media type
# registry is at &lt;http://www.iana.org/assignments/media-types/&gt;.

# MIME type                     Extensions
application/activemessage
application/andrew-inset        ez
application/applefile
application/atom+xml            atom
application/atomicmail
application/batch-smtp
application/beep+xml
application/cals-1840
application/cnrp+xml
application/commonground
application/cpl+xml
application/cybercash
application/dca-rft
application/dec-dx
application/dvcs
application/edi-consent
application/edifact
application/edi-x12
application/eshop
application/font-tdpfr
application/http
application/hyperstudio
application/iges
application/index
application/index.cmd
application/index.obj
application/index.response
application/index.vnd
application/iotp
application/ipp
application/isup
application/mac-binhex40        hqx
application/mac-compactpro      cpt
application/macwriteii
application/marc
application/mathematica
application/mathml+xml          mathml
application/msword              doc
application/news-message-id
application/news-transmission
application/ocsp-request
application/ocsp-response
application/octet-stream        bin dms lha lzh exe class so dll dmg
application/oda                 oda
application/ogg                 ogg
application/parityfec
application/pdf                 pdf
application/pgp-encrypted
application/pgp-keys
application/pgp-signature
application/pkcs10
application/pkcs7-mime
application/pkcs7-signature
application/pkix-cert
application/pkix-crl
application/pkixcmp
application/postscript          ai eps ps
application/prs.alvestrand.titrax-sheet
application/prs.cww
application/prs.nprend
application/prs.plucker
application/qsig
application/rdf+xml             rdf
application/reginfo+xml
application/remote-printing
application/riscos
application/rtf
application/sdp
application/set-payment
application/set-payment-initiation
application/set-registration
application/set-registration-initiation
application/sgml
application/sgml-open-catalog
application/sieve
application/slate
application/smil                smi smil
application/srgs                gram
application/srgs+xml            grxml
application/timestamp-query
application/timestamp-reply
application/tve-trigger
application/vemmi
application/vnd.3gpp.pic-bw-large
application/vnd.3gpp.pic-bw-small
application/vnd.3gpp.pic-bw-var
application/vnd.3gpp.sms
application/vnd.3m.post-it-notes
application/vnd.accpac.simply.aso
application/vnd.accpac.simply.imp
application/vnd.acucobol
application/vnd.acucorp
application/vnd.adobe.xfdf
application/vnd.aether.imp
application/vnd.amiga.ami
application/vnd.anser-web-certificate-issue-initiation
application/vnd.anser-web-funds-transfer-initiation
application/vnd.audiograph
application/vnd.blueice.multipass
application/vnd.bmi
application/vnd.businessobjects
application/vnd.canon-cpdl
application/vnd.canon-lips
application/vnd.cinderella
application/vnd.claymore
application/vnd.commerce-battelle
application/vnd.commonspace
application/vnd.contact.cmsg
application/vnd.cosmocaller
application/vnd.criticaltools.wbs+xml
application/vnd.ctc-posml
application/vnd.cups-postscript
application/vnd.cups-raster
application/vnd.cups-raw
application/vnd.curl
application/vnd.cybank
application/vnd.data-vision.rdz
application/vnd.dna
application/vnd.dpgraph
application/vnd.dreamfactory
application/vnd.dxr
application/vnd.ecdis-update
application/vnd.ecowin.chart
application/vnd.ecowin.filerequest
application/vnd.ecowin.fileupdate
application/vnd.ecowin.series
application/vnd.ecowin.seriesrequest
application/vnd.ecowin.seriesupdate
application/vnd.enliven
application/vnd.epson.esf
application/vnd.epson.msf
application/vnd.epson.quickanime
application/vnd.epson.salt
application/vnd.epson.ssf
application/vnd.ericsson.quickcall
application/vnd.eudora.data
application/vnd.fdf
application/vnd.ffsns
application/vnd.fints
application/vnd.flographit
application/vnd.framemaker
application/vnd.fsc.weblaunch
application/vnd.fujitsu.oasys
application/vnd.fujitsu.oasys2
application/vnd.fujitsu.oasys3
application/vnd.fujitsu.oasysgp
application/vnd.fujitsu.oasysprs
application/vnd.fujixerox.ddd
application/vnd.fujixerox.docuworks
application/vnd.fujixerox.docuworks.binder
application/vnd.fut-misnet
application/vnd.grafeq
application/vnd.groove-account
application/vnd.groove-help
application/vnd.groove-identity-message
application/vnd.groove-injector
application/vnd.groove-tool-message
application/vnd.groove-tool-template
application/vnd.groove-vcard
application/vnd.hbci
application/vnd.hhe.lesson-player
application/vnd.hp-hpgl
application/vnd.hp-hpid
application/vnd.hp-hps
application/vnd.hp-pcl
application/vnd.hp-pclxl
application/vnd.httphone
application/vnd.hzn-3d-crossword
application/vnd.ibm.afplinedata
application/vnd.ibm.electronic-media
application/vnd.ibm.minipay
application/vnd.ibm.modcap
application/vnd.ibm.rights-management
application/vnd.ibm.secure-container
application/vnd.informix-visionary
application/vnd.intercon.formnet
application/vnd.intertrust.digibox
application/vnd.intertrust.nncp
application/vnd.intu.qbo
application/vnd.intu.qfx
application/vnd.irepository.package+xml
application/vnd.is-xpr
application/vnd.japannet-directory-service
application/vnd.japannet-jpnstore-wakeup
application/vnd.japannet-payment-wakeup
application/vnd.japannet-registration
application/vnd.japannet-registration-wakeup
application/vnd.japannet-setstore-wakeup
application/vnd.japannet-verification
application/vnd.japannet-verification-wakeup
application/vnd.jisp
application/vnd.kde.karbon
application/vnd.kde.kchart
application/vnd.kde.kformula
application/vnd.kde.kivio
application/vnd.kde.kontour
application/vnd.kde.kpresenter
application/vnd.kde.kspread
application/vnd.kde.kword
application/vnd.kenameaapp
application/vnd.koan
application/vnd.liberty-request+xml
application/vnd.llamagraphics.life-balance.desktop
application/vnd.llamagraphics.life-balance.exchange+xml
application/vnd.lotus-1-2-3
application/vnd.lotus-approach
application/vnd.lotus-freelance
application/vnd.lotus-notes
application/vnd.lotus-organizer
application/vnd.lotus-screencam
application/vnd.lotus-wordpro
application/vnd.mcd
application/vnd.mediastation.cdkey
application/vnd.meridian-slingshot
application/vnd.micrografx.flo
application/vnd.micrografx.igx
application/vnd.mif             mif
application/vnd.minisoft-hp3000-save
application/vnd.mitsubishi.misty-guard.trustweb
application/vnd.mobius.daf
application/vnd.mobius.dis
application/vnd.mobius.mbk
application/vnd.mobius.mqy
application/vnd.mobius.msl
application/vnd.mobius.plc
application/vnd.mobius.txf
application/vnd.mophun.application
application/vnd.mophun.certificate
application/vnd.motorola.flexsuite
application/vnd.motorola.flexsuite.adsi
application/vnd.motorola.flexsuite.fis
application/vnd.motorola.flexsuite.gotap
application/vnd.motorola.flexsuite.kmr
application/vnd.motorola.flexsuite.ttc
application/vnd.motorola.flexsuite.wem
application/vnd.mozilla.xul+xml xul
application/vnd.ms-artgalry
application/vnd.ms-asf
application/vnd.ms-excel        xls
application/vnd.ms-lrm
application/vnd.ms-powerpoint   ppt
application/vnd.ms-project
application/vnd.ms-tnef
application/vnd.ms-works
application/vnd.ms-wpl
application/vnd.mseq
application/vnd.msign
application/vnd.music-niff
application/vnd.musician
application/vnd.netfpx
application/vnd.noblenet-directory
application/vnd.noblenet-sealer
application/vnd.noblenet-web
application/vnd.novadigm.edm
application/vnd.novadigm.edx
application/vnd.novadigm.ext
application/vnd.obn
application/vnd.osa.netdeploy
application/vnd.palm
application/vnd.pg.format
application/vnd.pg.osasli
application/vnd.powerbuilder6
application/vnd.powerbuilder6-s
application/vnd.powerbuilder7
application/vnd.powerbuilder7-s
application/vnd.powerbuilder75
application/vnd.powerbuilder75-s
application/vnd.previewsystems.box
application/vnd.publishare-delta-tree
application/vnd.pvi.ptid1
application/vnd.pwg-multiplexed
application/vnd.pwg-xhtml-print+xml
application/vnd.quark.quarkxpress
application/vnd.rapid
application/vnd.rn-realmedia    rm
application/vnd.s3sms
application/vnd.sealed.net
application/vnd.seemail
application/vnd.shana.informed.formdata
application/vnd.shana.informed.formtemplate
application/vnd.shana.informed.interchange
application/vnd.shana.informed.package
application/vnd.smaf
application/vnd.sss-cod
application/vnd.sss-dtf
application/vnd.sss-ntf
application/vnd.street-stream
application/vnd.svd
application/vnd.swiftview-ics
application/vnd.triscape.mxs
application/vnd.trueapp
application/vnd.truedoc
application/vnd.ufdl
application/vnd.uplanet.alert
application/vnd.uplanet.alert-wbxml
application/vnd.uplanet.bearer-choice
application/vnd.uplanet.bearer-choice-wbxml
application/vnd.uplanet.cacheop
application/vnd.uplanet.cacheop-wbxml
application/vnd.uplanet.channel
application/vnd.uplanet.channel-wbxml
application/vnd.uplanet.list
application/vnd.uplanet.list-wbxml
application/vnd.uplanet.listcmd
application/vnd.uplanet.listcmd-wbxml
application/vnd.uplanet.signal
application/vnd.vcx
application/vnd.vectorworks
application/vnd.vidsoft.vidconference
application/vnd.visio
application/vnd.visionary
application/vnd.vividence.scriptfile
application/vnd.vsf
application/vnd.wap.sic
application/vnd.wap.slc
application/vnd.wap.wbxml       wbxml
application/vnd.wap.wmlc        wmlc
application/vnd.wap.wmlscriptc  wmlsc
application/vnd.webturbo
application/vnd.wrq-hp3000-labelled
application/vnd.wt.stf
application/vnd.wv.csp+wbxml
application/vnd.xara
application/vnd.xfdl
application/vnd.yamaha.hv-dic
application/vnd.yamaha.hv-script
application/vnd.yamaha.hv-voice
application/vnd.yellowriver-custom-menu
application/voicexml+xml        vxml
application/watcherinfo+xml
application/whoispp-query
application/whoispp-response
application/wita
application/wordperfect5.1
application/x-bcpio             bcpio
application/x-cdlink            vcd
application/x-chess-pgn         pgn
application/x-compress
application/x-cpio              cpio
application/x-csh               csh
application/x-director          dcr dir dxr
application/x-dvi               dvi
application/x-futuresplash      spl
application/x-gtar              gtar
application/x-gzip
application/x-hdf               hdf
application/x-javascript        js
application/x-java-jnlp-file    jnlp
application/x-koan              skp skd skt skm
application/x-latex             latex
application/x-netcdf            nc cdf
application/x-sh                sh
application/x-shar              shar
application/x-shockwave-flash   swf
application/x-stuffit           sit
application/x-sv4cpio           sv4cpio
application/x-sv4crc            sv4crc
application/x-tar               tar
application/x-tcl               tcl
application/x-tex               tex
application/x-texinfo           texinfo texi
application/x-troff             t tr roff
application/x-troff-man         man
application/x-troff-me          me
application/x-troff-ms          ms
application/x-ustar             ustar
application/x-wais-source       src
application/x400-bp
application/xhtml+xml           xhtml xht
application/xslt+xml            xslt
application/xml                 xml xsl
application/xml-dtd             dtd
application/xml-external-parsed-entity
application/zip                 zip
audio/32kadpcm
audio/amr
audio/amr-wb
audio/basic                     au snd
audio/cn
audio/dat12
audio/dsr-es201108
audio/dvi4
audio/evrc
audio/evrc0
audio/g722
audio/g.722.1
audio/g723
audio/g726-16
audio/g726-24
audio/g726-32
audio/g726-40
audio/g728
audio/g729
audio/g729D
audio/g729E
audio/gsm
audio/gsm-efr
audio/l8
audio/l16
audio/l20
audio/l24
audio/lpc
audio/midi                      mid midi kar
audio/mpa
audio/mpa-robust
audio/mp4a-latm                 m4a m4p
audio/mpeg                      mpga mp2 mp3
audio/parityfec
audio/pcma
audio/pcmu
audio/prs.sid
audio/qcelp
audio/red
audio/smv
audio/smv0
audio/telephone-event
audio/tone
audio/vdvi
audio/vnd.3gpp.iufp
audio/vnd.cisco.nse
audio/vnd.cns.anp1
audio/vnd.cns.inf1
audio/vnd.digital-winds
audio/vnd.everad.plj
audio/vnd.lucent.voice
audio/vnd.nortel.vbk
audio/vnd.nuera.ecelp4800
audio/vnd.nuera.ecelp7470
audio/vnd.nuera.ecelp9600
audio/vnd.octel.sbc
audio/vnd.qcelp
audio/vnd.rhetorex.32kadpcm
audio/vnd.vmx.cvsd
audio/x-aiff                    aif aiff aifc
audio/x-alaw-basic
audio/x-mpegurl                 m3u
audio/x-pn-realaudio            ram ra
audio/x-pn-realaudio-plugin
audio/x-wav                     wav
chemical/x-pdb                  pdb
chemical/x-xyz                  xyz
image/bmp                       bmp
image/cgm                       cgm
image/g3fax
image/gif                       gif
image/ief                       ief
image/jpeg                      jpeg jpg jpe
image/jp2                       jp2
image/naplps
image/pict                      pict pic pct
image/png                       png
image/prs.btif
image/prs.pti
image/svg+xml                   svg
image/t38
image/tiff                      tiff tif
image/tiff-fx
image/vnd.cns.inf2
image/vnd.djvu                  djvu djv
image/vnd.dwg
image/vnd.dxf
image/vnd.fastbidsheet
image/vnd.fpx
image/vnd.fst
image/vnd.fujixerox.edmics-mmr
image/vnd.fujixerox.edmics-rlc
image/vnd.globalgraphics.pgb
image/vnd.mix
image/vnd.ms-modi
image/vnd.net-fpx
image/vnd.svf
image/vnd.wap.wbmp              wbmp
image/vnd.xiff
image/x-cmu-raster              ras
image/x-macpaint                pntg pnt mac
image/x-icon                    ico
image/x-portable-anymap         pnm
image/x-portable-bitmap         pbm
image/x-portable-graymap        pgm
image/x-portable-pixmap         ppm
image/x-quicktime               qtif qti
image/x-rgb                     rgb
image/x-xbitmap                 xbm
image/x-xpixmap                 xpm
image/x-xwindowdump             xwd
message/delivery-status
message/disposition-notification
message/external-body
message/http
message/news
message/partial
message/rfc822
message/s-http
message/sip
message/sipfrag
model/iges                      igs iges
model/mesh                      msh mesh silo
model/vnd.dwf
model/vnd.flatland.3dml
model/vnd.gdl
model/vnd.gs-gdl
model/vnd.gtw
model/vnd.mts
model/vnd.parasolid.transmit.binary
model/vnd.parasolid.transmit.text
model/vnd.vtu
model/vrml                      wrl vrml
multipart/alternative
multipart/appledouble
multipart/byteranges
multipart/digest
multipart/encrypted
multipart/form-data
multipart/header-set
multipart/mixed
multipart/parallel
multipart/related
multipart/report
multipart/signed
multipart/voice-message
text/calendar                   ics ifb
text/css                        css
text/directory
text/enriched
text/html                       html htm
text/parityfec
text/plain                      asc txt
text/prs.lines.tag
text/rfc822-headers
text/richtext                   rtx
text/rtf                        rtf
text/sgml                       sgml sgm
text/t140
text/tab-separated-values       tsv
text/uri-list
text/vnd.abc
text/vnd.curl
text/vnd.dmclientscript
text/vnd.fly
text/vnd.fmi.flexstor
text/vnd.in3d.3dml
text/vnd.in3d.spot
text/vnd.iptc.nitf
text/vnd.iptc.newsml
text/vnd.latex-z
text/vnd.motorola.reflex
text/vnd.ms-mediapackage
text/vnd.net2phone.commcenter.command
text/vnd.sun.j2me.app-descriptor
text/vnd.wap.si
text/vnd.wap.sl
text/vnd.wap.wml                wml
text/vnd.wap.wmlscript          wmls
text/x-setext                   etx
text/xml
text/xml-external-parsed-entity
video/bmpeg
video/bt656
video/celb
video/dv
video/h261
video/h263
video/h263-1998
video/h263-2000
video/jpeg
video/mp1s
video/mp2p
video/mp2t
video/mp4                       mp4
video/mp4v-es
video/mpv
video/mpeg                      mpeg mpg mpe
video/nv
video/parityfec
video/pointer
video/quicktime                 qt mov
video/smpte292m
video/vnd.fvt
video/vnd.motorola.video
video/vnd.motorola.videop
video/vnd.mpegurl               mxu m4u
video/vnd.nokia.interleaved-multimedia
video/vnd.objectvideo
video/vnd.vivo
video/x-dv                      dv dif
video/x-msvideo                 avi
video/x-sgi-movie               movie
x-conference/x-cooltalk         ice
&lt;/pre&gt;</text>
    </revision>
  </page>
  <page>
    <title>Mini Project 1</title>
    <id>8</id>
    <revision>
      <id>37</id>
      <timestamp>2007-11-28T05:09:29Z</timestamp>
      <contributor>
        <username>Simsong</username>
        <id>1</id>
      </contributor>
      <comment>New page: Ideas:  * Tic-tac-toe</comment>
      <text xml:space="preserve">Ideas:

* Tic-tac-toe</text>
    </revision>
  </page>
  <page>
    <title>Modified multi-threaded server</title>
    <id>140</id>
    <revision>
      <id>982</id>
      <timestamp>2008-03-05T08:48:35Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">&lt;pre&gt;
package week8;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 *
 * @author simsong
 */
public class TCPMultiThreadedServer {

    private ServerSocket sock; // My socket
    static int port = 1234;
    Integer clientCount = 0;

    /* The worker thread for each incoming connection */
    class Worker extends Thread {

        Socket remote;

        Worker(Socket remote) {
            this.remote = remote;
        }

        public void run() {
            try {
                BufferedOutputStream bos = new BufferedOutputStream(remote.getOutputStream());
                PrintWriter os = new PrintWriter(bos, false);

                synchronized (clientCount) {
                    os.println(&quot;Welcome client #&quot; + clientCount);
                }
                os.println(&quot;You are coming from host &quot; + remote.getRemoteSocketAddress().toString());
                System.out.printf(&quot;Client #%d came from host %s %n&quot;,
                        clientCount, remote.getRemoteSocketAddress().toString());
                os.flush();

                BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
                String line = in.readLine();
                if (line == null) {
                    System.out.println(&quot;Lost client...&quot;);
                } else {
                    os.println(&quot;Pleased to meet you, &quot; + line);
                    System.out.println(&quot;User is &quot; + line);
                }
                os.close();
                remote.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void listen_for_connections() {
        try {
            sock = new ServerSocket(port);
            System.out.println(&quot;TCPServer Starting on port &quot; + port);
            System.out.println(&quot;sock=&quot; + sock);
        } catch (IOException e) {
            /* Notice the fancy exception chaining. */
            throw new RuntimeException(&quot;Couldn't create server: &quot; + e.getMessage());
        }
        while (true) {
            try {
                Socket client = sock.accept(); /* Get my socket from the server socket */
                synchronized (clientCount) {
                    ++clientCount;
                }
                System.out.println(&quot;Starting new Worker thread...&quot;);
                (new Worker(client)).start();
                System.out.println(&quot;Worker thread is working...&quot;);

            } catch (IOException e) {
                System.out.println(&quot;Error in client: &quot; + e.getMessage());
            }
        }
    }

    public static void main(String[] args) {
        TCPMultiThreadedServer server = new TCPMultiThreadedServer();
        server.listen_for_connections();
    }
}
&lt;/pre&gt;</text>
    </revision>
  </page>
  <page>
    <title>Modified single-threaded server</title>
    <id>139</id>
    <revision>
      <id>983</id>
      <timestamp>2008-03-05T08:48:57Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">&lt;pre&gt;
package week8;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 *
 * @author simsong
 */
public class TCPMultiThreadedServer {

    private ServerSocket sock; // My socket
    static int port = 1234;
    Integer clientCount = 0;

    /* The worker thread for each incoming connection */
    class Worker extends Thread {

        Socket remote;

        Worker(Socket remote) {
            this.remote = remote;
        }

        public void run() {
            try {
                BufferedOutputStream bos = new BufferedOutputStream(remote.getOutputStream());
                PrintWriter os = new PrintWriter(bos, false);

                synchronized (clientCount) {
                    os.println(&quot;Welcome client #&quot; + clientCount);
                }
                os.println(&quot;You are coming from host &quot; + remote.getRemoteSocketAddress().toString());
                System.out.printf(&quot;Client #%d came from host %s %n&quot;,
                        clientCount, remote.getRemoteSocketAddress().toString());
                os.flush();

                BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
                String line = in.readLine();
                if (line == null) {
                    System.out.println(&quot;Lost client...&quot;);
                } else {
                    os.println(&quot;Pleased to meet you, &quot; + line);
                    System.out.println(&quot;User is &quot; + line);
                }
                os.close();
                remote.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void listen_for_connections() {
        try {
            sock = new ServerSocket(port);
            System.out.println(&quot;TCPServer Starting on port &quot; + port);
            System.out.println(&quot;sock=&quot; + sock);
        } catch (IOException e) {
            /* Notice the fancy exception chaining. */
            throw new RuntimeException(&quot;Couldn't create server: &quot; + e.getMessage());
        }
        while (true) {
            try {
                Socket client = sock.accept(); /* Get my socket from the server socket */
                synchronized (clientCount) {
                    ++clientCount;
                }
                System.out.println(&quot;Starting new Worker thread...&quot;);
                (new Worker(client)).start();
                System.out.println(&quot;Worker thread is working...&quot;);

            } catch (IOException e) {
                System.out.println(&quot;Error in client: &quot; + e.getMessage());
            }
        }
    }

    public static void main(String[] args) {
        TCPMultiThreadedServer server = new TCPMultiThreadedServer();
        server.listen_for_connections();
    }
}
&lt;/pre&gt;</text>
    </revision>
  </page>
  <page>
    <title>My favorite Tools</title>
    <id>168</id>
    <revision>
      <id>1167</id>
      <timestamp>2008-03-20T15:40:44Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>/* Windows */</comment>
      <text xml:space="preserve">=Operating Systems=
* [http://www.freebsd.org FreeBSD]
* Macintosh
* Fedora Core 8
* http://www.ubuntu.com/
* http://www.debian.org/
* Windows

=ISPs=
==General Web Hosting==
* http://www.dreamhost.com/
* http://www.pair.com/
* http://www.site5.com/
==Domain Registrars==
All of the ISPs listed above can register domains for you. If you want to get into the world of domain speculation, you may wish to consider:
* http://www.moniker.com/
* http://www.dotster.com/
==Dynamic DNS==
* https://www.dyndns.com/
==Website Analysis==
* [http://www.google.com/analytics/indexu.html Google Analytics]
* [http://www.google.com/webmasters/ Google Webmaster]
==Misc==
* http://www.surveymonkey.com
* http://www.j2.com/
* http://www.vonage.com/

=Automation=
* Make
* Subversion
* automake &amp; autoconf
* emacs

==Time==
* NTP - to set the time.
* http://tycho.usno.navy.mil/
* [http://en.wikipedia.org/wiki/ICalendar iCalendar] - Represents calendar and time entries
* http://phpicalendar.net/ - Displays a calendar

==Text Processing==
* [http://www.accesspdf.com/pdftk/ pdftk] - PDF manipulation
* Zipfiles:
** unzip - command-line manipulation of zip files
** jar - Java manipulation
** python 2.5 zipfile module.

=Image Processing=
* [http://www.imagemagick.org/ ImageMagick] - lots of image manipulations, scriptable.
* EXIF - understand the JPEG Exif format.

==Data Synchronization==
* svn
* [http://www.samba.org/rsync/ rsync] - 1 way synchronizer
* [http://www.cis.upenn.edu/~bcpierce/unison/ unison] - 2 way synchronizer

==Collaboration Tools==
* [http://www.mediawiki.org/wiki/MediaWiki MediaWiki]

Legacy tool list: http://www.simson.net/tools.php

=Windows=
* VMWare
* [http://www.cygwin.com/ Cygwin]
* [http://www.microsoft.com/downloads/details.aspx?FamilyID=8be579aa-780d-4253-9e0a-e17e51db2223&amp;DisplayLang=en Microsoft Keyboard Layout Creator]
* [http://webpages.charter.net/krumsick/ KeyTweak - Remap windows keyboard]</text>
    </revision>
  </page>
  <page>
    <title>Nelson final project</title>
    <id>153</id>
    <revision>
      <id>1051</id>
      <timestamp>2008-03-12T15:21:47Z</timestamp>
      <contributor>
        <username>Janelson</username>
        <id>17</id>
      </contributor>
      <text xml:space="preserve">Jason Nelson Final Project Proposal

Creating a version of Space Invaders-like game using Flatland as a base.

One Shooter Bot (User control)

Shoots Bullet Bots at Target Bots

If Bullet Bot intersectes with Target Bot, both Bots removed and points added to total

If Target Bots get to bottom of screen, game lost

If all Target Bots are eliminated, restart at next level

Each level up, time for Targets to get to bottom decreases



If time allows:

Create destroyable objects between Target Bots and Shooter Bot to be used as  
  
shields and obstructions

Allow Target Bots to shoot back at Shooter Bot.



TBD:
Test Methods: 
Material Requirements for Use: 
Performance Requirements:  
Quality Considerations: 
Completion Delivery: 
Provision for Inspection/Rejection/Corrective Measures: 



[[Category:Final Projects]]</text>
    </revision>
  </page>
  <page>
    <title>Office Hours Sign-Up</title>
    <id>138</id>
    <revision>
      <id>985</id>
      <timestamp>2008-03-07T05:13:28Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>can't sign up for an hour</comment>
      <text xml:space="preserve">=Monday, March 3=
1100 - 1130
* Taken

1130 - 1200
* Taken

=Tuesday, March 4=
930 - 1000

1000-1030

=Wednesday, March 5=
1400 - 1430

1430 - 1500

=Friday, March 7=
1100 - 1130  Ayers Cs3773 

1130 - 1200</text>
    </revision>
  </page>
  <page>
    <title>Open Source</title>
    <id>161</id>
    <revision>
      <id>1100</id>
      <timestamp>2008-03-18T05:54:05Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>New page: What does Open Source mean?  * Source code is available. * Free --- Free Speech vs. Free Beer</comment>
      <text xml:space="preserve">What does Open Source mean?

* Source code is available.
* Free --- Free Speech vs. Free Beer</text>
    </revision>
  </page>
  <page>
    <title>Org.apache.lucene.demo.IndexFiles source</title>
    <id>124</id>
    <revision>
      <id>890</id>
      <timestamp>2008-02-21T06:02:52Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>New page: &lt;pre&gt; package org.apache.lucene.demo;  /**  * Licensed to the Apache Software Foundation (ASF) under one or more  * contributor license agreements.  See the NOTICE file distributed with  *...</comment>
      <text xml:space="preserve">&lt;pre&gt;
package org.apache.lucene.demo;

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the &quot;License&quot;); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;

/** Index all text files under a directory. */
public class IndexFiles {
  
  private IndexFiles() {}

  static final File INDEX_DIR = new File(&quot;index&quot;);
  
  /** Index all text files under a directory. */
  public static void main(String[] args) {
    String usage = &quot;java org.apache.lucene.demo.IndexFiles &lt;root_directory&gt;&quot;;
    if (args.length == 0) {
      System.err.println(&quot;Usage: &quot; + usage);
      System.exit(1);
    }

    if (INDEX_DIR.exists()) {
      System.out.println(&quot;Cannot save index to '&quot; +INDEX_DIR+ &quot;' directory, please delete it first&quot;);
      System.exit(1);
    }
    
    final File docDir = new File(args[0]);
    if (!docDir.exists() || !docDir.canRead()) {
      System.out.println(&quot;Document directory '&quot; +docDir.getAbsolutePath()+ &quot;' does not exist or is not readable, please check the path&quot;);
      System.exit(1);
    }
    
    Date start = new Date();
    try {
      IndexWriter writer = new IndexWriter(INDEX_DIR, new StandardAnalyzer(), true);
      System.out.println(&quot;Indexing to directory '&quot; +INDEX_DIR+ &quot;'...&quot;);
      indexDocs(writer, docDir);
      System.out.println(&quot;Optimizing...&quot;);
      writer.optimize();
      writer.close();

      Date end = new Date();
      System.out.println(end.getTime() - start.getTime() + &quot; total milliseconds&quot;);

    } catch (IOException e) {
      System.out.println(&quot; caught a &quot; + e.getClass() +
       &quot;\n with message: &quot; + e.getMessage());
    }
  }

  static void indexDocs(IndexWriter writer, File file)
    throws IOException {
    // do not try to index files that cannot be read
    if (file.canRead()) {
      if (file.isDirectory()) {
        String[] files = file.list();
        // an IO error could occur
        if (files != null) {
          for (int i = 0; i &lt; files.length; i++) {
            indexDocs(writer, new File(file, files[i]));
          }
        }
      } else {
        System.out.println(&quot;adding &quot; + file);
        try {
          writer.addDocument(FileDocument.Document(file));
        }
        // at least on windows, some temporary files raise this exception with an &quot;access denied&quot; message
        // checking if the file can be read doesn't help
        catch (FileNotFoundException fnfe) {
          ;
        }
      }
    }
  }
  
}
&lt;/pre&gt;</text>
    </revision>
  </page>
  <page>
    <title>Org.apache.lucene.demo.SearchFiles source</title>
    <id>123</id>
    <revision>
      <id>888</id>
      <timestamp>2008-02-21T06:02:06Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>New page: &lt;pre&gt; package org.apache.lucene.demo;  /**  * Licensed to the Apache Software Foundation (ASF) under one or more  * contributor license agreements.  See the NOTICE file distributed with  *...</comment>
      <text xml:space="preserve">&lt;pre&gt;
package org.apache.lucene.demo;

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the &quot;License&quot;); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.FilterIndexReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Searcher;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

/** Simple command-line based search demo. */
public class SearchFiles {

  /** Use the norms from one field for all fields.  Norms are read into memory,
   * using a byte of memory per document per searched field.  This can cause
   * search of large collections with a large number of fields to run out of
   * memory.  If all of the fields contain only a single token, then the norms
   * are all identical, then single norm vector may be shared. */
  private static class OneNormsReader extends FilterIndexReader {
    private String field;

    public OneNormsReader(IndexReader in, String field) {
      super(in);
      this.field = field;
    }

    public byte[] norms(String field) throws IOException {
      return in.norms(this.field);
    }
  }

  private SearchFiles() {}

  /** Simple command-line based search demo. */
  public static void main(String[] args) throws Exception {
    String usage =
      &quot;Usage: java org.apache.lucene.demo.SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-raw] [-norms field]&quot;;
    if (args.length &gt; 0 &amp;&amp; (&quot;-h&quot;.equals(args[0]) || &quot;-help&quot;.equals(args[0]))) {
      System.out.println(usage);
      System.exit(0);
    }

    String index = &quot;index&quot;;
    String field = &quot;contents&quot;;
    String queries = null;
    int repeat = 0;
    boolean raw = false;
    String normsField = null;
    
    for (int i = 0; i &lt; args.length; i++) {
      if (&quot;-index&quot;.equals(args[i])) {
        index = args[i+1];
        i++;
      } else if (&quot;-field&quot;.equals(args[i])) {
        field = args[i+1];
        i++;
      } else if (&quot;-queries&quot;.equals(args[i])) {
        queries = args[i+1];
        i++;
      } else if (&quot;-repeat&quot;.equals(args[i])) {
        repeat = Integer.parseInt(args[i+1]);
        i++;
      } else if (&quot;-raw&quot;.equals(args[i])) {
        raw = true;
      } else if (&quot;-norms&quot;.equals(args[i])) {
        normsField = args[i+1];
        i++;
      }
    }
    
    IndexReader reader = IndexReader.open(index);

    if (normsField != null)
      reader = new OneNormsReader(reader, normsField);

    Searcher searcher = new IndexSearcher(reader);
    Analyzer analyzer = new StandardAnalyzer();

    BufferedReader in = null;
    if (queries != null) {
      in = new BufferedReader(new FileReader(queries));
    } else {
      in = new BufferedReader(new InputStreamReader(System.in, &quot;UTF-8&quot;));
    }
      QueryParser parser = new QueryParser(field, analyzer);
    while (true) {
      if (queries == null)                        // prompt the user
        System.out.println(&quot;Enter query: &quot;);

      String line = in.readLine();

      if (line == null || line.length() == -1)
        break;

      line = line.trim();
      if (line.length() == 0)
        break;
      
      Query query = parser.parse(line);
      System.out.println(&quot;Searching for: &quot; + query.toString(field));

      Hits hits = searcher.search(query);
      
      if (repeat &gt; 0) {                           // repeat &amp; time as benchmark
        Date start = new Date();
        for (int i = 0; i &lt; repeat; i++) {
          hits = searcher.search(query);
        }
        Date end = new Date();
        System.out.println(&quot;Time: &quot;+(end.getTime()-start.getTime())+&quot;ms&quot;);
      }

      System.out.println(hits.length() + &quot; total matching documents&quot;);

      final int HITS_PER_PAGE = 10;
      for (int start = 0; start &lt; hits.length(); start += HITS_PER_PAGE) {
        int end = Math.min(hits.length(), start + HITS_PER_PAGE);
        for (int i = start; i &lt; end; i++) {

          if (raw) {                              // output raw format
            System.out.println(&quot;doc=&quot;+hits.id(i)+&quot; score=&quot;+hits.score(i));
            continue;
          }

          Document doc = hits.doc(i);
          String path = doc.get(&quot;path&quot;);
          if (path != null) {
            System.out.println((i+1) + &quot;. &quot; + path);
            String title = doc.get(&quot;title&quot;);
            if (title != null) {
              System.out.println(&quot;   Title: &quot; + doc.get(&quot;title&quot;));
            }
          } else {
            System.out.println((i+1) + &quot;. &quot; + &quot;No path for this document&quot;);
          }
        }

        if (queries != null)                      // non-interactive
          break;
        
        if (hits.length() &gt; end) {
          System.out.println(&quot;more (y/n) ? &quot;);
          line = in.readLine();
          if (line.length() == 0 || line.charAt(0) == 'n')
            break;
        }
      }
    }
    reader.close();
  }
}
&lt;/pre&gt;</text>
    </revision>
  </page>
  <page>
    <title>Othello Server</title>
    <id>100</id>
    <revision>
      <id>774</id>
      <timestamp>2008-02-01T18:05:05Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>/* Server Functionality */</comment>
      <text xml:space="preserve">Design for the Othello Server:

=Requirements=
Server Requirements:
* Allow pairs of users to play Othello with each other
* Multiple players playing at once.
* Maintain all state associated with the game.
* Validate all moves.


Game requirements:
* One player goes first.
* The game ends when neither player can move.
* Players may move multiple times in a row (if your opponent can't move, you go again.)
* Players should be able to send each other messages.

State that needs to be on the server:
* All users
* All games currently being played
* The state of every game board
* Player whose turn it is.

State that needs to be kept on the clients:
* Name of this user
* Current game being played.

=Server Functionality=
* Create user ''username''.
* Create a game of ''user1'' playing ''user2''

=Client Theory-of-Operation=
* Ask user for their username.
*

=Proposed API=

==GetGames(username)==
Returns:
* array - all the games that username is currently playing.
==GetBoard(username,game)==
Returns:
* board - current position of the board
* yourMove - boolean if it is ''username's'' move.
* message - message to display
* gameInProgress - true if game is in progress; false if game is over.
==SendMessage(username,game)==
Sends a message to the opponent.
==MakeMove(username,move)==
Makes the move. Returns:
* moveOK - true: move was okay; false: move was illegal</text>
    </revision>
  </page>
  <page>
    <title>Output 1</title>
    <id>142</id>
    <revision>
      <id>994</id>
      <timestamp>2008-03-10T04:43:12Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>New page: &lt;pre&gt; Get a String class and show the methods that it implements Class: java.lang.String Methods:    hashCode    compareTo    compareTo    equals    length    charAt    toString    indexOf...</comment>
      <text xml:space="preserve">&lt;pre&gt;
Get a String class and show the methods that it implements
Class: java.lang.String
Methods:
   hashCode
   compareTo
   compareTo
   equals
   length
   charAt
   toString
   indexOf
   indexOf
   indexOf
   indexOf
   codePointAt
   codePointBefore
   codePointCount
   offsetByCodePoints
   getChars
   getBytes
   getBytes
   getBytes
   contentEquals
   contentEquals
   equalsIgnoreCase
   compareToIgnoreCase
   regionMatches
   regionMatches
   startsWith
   startsWith
   endsWith
   lastIndexOf
   lastIndexOf
   lastIndexOf
   lastIndexOf
   substring
   substring
   subSequence
   concat
   replace
   replace
   matches
   contains
   replaceFirst
   replaceAll
   split
   split
   toLowerCase
   toLowerCase
   toUpperCase
   toUpperCase
   trim
   toCharArray
   format
   format
   valueOf
   valueOf
   valueOf
   valueOf
   valueOf
   valueOf
   valueOf
   valueOf
   valueOf
   copyValueOf
   copyValueOf
   intern
   getClass
   wait
   wait
   wait
   notify
   notifyAll
&lt;/pre&gt;</text>
    </revision>
  </page>
  <page>
    <title>Output 2</title>
    <id>143</id>
    <revision>
      <id>997</id>
      <timestamp>2008-03-10T04:46:31Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>New page: &lt;pre&gt; Get a String class and show the methods that it implements Class: java.lang.String Methods:   (int) hashCode    (int) compareTo    (int) compareTo    (boolean) equals    (int) length...</comment>
      <text xml:space="preserve">&lt;pre&gt;
Get a String class and show the methods that it implements
Class: java.lang.String
Methods:
  (int) hashCode 
  (int) compareTo 
  (int) compareTo 
  (boolean) equals 
  (int) length 
  (char) charAt 
  (java.lang.String) toString 
  (int) indexOf 
  (int) indexOf 
  (int) indexOf 
  (int) indexOf 
  (int) codePointAt 
  (int) codePointBefore 
  (int) codePointCount 
  (int) offsetByCodePoints 
  (void) getChars 
  (void) getBytes 
  ([B) getBytes 
  ([B) getBytes 
  (boolean) contentEquals 
  (boolean) contentEquals 
  (boolean) equalsIgnoreCase 
  (int) compareToIgnoreCase 
  (boolean) regionMatches 
  (boolean) regionMatches 
  (boolean) startsWith 
  (boolean) startsWith 
  (boolean) endsWith 
  (int) lastIndexOf 
  (int) lastIndexOf 
  (int) lastIndexOf 
  (int) lastIndexOf 
  (java.lang.String) substring 
  (java.lang.String) substring 
  (java.lang.CharSequence) subSequence 
  (java.lang.String) concat 
  (java.lang.String) replace 
  (java.lang.String) replace 
  (boolean) matches 
  (boolean) contains 
  (java.lang.String) replaceFirst 
  (java.lang.String) replaceAll 
  ([Ljava.lang.String;) split 
  ([Ljava.lang.String;) split 
  (java.lang.String) toLowerCase 
  (java.lang.String) toLowerCase 
  (java.lang.String) toUpperCase 
  (java.lang.String) toUpperCase 
  (java.lang.String) trim 
  ([C) toCharArray 
  (java.lang.String) format 
  (java.lang.String) format 
  (java.lang.String) valueOf 
  (java.lang.String) valueOf 
  (java.lang.String) valueOf 
  (java.lang.String) valueOf 
  (java.lang.String) valueOf 
  (java.lang.String) valueOf 
  (java.lang.String) valueOf 
  (java.lang.String) valueOf 
  (java.lang.String) valueOf 
  (java.lang.String) copyValueOf 
  (java.lang.String) copyValueOf 
  (java.lang.String) intern 
  (java.lang.Class) getClass 
  (void) wait 
  (void) wait 
  (void) wait 
  (void) notify 
  (void) notifyAll 
&lt;/pre&gt;</text>
    </revision>
  </page>
  <page>
    <title>Papers</title>
    <id>45</id>
    <revision>
      <id>354</id>
      <timestamp>2008-01-01T20:57:14Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <text xml:space="preserve">Here are the papers that we'll be reading in this class, roughly in the order that they'll be introduced.

[[Media:P159-irimia.pdf|Enhancing the introductory computer science curriculum: C++ or Java?]] Andrei Irimia, CCSC 2001.

[[Media:P48-biddle.pdf|Java Pitfalls for Beginners]] , Robert Biddle and Ewan Tempero, SIGCSE, June 1998

[[Media:P151-frens.pdf|Taming the Tiger: Teaching the Next Version of Java&amp;trade;]]  , Jeremy D. Frens, SIGCSE'04

[[Media:P33-zaidman.pdf|Teaching Defensive Programming in Java]], Marsha Zaidman, 2003.

[[Media:P11-barowski.pdf|From C to Java: A Case Study in Portability, Efficiency, and Maintenance]] , Larry A. Barowski, James H. Cross II, and T. Dean Hendrix, 2000

[[Media:P57-reiss.pdf|Visualizing Java in Action]], Steven P. Reiss, Software Visualization, 2003

[[Media:P109-prechelt.pdf|Comparing Java vs. C/C++ Efficiency Differences to Interpersonal Differences]], Lutz Prechelt, October 1999

[[Media:A3-yamauchi.pdf|Writing Solaris Device Drivers in Java]] 






=Other Papers=
These papers aren't assigned, but you may find them fun to read just the same. 

[[Media:P38-tyma.pdf|Why are we using Java again?]]   Paul Tyma, June 1998.

[[Media:A4-stroustrup.pdf|Evolving a language in and for the real world: C++ 1991-2006]] , Bjarne Stroustrup

[[Media:P57-grissom.pdf| A Pedagogical Framework for Introducing Java I/O in CS1]], Scott Grissom, December 2000

[[Media:P70-alphonce.pdf|Object Orientation in CS1-CS2 by Design]], Carl Alphonce and Phil Ventura, ITiCSE'02.

[[Media:P287-wicentowski.pdf| Using Image Processing Projects to Teach CS1 Topics]], Richard Wicentowski and Tia Newhall

[[Media:P357-bishop.pdf| Object-orientation in Java for scientific programmers]], Judith Bishop  and Nigel Bishop

[[Media:P236-sangappa.pdf|Benchmarking Java Against C/C++ for Interactive Scientific Visualization]], Sudhir Sangappa , K. Palaniappan , and Richard Tollerton</text>
    </revision>
  </page>
  <page>
    <title>Rashid: Final Project Proposal</title>
    <id>156</id>
    <revision>
      <id>1063</id>
      <timestamp>2008-03-13T17:22:54Z</timestamp>
      <contributor>
        <username>Tmrashid</username>
        <id>8</id>
      </contributor>
      <text xml:space="preserve">'''Final Project Specification V2'''

'''SAR Search Pattern Application'''

For maritime helictoper search and rescue pattern geometry and selection, aircrews use NWP 3-22-6 SAR-TAC.

This program will assume that the search unit is a helicopter.

'''ULTIMATE OUTPUT'''
It will calculate the optimal pattern track spacing, and output optimal altitude and airspeed based upon the following input parameters which will be user selectable via a GUI.  It will recommend a search pattern type from the following list.
Expanding Square
Parallel Area
Sector Search
Trackline Single Unit Returning

'''USER INPUT'''
Search target. ( Person in the water or raft)
Last known position of the search target. (LKP)
Wind speed and direction (kts and compass direction)
Time of Day on station ( 24 hr clock)

'''PROGRAM OUTPUT'''
From the above the program will estimate the current position (DATUM)
and give a confidence area for the current postion.  This will be shown in a small window.

'''USER INPUT'''
Illumination Level (Lunar)
Visibility (in nautical miles)
Sea State (Beafort Scale)
Desired probability of Detection or Desired Coverage Factor
Search Unit available time on Station.
Search unit available sensors. (Eye, FLIR, NVD)
Search unit crew fatigue level. (Yes or No)


The only physical model will be the drift calculation of the search target from LKP to DATUM</text>
    </revision>
  </page>
  <page>
    <title>Readings</title>
    <id>66</id>
    <revision>
      <id>857</id>
      <timestamp>2008-02-13T04:39:43Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">Each week we have readings from the book or online Java tutorials. On Wednesday we also read something different.

&lt;DPL&gt;
  category=JavaWeek
  ordermethod=title
  include=#Readings
  nottitlematch=%JavaWeek%
  format = ,\n= [[%PAGE%|%TITLE%]]=,,
&lt;/DPL&gt;</text>
    </revision>
  </page>
  <page>
    <title>Resources</title>
    <id>5</id>
    <revision>
      <id>29</id>
      <timestamp>2007-11-25T07:28:43Z</timestamp>
      <contributor>
        <username>Simsong</username>
        <id>1</id>
      </contributor>
      <text xml:space="preserve">=Development Environments=
;http://www.bluej.org/
:An IDE designed for learning Java

;http://www.eclipse.org/
:The most popular Java IDE, originally developed by IBM.

;http://www.netbeans.org/
:Sun's Java IDE. Not as powerful as Eclipse but easier to use. Includes support for profiling and a nice Swing UI designer. This is the one that we use in CS3773, because most of MOVES uses NetBeans.

=Simulation Systems=

;http://www.greenfoot.org/
:The Java Object World - A simulation environment written in Java for teaching programming to high school and college students. Created by the BlueJ team.</text>
    </revision>
  </page>
  <page>
    <title>SQL &amp; JDBC</title>
    <id>160</id>
    <revision>
      <id>1109</id>
      <timestamp>2008-03-18T15:31:06Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>[[SQL &amp; JODBC]] moved to [[SQL &amp; JDBC]]</comment>
      <text xml:space="preserve">SQL is the Structured Query Language.

* It's an Interface and language for communicating with database servers; it is not the way that the data is stored.
* Can be used with a client/server database or embedded.

=SQL Servers=
''[[Open Source]]'':
* [http://www.mysql.com MySQL]
* [http://www.postgresql.org/ PostgreSQL]
* [http://www.firebirdsql.org Firebird]
* [http://www.ingres.com/ Ingres]
* [http://www.sqlite.org/ SQLite]


''Closed Source''
* Microsoft SQL Server
* Oracle

''100% Pure Java DBMS'' [http://java.sun.com/products/jdbc/driverdesc.html Type 4 JDBC drivers]
* [http://hsqldb.sourceforge.net/ HSQLDB]
* [http://www.smallsql.de/ SmallSQL Database] (Also see http://sourceforge.net/projects/smallsql/)

=SQL Statements=
* CREATE 
* SELECT
* WHERE
* INSERT
* UPDATE
* DELETE

=Mini Demo=
&lt;pre&gt;
Suspended
xy:~&gt; sqlite
SQLite version 2.8.16
Enter &quot;.help&quot; for instructions
sqlite&gt; create table bar (x int,name varchar(255));
sqlite&gt; insert into bar (x,name) values (3,&quot;foo&quot;);
sqlite&gt; insert into bar (x,name) values (2,&quot;nosmis&quot;);
sqlite&gt; insert into bar (x,name) values (1,&quot;you bet your life&quot;);
sqlite&gt; select * from bar;
3|foo
2|nosmis
1|you bet your life
sqlite&gt; select * from bar where x==2;
2|nosmis
sqlite&gt; select * from bar where x=2;
2|nosmis
sqlite&gt; select * from bar where name like 'f%';
3|foo
sqlite&gt; select * from bar where name like '%f%';
3|foo
1|you bet your life
sqlite&gt; 
&lt;/pre&gt;

=JDBC=
* A Standard Java driver for SQL
  import java.sql.*;
Classes:
* Connection - Makes the connection
* Statement - Creates the SQL connection.
* ResultSet - What a query resopnds with
Sample code: [[ArffSQL]]



* SQLite:
** [http://www.zentus.com/sqlitejdbc/ SQLiteJDBC]
** [http://www.ch-werner.de/javasqlite/ SQLite Java Wrapper/JDBC Driver]

=SQL Injection Attacks=

=References=
* [http://java.sun.com/products/jdbc/overview.html Sun's JDBC Overview]
* [http://www.w3schools.com/sql/default.asp W3School's SQL Tutorial]
* [http://www.osalt.com/ Open Source as Alternative]</text>
    </revision>
  </page>
  <page>
    <title>SQL &amp; JODBC</title>
    <id>163</id>
    <revision>
      <id>1110</id>
      <timestamp>2008-03-18T15:31:06Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <comment>[[SQL &amp; JODBC]] moved to [[SQL &amp; JDBC]]</comment>
      <text xml:space="preserve">#REDIRECT [[SQL &amp; JDBC]]</text>
    </revision>
  </page>
  <page>
    <title>Section of the Bloch Book</title>
    <id>145</id>
    <revision>
      <id>1041</id>
      <timestamp>2008-03-12T06:43:39Z</timestamp>
      <contributor>
        <username>Crfitzpa</username>
        <id>16</id>
      </contributor>
      <text xml:space="preserve">Let's discuss these:

* Item 54 - Use Serializations judiciously.
* Item 56 - Write readObject methods defensively.

Not sure if it has to be recent material,  if not these seem interesting
* Item 40- Used Checked Exceptions for Recoverable conditions and run-time exceptions for programming errors.
* Item 16- Prefer interfaces to abstract classes.  [[User:Tmrashid|Tmrashid]] 22:58, 11 March 2008 (PDT)
* Item 30 - Know and use the libraries.
* Item 51 - Don't depend on the thread scheduler.</text>
    </revision>
  </page>
  <page>
    <title>Simson Garfinkel Final Project Proposal</title>
    <id>137</id>
    <revision>
      <id>967</id>
      <timestamp>2008-03-03T16:09:43Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>New page: I will write a java program.</comment>
      <text xml:space="preserve">I will write a java program.</text>
    </revision>
  </page>
  <page>
    <title>Subversion</title>
    <id>68</id>
    <revision>
      <id>785</id>
      <timestamp>2008-02-04T15:47:52Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>/* Windows */</comment>
      <text xml:space="preserve">[http://subversion.tigris.org/ Subversion] is a source code control system.  Subversion maintains a '''repository''' on a central server with a master copy of a project. Each time the project is modified the repository is updated with the modifications. Unlike a Windows file share, the subversion repository keeps a copy of every previous version of every file in the repository. 

You can '''check out''' a copy of a subversion repository. This downloads a copy of the repository to your computer, where you are free to edit it. After you check it out, you can '''update''' repository. If the repository has been modified in the meantime, all of the modifications to the repository are applied to your local copy, but your local edits are kept intact. 

We will be using subversion to distribute source code in this class. 

The subversion repository for this class is located at '''http://domex.nps.edu/cs3773/svn/'''. This repository is configured to allow anonymous read access. Only class staff has the ability to commit changes back to the repository, however.

=Getting Started with Subversion=
To get started with subversion you need to download a copy of the subversion client to your computer.
==Windows==
* Download and install [http://subversion.tigris.org/files/documents/15/41077/svn-win32-1.4.6.zip] from http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=91 . This will give you the Subversion command-line utilities for Windows.  (Note: you will be told that this binaries are not compatible with Apache 2.2. Don't worry about this; it only affects you if you are running a Subversion server, not a subversion client.)

* You may find it easier to use Subversion if you install the [http://tortoisesvn.net/downloads TortoiseSVN Shell Extension].

It is similar to RCS and CVS, if you have used either of those.

*

==Macintosh==
* You can download a DMG of the subversion client from http://metissian.com/projects/macosx/subversion/

==RedHat Linux==
* just run &lt;tt&gt;yum install subversion&lt;/tt&gt;
==Debian Linux==
* just run &lt;tt&gt;apt-get install subversion&lt;/tt&gt;
==Anything else==
Please see http://subversion.tigris.org/project_packages.html.

=Check out the course directory=
Use the '''svn checkout''' command to check out the CS3773 course directory into a directory on your local machine:

&lt;pre&gt;
$ svn checkout https://domex.nps.edu/cs3773/svn/ cs3773
A    cs3773/lib
A    cs3773/week1
Checked out revision 1.
$ 
&lt;/pre&gt;

You can '''cd''' into the directory and use the info command to verify the checkout:
&lt;pre&gt;
$ cd cs3773
$ svn info
Path: .
URL: https://domex.nps.edu/cs3773/svn
Repository Root: https://domex.nps.edu/cs3773/svn
Repository UUID: 142099ca-78df-40c8-a049-6b37f5426d51
Revision: 1
Node Kind: directory
Schedule: normal
Last Changed Author: simsong
Last Changed Rev: 1
Last Changed Date: 2008-01-01 15:37:07 -0800 (Tue, 01 Jan 2008)

$
&lt;/pre&gt;
=SVN Update Frequently=
Use the '''svn update''' command to sync your copy with the server:

&lt;pre&gt;
$ svn update
At revision 1.
&lt;/pre&gt;

=See Also=
* http://subversion.tigris.org/ - Subversion home page</text>
    </revision>
  </page>
  <page>
    <title>Syllabus</title>
    <id>6</id>
    <revision>
      <id>869</id>
      <timestamp>2008-02-15T16:10:29Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">Lectures will be held at Every day at 0800 in GE-117.

Although portions of this class may be taught using tele-presence equipment, this class will not be videotaped. The making of video or audio recordings is strictly prohibited.

=Contact Information=

{| border=&quot;1&quot; cellpadding=&quot;5&quot; cellspacing=&quot;0&quot;
|-
|Course Location
| GE 117
|-
|Meeting Time:
|MTWR 0800-0850 &lt;br&gt; F 0800-0950
|-
| Professor:
|	[[User:Simsong|Simson L. Garfinkel]], Ph.D.
|-
|Phone:	
|831-656-7602 (office); &lt;br&gt;617-876-6111 (home)
|-
|NPS e-mail:	
|slgarfin
|-
|Office Hours:
|Tuesdays, 0900-1000
|-
|Professor's Website:	
|http://www.simson.net
|}

=Catalog Description=

'''CS3773 Java as a Second Language (4-2)'''&lt;br&gt;
A first course in Java for students experienced in another programming language. Students learn to implement problem solutions using the procedural and object-oriented language features of Java. Topics include: program structures and environment, arrays, exceptions, constructors and finalizers, class extension, visibility and casting, overriding versus overloading, abstract classes and interfaces, files and streams, class loaders, threads, and sockets. Programming projects provide students the opportunity to implement techniques covered in class. Prerequisite: Recent completion of the complete series in another programming language course, or programming experience in another programming language.

=Learning Outcomes=
Upon successful completion of this course, you will be able to:
*Use NetBeans, Sun's integrated development environment (IDE) for Java.
*Decompose a problem using classes and objects.
*Identify, understand and use all of the [[Java reserved keywords]].
*Use Java Container Classes and Iterators, including Array, Vector, Stack, Hashtable, and BitSet.
*Develop classes and methods that match a specified signature.
*Create a JAR file that contains all information necessary to run a Java program.
*Write programs that use files and streams.
*Interact with an SQL database using JDBC.
*Write a program that displays a graphical user interface using Swing.
*Write an applet that displays itself in a web page
*Write an XMLRPC client and server.
*Develop a program that uses Lucene, the open source indexing kit.

=Course Format=

This course is divided into 11 weeks. Each week will follow roughly this schedule:

* Monday 0800 - The week's assignment is released.  Class commences at 0800.
* Monday &amp; Tuesday - New material is presented.
* Wednesday - Class discussion regarding the assigned reading.
* Thursday - Additional new material on the week's theme is presented.
* Friday 0800 - 0950 - Brief Quiz; Q&amp;A; Lab time to work on the assignment.
* Sunday 1800 - Assignments are due at 1800, submitted electronically. Late assignments are not accepted.


You should bring a laptop equipped with NetBeans and JDK 1.6 (Java 6) to each class and lab period.

=Text=
This course has three texts:
* ''[http://www.amazon.com/Sams-Teach-Yourself-Java-Days/dp/0672329433 Sams Teach Yourself Java 6 in 21 Days (5th Edition)]'', which can be ordered from Amazon. The book may also be available in the campus book store. This isn't the best book about Java, but it is serviceable and it covers Java 6. 
* [[The Java Tutorial]]
* [[Papers]] that can be downloadable from this website

We also have some recommended readings:
* ''[http://java.sun.com/docs/books/effective/index.html Effective Java: Programming Language Guide],'' by Joshua Bloch. This book is highly recommended; it will teach you a lot about Java in particular and programming in general.
* ''[http://www.sun.com/books/catalog/gosling_JPL4.xml The Java™ Programming Language, 4th Edition],'' by James Gosling, Ken Arnold and David Holmes. This 928-page book is the definitive guide to Java™ 2 Standard Edition 5.0 (J2SE 5.0). Unfortunately it's very difficult to read and is really written for Java experts, not for Java beginners.

=Assessment=

Grades are calculated as follows:

{|class=&quot;wikitable&quot;
|Weekly assessment (11)
|	 25%
|-
|Programming Assignments (11):
|	 50%
|-
|Final Project:	 
|        25%
|-
|Class Participation:
|	 priceless
|}

All work in this class should conform to the [[CS3773 Java Style Guide]].

==Class Participation==

This is an intensive workshop-style class. As such, class participation is an important part of the experience. You won't get a grade for your participation, but participating will help you to understand the material better.

==Grades==

Grades are based on an absolute scale:

{|
|-
|A
|	90 to 100% of the total possible points
|-
|B
|	80 to 89% of the total possible points
|-
|C
|	70 to 79% of the total possible points
|-
|D
|	60 to 69% of the total possible points
|-
|F
|	0 to 59% of the total possible points
|}

=Collaboration, Plagiarism and Academic Integrity=

It is strongly recommended that you discuss the readings and assignments with your classmates. You may wish to organize reading or study groups for this purpose. However, it is also expected that the homework you submit will be your own work. You may not collaborate on homework; collaboration on the final project is limited to approved groups.

Plagiarism in any form will not be tolerated in this course. This includes both direct plagiarism, in which you reprint code or words written by another person without reference, and to intellectual plagiarism, in which you present another person's ideas or argument as if they are your own.

Academic integrity on the part of U.S. and international officers and civilians participating in NPS programs is an important aspect of professional performance. For this reason, the provisions of NAVPGSCOLINST 5370.1C of the Academic Honor Code will be strictly enforced.

If you have questions about collaboration, plagiarism or academic integrity, please contact the class staff.

=Citation Policy=

It is possible that you may wish to reference articles, algorithms, or websites in the preparation of your assignments. Citations should include the author of the work being cited, its title, where it is located (usually a URL), the date it was written, and in the case of URLs, the date that you downloaded it. A URL without an author, title, publication title, and publication date is not an acceptable citation format. Citations that are bare URLs will be ignored.

=Protocols=

Communication is a central part of every course. This section of the syllabus describes what we expect from your communications with your fellow students and the course staff.

==Notifications==

For announcements and assignments, the Web is our authoritative form of communication. Students are expected to check the home page for both news and assignments at least once a week. If you hear a rumor, check it there. If you miss an announcement, it should be on the home page.

==Homework==

All homework is due at the start of class on the day for which it is assigned. In most cases your homework will be uploaded to the course website. Late homework is not accepted except in extraordinary cases.

=Course Outline=

Here is the week-by-week outline:


&lt;DPL&gt;
  category=JavaWeek
  ordermethod=title
  nottitlematch=%JavaWeek%
&lt;/DPL&gt;

You can get a more detailed outline on the [[Week-by-week Outline]] page.</text>
    </revision>
  </page>
  <page>
    <title>The Java Tutorial</title>
    <id>7</id>
    <revision>
      <id>34</id>
      <timestamp>2007-11-28T04:46:31Z</timestamp>
      <contributor>
        <username>Simsong</username>
        <id>1</id>
      </contributor>
      <text xml:space="preserve">The Java Tutorials are written by Sun Microsystems to help people use Java. They are well written and freely available on the Internet.

We have found the following tutorials to be highly informative:

* [http://java.sun.com/docs/books/tutorial/uiswing/components/index.html Using Swing Components]

Because the tutorials are online, you will probably find it useful to take notes as you do the tutorials.</text>
    </revision>
  </page>
  <page>
    <title>The Life Cycle of a Thread</title>
    <id>128</id>
    <revision>
      <id>908</id>
      <timestamp>2008-02-25T06:04:50Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">[[Image:threadlife.png]]

Thread objects move in and out a different states in response to various methods and events

:Thread states
;Ready: the Thread is capable of running, but waiting to be assigned to a CPU
;Running: The Thread has been dispatched by the operating system and has been allocated to a CPU
;Blocked: the Thread has issued an I/O request, and is waiting for completion of the I/O operation (i.e. waiting for a disk block to be read into memory)
;Suspended: the Thread has been suspended and is waiting for a call to resume
;Sleeping: the Thread has been deactivated for a specific amount of time
;Waiting: the Thread is waiting for a specific event to happen before it will continue (like for another thread to end, as with join ( ))
;Dead:the run method has completed, or the stop method has been invoked for the Thread
 

''Thanks for Barry Peterson for this material.''</text>
    </revision>
  </page>
  <page>
    <title>Things to do</title>
    <id>86</id>
    <revision>
      <id>559</id>
      <timestamp>2008-01-21T20:10:24Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <comment>New page: Review: * http://en.wikipedia.org/wiki/Wikipedia:Text_editor_support * http://qbnz.com/highlighter/index.php - GeSHI - Generic Syntax Highlighter</comment>
      <text xml:space="preserve">Review:
* http://en.wikipedia.org/wiki/Wikipedia:Text_editor_support
* http://qbnz.com/highlighter/index.php - GeSHI - Generic Syntax Highlighter</text>
    </revision>
  </page>
  <page>
    <title>Threading</title>
    <id>11</id>
    <revision>
      <id>71</id>
      <timestamp>2007-11-30T06:24:06Z</timestamp>
      <contributor>
        <username>Simsong</username>
        <id>1</id>
      </contributor>
      <text xml:space="preserve">Before you think about multi threaded programming, look over these articles:

[http://weblogs.java.net/blog/kgh/archive/2004/10/multithreaded_t.html Graham Hamilton's Blog:Multithreaded toolkits: A failed dream?]

[http://home.pacbell.net/ouster/threads.pdf Why Threads are a bad idea (for most purposes)]

[http://weblogs.java.net/blog/chet/archive/2004/08/threadaches.html Threadaches (Chet Haase's Blog)]

[http://java.sun.com/docs/books/tutorial/essential/concurrency/memconsist.html Memory Consistency Errors]</text>
    </revision>
  </page>
  <page>
    <title>Useful JFC Methods</title>
    <id>9</id>
    <revision>
      <id>47</id>
      <timestamp>2007-11-28T05:55:38Z</timestamp>
      <contributor>
        <username>Simsong</username>
        <id>1</id>
      </contributor>
      <text xml:space="preserve">=JComponent=
Some JFC/Swing JComponent methods that I like a lot:

   .setOpaque(true)
   .setBackground(a color)
   .setPreferredSize(a Dimension)
   .add(anotherComponent)
   .setToolTipText(aString)

Some useful components:

* JLabel - Displays text, images, and arbitrary HTML
* JButton
* JRadioButton
* JTabbedPane

See [http://java.sun.com/docs/books/tutorial/uiswing/components/button.html  How to Use Buttons, Check Boxes, and Radio Buttons]

Making a dimension of 200 x 20:
   new Dimension(200,20)


=Sun Documentation=

Here's the hierarchy for a JLabel:

* [http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html java.lang.Object]
* [http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Component.html awt.Component]
* [http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Container.html awt.Container]
* [http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JComponent.html JComponent]
* [http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JLabel.html JLabel]</text>
    </revision>
  </page>
  <page>
    <title>Useful Websites</title>
    <id>73</id>
    <revision>
      <id>864</id>
      <timestamp>2008-02-13T18:58:50Z</timestamp>
      <contributor>
        <username>Bdlindbe</username>
        <id>10</id>
      </contributor>
      <text xml:space="preserve">Here are some useful websites:

Sun Java Tutorials
[http://java.sun.com/docs/books/tutorial/index.html]

; http://www.gotapi.com/
: Useful information about APIs
: In the right hand column under &quot;Java&quot; click the J2SE v1.5 link, and then type use the Search or Browse section on the left.
'''
[http://www.touchgraph.com/TGGoogleBrowser.html TouchGraph Google, Amazon, Facebook browser]'''</text>
    </revision>
  </page>
  <page>
    <title>Wall intersections in Flatland</title>
    <id>144</id>
    <revision>
      <id>1002</id>
      <timestamp>2008-03-11T14:57:20Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">Here are some thoughts on bot/wall intersections in flatland. If you still need help, let me know.

&lt;pre&gt;
We have a line that goes from (x1,y1) to (x2,y2)
We have a bot that is at (x0,y0) and moving at (dx,dy)

We can describe the first line with a parametric formula in t, as t goes from 0 to 1:

   ex = x2-x1
   ey = y2-y1


   x(t) = x1 + ex * t
   y(t) = y1 + ey * t

We can describe the second line as a parametric formual in s, as s goes from 0 to 1:

   x(s) = x0 + dx * s
   y(s) = y0 + dy * s


Now then, we just want to know if there is some t &amp; s where:
    x(t) = x(s)
and y(t) = y(s)

We have two equations and two unknowns! 

   x(t) = x(s)  
   y(t) = y(s)
is:

   x1 + ex * t = x0 + dx * s
   y1 + ey * t = y0 + dy * s


Recall that s describes the position of the bot as it moves. Let's solve
these equations for s. If we get 0&lt;=s&lt;=1, then we know that the intersection
happens during the next click. If we get a division by 0, it never happens. If we get s&lt;0, it already
happened. If we get s&gt;1, it isn't going to happen in the next time click.

   ex * t = x0 + dx * s - x1
   ey * t = y0 + dy * s - y1

divide the top equation by ex and the button equation by ey:

   t = (x0 + dx * s - x1) / ex
   t = (y0 + dy * s - y1) / ey

Those equations must be equal:

   (x0 + dx * s - x1) / ex = (y0 + dy * s - y1) / ey

Solve for s:

   (x0 + dx * s - x1) * ey  = (y0 + dy * s - y1) * ex

Distribute the ey and the ex:

   x0 * ey + dx * s * ey - x1 * ey  = y0 * ex + dy * s * ex - y1 * ex

Collect terms:

   dx * s * ey - dy * s * ex = y0 * ex + - y1 * ex - x0 * ey  + x1 * ey  

Factor out the s:

   s * (dx * ey - dy * ex ) = y0 * ex + - y1 * ex - x0 * ey  + x1 * ey  

Divide by (dx*ey - dy*ex):

   s = y0 * ex + - y1 * ex - x0 * ey  + x1 * ey  / (dx * ey - dy * ex ) 


Here is a little python program that figures it out; you can rewrite this into Java:

#!/usr/bin/python

def intersects(x1,y1,x2,y2,x0,y0,dx,dy):
    print &quot;intersects( p1 = (%g,%g)  p2 = (%g,%g)  p=(%g,%g) speed=(%g,%g)&quot; % (x1,y1,x2,y2,x0,y0,dx,dy)
    ex = y2 - y1
    ey = x2 - x1
    s = y0 * ex + - y1 * ex - x0 * ey  + x1 * ey  / (dx * ey - dy * ex ) 
    print &quot;s=&quot;,s
    return 0 &lt;= s and s &lt;= 1.0
    return False

print intersects(10.,0.,0.,10.,0.,0.,1.,1.),&quot;\n&quot;
print intersects(10.,0.,0.,10.,0.,0.,20.,20.),&quot;\n&quot;


Now that you know if the intersection happens or not (and, in fact, you know where it happens, since you know s),
you can figure out how much after s the destination intersection is.

You know that the intersection happens at:

    x = x0 + s * dx
    y = y0 + s * dy

So you just need to calculate the new angle that the bot is tarveling at (which can be done with similar
triangles) and how far it travels (which is 1-s)



&lt;/pre&gt;</text>
    </revision>
  </page>
  <page>
    <title>Week-by-week Outline</title>
    <id>10</id>
    <revision>
      <id>827</id>
      <timestamp>2008-02-07T16:50:29Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">&lt;font size=&quot;+2&quot;&gt;PRELIMINARY --- SUBJECT TO CHANGE &lt;/font&gt;

You have 11 weeks to learn Java and object-oriented design. 

Each week will have:
* Stuff to learn
* Programming homework, due Sunday night..
* Quiz, in Friday in Lab

=Course Outline=

&lt;DPL&gt;
  category=JavaWeek
  ordermethod=title
  include=#Goals
  nottitlematch=%JavaWeek%
  format = ,\n= [[%PAGE%|%TITLE%]]=,,
&lt;/DPL&gt;</text>
    </revision>
  </page>
  <page>
    <title>Week 01: Java Without Classes</title>
    <id>18</id>
    <revision>
      <id>460</id>
      <timestamp>2008-01-14T16:37:38Z</timestamp>
      <contributor>
        <username>Bmhawkin</username>
        <id>7</id>
      </contributor>
      <text xml:space="preserve">*'''Next: ''' [[Week_02:_Classes|Week 02: Classes]]
{{JavaWeek
|name=Introduction
|week=1
|shortname=Intro
}}

=Goals=
* Course Goals
* Understand Java and how it's different from C++
* Compile Hello World
* Turn in your first assignment.

=Outline=
==Administrivia==
* Course Schedule
* Weekly Schedule:
** Mondays - New Topic is introduced; slides
** Tuesdays - Delve deeper into new topic; code
** Wednesdays - Java Article to discuss; Q&amp;A
** Thursday - Corner cases; more about the topics. 
** Friday - Lab.  Mini quiz; Q&amp;A;  homework must be submitted by 1800 Sunday (6pm) Pacific Time.
* Survey: What do you know? What do you want to get out of the course?
* How to use the wiki
* How to use [[Subversion]] to get the course material.

==Welcome to Java==
* Busy Box - be amazed
* Java pros/cons
* [[History of Java]]

==Hello World!==

Here is a simple Java program:
&lt;pre&gt;
public class hello {
    public static void main(String args[]){
	System.out.println(&quot;Hello World!&quot;);
    }
}
&lt;/pre&gt;

This program ''must'' be put in a file called '''hello.java'''. 

You compile this program with the '''javac''' compiler:
  % javac hello.java

You run this program with the '''java''' command:
  % java hello
  Hello World!


Other things that we'll teach today:
* Using the Java online documentation.
* Installing the Java system on your computer.
* What CLASSPATH does
* applets vs. stand-alone programs.
* GUI vs. command-line programs.

==Writing Java==
* Compiling and running from the command line
* IDEs - emacs, BlueJ, NetBeans, Eclipse,
* We will be using Eclipse

==Running Java==
* Windows &amp; Unix
* CLASSPATH
* PATH, JAVA_HOME, and  Classpath
* C:\Java\j2sdk1.4.2\jre\lib\ext
==Java Documentation==
* How to find the documentation. 
* Javadoc

==Introduction to Java Sytax==
* math (integer; float, etc)
* Data types &amp; operators
* Using strings, ints, arrays
* Control flow - for (c-kind), if/then/else, switch, while, for (python kind)
* import and packages
* operator precedence

==Java vs. C++==
What's mostly the same:
* basic types (except for string)
* syntax
* classes
* System.output.println vs. cout &lt;&lt;

What's different:
* Single inheritance
* string type
* no objects on the stack (no automatic object creation)
* no operator overloading
* JavaDoc
* bytecode vs. object code
* anonymous classes

==Java vs Python==
What's mostly the same:
* Single inheritance
* bytecode, not object code
* basic types (including string)

What's different:
* syntax
* classes
* no objects on the stack
* no operator overloading
* JavaDoc

=Slides=
*  [[Media:Week1_-_Java_without_classes.pdf‎|Slides for Week 1 Monday, Tuesday]]
*  [[Media:Week1b.pdf|Wednesday]] 
*  [[Media:Week1c.pdf|Thursday]] 
=Readings=
* Read the [[CS3773 Java Style Guide]]. 
* Teach Yourself Java  6 in 21 Days.  Please review chapters 1 through 5 by the end of the week.
* Wednesday Paper: [[Media:P159-irimia.pdf|Enhancing the introductory computer science curriculum: C++ or Java?]] Andrei Irimia, CCSC 2001.

=Assignments=
[[Assignment 1]] is due on Sunday, January 13, at 6pm pacific time

= =
*'''Next: ''' [[Week_02:_Classes|Week 02: Classes]]</text>
    </revision>
  </page>
  <page>
    <title>Week 02: Classes</title>
    <id>19</id>
    <revision>
      <id>523</id>
      <timestamp>2008-01-18T00:35:06Z</timestamp>
      <contributor>
        <username>Bmhawkin</username>
        <id>7</id>
      </contributor>
      <minor/>
      <comment>/* Class Notes */</comment>
      <text xml:space="preserve">*'''Previous: ''' [[Week_01:_Java_Without_Classes|Week 01: Java Without Classes]]
*'''Next: ''' [[Week_03:_Object-Oriented_Design|Week 03: Object-Oriented Design]]
{{JavaWeek
|week=2
|name=Classes
|shortname=Classes
}}


=Goals=
==Language Goals==
* What is a class? What is an instance? What is an object? 
* Understanding inheritance: methods &amp; variables
* Encapsulation: public variables vs. accessor methods
* Final: final methods &amp; final variables 
* mutable vs. immutable objects
* Enums

==Environment Goals==
* applets vs. stand-alone programs.
* GUI vs. command-line programs.
* What CLASSPATH does
* Using the debugger

=Outline=
==Monday: Basics of Classes and Object-Oriented Design==

* [[Media:Week2.pdf|Monday Slides]]
==Tuesday: Classes With Code==
* Show the Demo
** Download week2.jar
** Create a Bot.java
** &lt;tt&gt;java -classpath week2.jar;. Flandland&lt;/tt&gt;  (on Windows)
* Show [https://domex.nps.edu/cs3773/week2/doc/ JavaDoc for week2]

New [[Java reserved keywords]] for working with a single class:
;public


New [[Java reserved keywords]] for working with class hierarchies: 
;abstract
;extends
;implements
;instanceof
;interface
;protected

=Some code to discuss=

=Readings=
Last week we asked you to review Chapters 1-5 in ''Teach Yourself Java 6...''

This week we be working through the book.

==For Tuesday==
* '''Day 3,''' ''Teach Yourself Java  6 in 21 Days.'' This chapter discusses '''new''', methods, method calls, nested method calls, casting, and the '''instance of''' operator.
* Review the Q&amp;A on p. 112. You should know the answer to all of these questions.
* Take the quiz on p. 112--113. 
* Review the Q&amp;A on p. 85. Be sure you can answer all of the questions.
* Take the Quiz on p. 86.
* If they look hard, do the exercises on p. 87 (for yourself, not to hand in).  

==For Wednesday==
(But you may wish to do it in advance of Wednesday):
* [[Media:P48-biddle.pdf|Java Pitfalls for Beginners]] , Robert Biddle and Ewan Tempero, SIGCSE, June 1998
* '''Day 5,''' ''Teach Yourself Java  6 in 21 Days.'' This chapter discusses '''new''', methods, method calls, nested method calls, casting, and the '''instance of''' operator.

==For Thursday==
* '''Appendix A: Using the Java Development Kit,''' ''Teach Yourself Java  6 in 21 Days.'' This chapter discusses '''new''', methods, method calls, nested method calls, casting, and the '''instance of''' operator.

=Class Notes=
[[Week 02 Thursday Notes]]

=Navigation=
*'''Previous: ''' [[Week_01:_Java_Without_Classes|Week 01: Java Without Classes]]
*'''Next: ''' [[Week_03:_Object-Oriented_Design|Week 03: Object-Oriented Design]]</text>
    </revision>
  </page>
  <page>
    <title>Week 02 Thursday Notes</title>
    <id>83</id>
    <revision>
      <id>520</id>
      <timestamp>2008-01-17T16:46:55Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <comment>New page: &lt;pre&gt; /*  * NewClass.java  *  * Created on January 16, 2008, 8:04 AM  *  * To change this template, choose Tools | Template Manager  * and open the template in the editor.  */  import java...</comment>
      <text xml:space="preserve">&lt;pre&gt;
/*
 * NewClass.java
 *
 * Created on January 16, 2008, 8:04 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

import java.util.ArrayList;
import java.awt.Color;

abstract class AbstractSpaceShip {
    public void launch(){
        System.out.println(&quot;The spaceship is launching!&quot;);
    }
}

class Shuttle extends AbstractSpaceShip {
    public void launch(){
        super.launch();
        super.launch();
        super.launch();
        System.out.println(&quot;Shuttle going up!&quot;);
    }
}

class CrashedShuttle extends Shuttle {
    public void launch(){
        System.out.println(&quot;are you kidding?&quot;);
    }
}


public class NewClass {
    public static void main(String args[]) {
        AbstractSpaceShip s = new CrashedShuttle();
        s.launch();
        boolean a = s instanceof AbstractSpaceShip;
        System.out.println(&quot;a=&quot;+a);
        
        s = new Shuttle();
        s.launch();
        System.out.println(&quot;Is a Shuttle a CrashedShuttle?&quot;+(s instanceof CrashedShuttle));
    }
}
&lt;/pre&gt;</text>
    </revision>
  </page>
  <page>
    <title>Week 03: Object-Oriented Design</title>
    <id>16</id>
    <revision>
      <id>610</id>
      <timestamp>2008-01-24T08:21:25Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <comment>/* Item 19: Replaces structures with classes */</comment>
      <text xml:space="preserve">{{JavaWeek
|name=Object-Oriented Design
|week=3
|shortname=OOP
}}

*'''Previous: ''' [[Week_02:_Classes|Week 02: Classes]]
*'''Next: ''' [[Week_04:_I/O|Week 04: I/O]]

=Goals= 
* Inheritance
* Interfaces vs. Abstract classes
* Nested Classes
* Enumerated Types
* overriden methods
* overloaded methods
* overriding vs. overloading
* packages
* [[Annotations]]

=Class Notes=
==Finishing up from last week==
===super constructors===
To call the the constructor in the super-class, use this syntax:

  super();

So the ChaseBot implementation that we presented in class on Friday is more properly implemented as this:

&lt;pre&gt;
import java.lang.Math.*;

public class ChaseBot extends Bot {
    public ChaseBot(Location center,Size size) {
        super(center,size);
    }

    public void tick(Flatland fl){

        /* Find the random bot */
        RandomBot target = null;        // the random bot that we are looking for                                     
        for (FlatlandObject o : fl.things ){
            if(o instanceof RandomBot) target=(RandomBot)o;
        }
        if(target==null) return;                // don't move if there is no target                                   

        /* First calculate the values for what this Bot will look like in 1 second... */
        double dx = target.center.x-this.center.x;
        double dy = -(target.center.y-this.center.y);

        /* Set the new Heading with the atan2 function */
        heading = Math.toDegrees(Math.atan2(dx,dy));

        super.tick(fl);                 // and move                                                                   
    }
}
&lt;/pre&gt;

And the RandomBot looks like this:

&lt;pre&gt;
import java.lang.Math.*;

public class RandomBot extends Bot {
    int duration = 0;

    public RandomBot(Location center,Size size) {
        super(center,size);
    }
    public void tick(Flatland fl){

        if(duration&lt;=0){
            duration = (int)(Math.random()*100.0+30.0);
            heading = Math.random()*360;
        }
        duration = duration - 1;
        super.tick(fl);
    }
}

&lt;/pre&gt;

Get all my code: http://domex.nps.edu/cs3773/svn/week2/

===default constructors===
If you don't create one, Java creates one for you:

&lt;pre&gt;
public class Default {
    public print() {
        System.out.println(&quot;Hello!&quot;);
    }
}

...

Default d = new Default();
d.print();

&lt;/pre&gt;

===BotTester vs. BotTester2===
[http://domex.nps.edu/cs3773/svn/week2/BotTester.java BotTester] implemented '''Regression Testing'''

[http://domex.nps.edu/cs3773/svn/week2/BotTester2.java BotTester2] implemented '''Conformance Testing''' or '''Unit Testing'''


&lt;u&gt;Regression Testing:&lt;/u&gt;
* Run the same code with the same inputs and see if the output changes.
* Code 1 was slgarfin.jar
* Code 2 was '''yourname'''.jar


&lt;u&gt;Conformance Testing:&lt;/u&gt;
* Run the code with a '''test harness'' and check the outputs.


&lt;u&gt;Regression Testing Advantages:&lt;/u&gt;
* Easy to implement.
* Great for test new versions of code for release.


&lt;u&gt;Regression Testing Disadvantages:&lt;/u&gt;
* May not find bugs.


&lt;u&gt;Conformance Testing Advantages:&lt;/u&gt;


&lt;u&gt;Conformance Testing Disadvantages:&lt;/u&gt;

===Common Mistakes on the Homework===
* Duplicated code between Bot and RandomBot
* Hard-coded constants.
* Comments that weren't relevant.

This is useless:

&lt;pre&gt;
// publicRandomBot() creates a RandomBot():
public RandomBot(Location center, Size s){
  ...
&lt;/pre&gt;

This is almost useless:

&lt;pre&gt;
// Decrement counter
counter -= 1;
&lt;/pre&gt;

Try this:

&lt;pre&gt;
// When counter reaches 0, it's time to change direction:
counter -= 1;
if(counter&lt;=0){
   ...
&lt;/pre&gt;

===What is &quot;Business Logic?&quot;===
* Model/View/Controller  [See http://en.wikipedia.org/wiki/Model-view-controller]
* Three-Tier Architecture

==Abstract Classes vs. Interfaces==
Flatland uses both an Abstract class  and an Interface.

* Abstract Class: [http://domex.nps.edu/cs3773/svn/week2/FlatlandObject.java FlatlandObject]
* Interface: [http://domex.nps.edu/cs3773/svn/week2/FlatlandDelegate.java FlatlandDelegate]

Advantages of Abstract Classes:

Advantages of Interfaces:

==Java Packages==
* Syntax
* What's in the package
* import

==Java Scoping Rules==
* local scope
* package scope
* protected scape
* public scope

See http://mindprod.com/jgloss/scope.html

; public
: any class can reference it
; protected
: only classes that extend this class can reference it.
; default (package; friendly)
: any method in this package can access it.
; private
: no class can reference it
; local
: only visible in the block. 


&lt;pre&gt;
package one;
public class A {
    protected int b;
    void public scope_demo() {
        int local_scope = 3;
    }
}

package two;
import one.A;
class B extends A {
    void myMethod() {
        p = 1;  // ok
        A a = new A();
        a.p = 1; // not okay; p would have to be public
    }
}
&lt;/pre&gt;
Example from http://mindprod.com/jgloss/protectedscope.html

==-cp vs -classpath==
A question was asked in class about -cp vs. -classpath. Apparently they both work. See http://javahowto.blogspot.com/2006/06/new-options-in-javac-155-classpath-cp.html .

==Nested Classes==
Java 1.5 and above allows you to create classes inside a class. This is useful if you wish to create an internal class which no other class should be able to use.

Here is a somewhat trivial example:

&lt;pre&gt;
public class Test {
    private class InnerClass {
        StringBuilder res = new StringBuilder();
        String appendFoo(int i){
            while(i-- &gt; 0){
                res.append(&quot;foo &quot;);
            }
            return res.toString();
        }
    }

    public void run(){
        System.out.println(&quot;let's run the foo function...&quot;);

        InnerClass ic = new InnerClass();
        System.out.println(&quot;foo(3)=&quot;+ic.appendFoo(3));
        System.out.println(&quot;foo(2)=&quot;+ic.appendFoo(2));
        System.out.println(&quot;foo(1)=&quot;+ic.appendFoo(1));
    }


    public static void main(String[] args){
        Test t = new Test();
        t.run();
    }
}
&lt;/pre&gt;

The InnerClass is '''private,''' so it can only be accessed from within the '''Test''' class.

Here is what the output looks like:
&lt;pre&gt;
10:27 PM imac2:~$ javac Test.java
10:27 PM imac2:~$ java Test
let's run the foo function...
foo(3)=foo foo foo 
foo(2)=foo foo foo foo foo 
foo(1)=foo foo foo foo foo foo 
10:27 PM imac2:~$ 
&lt;/pre&gt;

Don't worry if this seems complicated right now.

==Enumerated Types==
Added in JDK 1.5.

See http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html

&lt;pre&gt;
public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY 
}
&lt;/pre&gt;

Points of note:
* Enumerated types are types, like classes. You could put the '''enum Day''' into a file called '''Day.java''' and compile it with javac.
* Enumerated types are really syntactic sugar. They don't exist at the bytecode level.

Here is how the Day.class file decompiles:
&lt;pre&gt;
10:53 PM imac2:~$ jad Day.class
Parsing Day.class... Generating Day.jad
10:53 PM imac2:~$ more Day.jad
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) 
// Source File Name:   Day.java


public final class Day extends Enum
{

    public static final Day[] values()
    {
        return (Day[])$VALUES.clone();
    }

    public static Day valueOf(String s)
    {
        return (Day)Enum.valueOf(Day, s);
    }

    private Day(String s, int i)
    {
        super(s, i);
    }

    public static final Day SUNDAY;
    public static final Day MONDAY;
    public static final Day TUESDAY;
    public static final Day WEDNESDAY;
    public static final Day THURSDAY;
    public static final Day FRIDAY;
    public static final Day SATURDAY;
    private static final Day $VALUES[];

    static 
    {
        SUNDAY = new Day(&quot;SUNDAY&quot;, 0);
        MONDAY = new Day(&quot;MONDAY&quot;, 1);
        TUESDAY = new Day(&quot;TUESDAY&quot;, 2);
        WEDNESDAY = new Day(&quot;WEDNESDAY&quot;, 3);
        THURSDAY = new Day(&quot;THURSDAY&quot;, 4);
        FRIDAY = new Day(&quot;FRIDAY&quot;, 5);
        SATURDAY = new Day(&quot;SATURDAY&quot;, 6);
        $VALUES = (new Day[] {
            SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
        });
    }
}
&lt;/pre&gt;


Several students asked ''what is a enumerated type good for?''

Enumerated types are useful when you have a variable that you want to restrict to particular values, but it doesn't make sense to have a different class defined for each variable type.

Here are examples:

* Days of the week.
* Months
* Planets
* Card suits (clubs, diamonds, hearts, spades)

=References=

* [http://hsqldb.sourceforge.net/ HSQLDB], a relational database written entirely in Java.
* [http://java.sun.com/docs/books/tutorial/java/package/packages.html Java Tutorial on packages]
* [http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html Java Tutorial on Annotations]
* [[equals]]

=Wisdom from Effective Java=
The book ''Effective Java'' (Bloch, 2001) is the very best book on Java that I've found. Everything I tell you that is at odds with the book is wrong. Really, this book is amazing. 

The books substance is 57 '''items''' which describe good, effective, clear and efficient programming style in Java. I'll list them here as we've covered enough about Java for them to make sense. Where the items are in odds with something I've done or said, I'll let you know. 

==Item 1: Consider providing static factory methods instead of constructors==
The reason for this is that a class can have multiple static factory methods, but only one constructor with a signature. This has already bitten us in the Flatland example; I should have done things differently, it seems. Another advantage of this approach is that the static constructors can cache objects that are created and return multiple references to the same object, especially if the objects are immutable. So I should have followed this advance with the Size() and Location classes. If we have time, I'll show you how. 
==Item 4: Avoid creating duplicate objects==
Don't do this:
  String s = new String(&quot;silly&quot;);
do this:
  String s = &quot;No longer silly&quot;;
==Item 5: Eliminate obsolete objects references==
We haven't come up against this one yet. But when you don't need an object anymore, overwrite its reference with '''null''' to force garbage collection.
==Item 13: Favor immutability==
We do this with our Location and Size classes.
==Item 14: Favor composition over inheritance==
We are doing this too. It's usually better to have an object that contains other ''helper'' objects, rather than to try to bundle everything into parent classes.
==Item 15: Design and document for inheritance or else prohibit it==
==Item 16: Prefer interfaces to abstract classes==
==Item 17: Use interfaces only to define types==
==Item 19: Replaces structures with classes==
Bloch recommends avoiding this:
&lt;pre&gt;
class Point {
  public float x;
  public float y;
}
&lt;/pre&gt;
and instead doing this:
&lt;pre&gt;
class Point {
  private float x;
  private float y;

  public Point(float x, float y) {
    this.x = x;
    this.y = y;
  }

  public float getX() { return x; }
  public float getY() { return y; }

  public void setX(float x) { this.x = x; }
  public void setY(float y) { this.y = y; }
}
&lt;/pre&gt;

Did you notice that Bloch violates his own rules about immutability and static factory members?

==Item 20: Replace unions with class hierarchies==

=Readings=
* Day 6, Packages, Interfaces, and Other Class Features, ''Teach Yourself Java in 21 Days,''
** Be sure you understand the Q&amp;A on p. 178.
** Take the Quiz on p. 179
** Answer the Certification Practice on pp. 179-180
** Do the exercises on p. 181 (not graded)
* Read the [http://java.sun.com/docs/books/tutorial/java/package/index.html Java Tutorials Lesson on Packages]
**  Do the [http://java.sun.com/docs/books/tutorial/java/package/QandE/packages-questions.html Java Tutorial Questions and Exercises on Packages]]
* [[Media:P151-frens.pdf|Taming the Tiger: Teaching the Next Version of Java&amp;trade;]]  , Jeremy D. Frens, SIGCSE'04

= =
*'''Previous: ''' [[Week_02:_Classes|Week 02: Classes]]
*'''Next: ''' [[Week_04:_I/O|Week 04: I/O]]</text>
    </revision>
  </page>
  <page>
    <title>Week 04: I/O</title>
    <id>20</id>
    <revision>
      <id>735</id>
      <timestamp>2008-01-30T06:20:08Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <comment>/* Getting going with MySQL */</comment>
      <text xml:space="preserve">*'''Previous: ''' [[Week_03:_Object-Oriented_Design|Week 03: Object-Oriented Design]]
*'''Next: ''' [[Week_05:_Basic_Graphics_and_GUI_with_AWT_and_Swing|Week 05: Basic Graphics and GUI with AWT and Swing]]


*[[Week 3 Redux]]


{{JavaWeek
|week=4
|name=I/O
|shortname=I/O
|badname=ff
}}

=Goals=
* Exceptions -  try/catch/finally/throws
* I/O Exceptions
* Keyboard input
* Streams, Buffered Streams
* Files
* Persistance
* SQL/MySQL/JDBC

=Notes=
'''This is a draft right now; it should be ready by Monday morning.'''

==Null reference exceptions==
Many students have been encountering errors that look like this:

&lt;pre&gt;
Exception in thread &quot;main&quot; java.lang.NullPointerException
	at ChaseBot.rangeToTarget(ChaseBot.java:21)
	at A.main(A.java:5)
&lt;/pre&gt;

This is a stack trace. You read it from the top down:

; Exception in thread &quot;main&quot; java.lang.NullPointerException
: This means that there was a Null Pointer Exception, which means that there was an attempt to reference a method or field of a pointer, but the pointer pointed to ''null''. 

; 	at ChaseBot.rangeToTarget(ChaseBot.java 21)
: This tells you '''where''' the exception took place:  the ''rangeToTarget'' method in the ''ChaseBot'' class, and specifically at line ''21'' inside the file (which is going to be the ChaseBot.java file)

; 	at A.main(A.java 5)
: This tells you where the call was made to the ''ChaseBot.rangetoTarget()'' method. The call was made in the method ''A.main'', specifically line 7 of the file ''A.java.''

Let's look at the ChaseBot.rangeToTarget method. The numbers on the left are line numbers: 

&lt;pre&gt;
20    public double rangeToTarget(){
21	double dx = target.getCenter().x-this.getCenter().x;
22	double dy = -(target.getCenter().y-this.getCenter().y);
23	return Math.sqrt(dx*dx + dy*dy);
24    }
&lt;/pre&gt;

In line 21, you'll see that there is an attempt to run the ''getCenter()'' method of ''target'' and of ''this''.  The variable ''this'' is always set (it's always the object which has received the method), but the instance variable ''target'' is only set if somebody has called the object's ''setTarget()'' method. 

Now it's time to look at the file A.java.  This is test program that was constructed to demonstrate the exception:

&lt;pre&gt;
public class A {
    public static void main(String[] args){
	ChaseBot b1 = new ChaseBot(new Location(10,10),1.0);
	ChaseBot b2 = new ChaseBot(new Location(20,20),1.0);
        System.out.printf(&quot;b1 range to b2: %g %n&quot;,b1.rangeToTarget());
    }
}
&lt;/pre&gt;

So what's clearly happened is that we've asked b1 to calculate its range to the target, but we never gave it a target. So it's thrown a null reference exception. The fix is easy: just set the target!

&lt;pre&gt;
    public static void main(String[] args){
        ChaseBot b1 = new ChaseBot(new Location(10,10),1.0);
        ChaseBot b2 = new ChaseBot(new Location(20,20),1.0);
        b1.setTarget(b2);
        System.out.printf(&quot;b1 range to b2: %g %n&quot;,b1.rangeToTarget());
    }
&lt;/pre&gt;

And now we'll get the answer:

&lt;pre&gt;
$ java A
b1 range to b2: 14.1421 
$
&lt;/pre&gt;

==Uses of Java Exceptions==
Exceptions don't have to make your program crash: Java gives us tools to allow programs to catch exceptions and do intelligent error recovery. This allows your program to deal with ''exceptional'' cases, rather than simply crashing. 

All programming languages have a strategy for dealing with runtime errors. In C the traditional approach is to look at the ''return codes'' of system calls. For example, if you want to open a file in C, you use code like this:

  File *f = fopen(&quot;filename.txt&quot;,&quot;r&quot;);

The C documentation says that you need to examine the return code of &quot;fopen&quot; to see if the file is properly opened or not:

  File *f = fopen(&quot;filename.txt&quot;,&quot;r&quot;);
  if(f==0) {
    printf(&quot;File filename.txt not found\n&quot;);
  }

Usually this happens in a function, so you need to return:

  File *f = fopen(&quot;filename.txt&quot;,&quot;r&quot;);
  if(f==0) {
    printf(&quot;File filename.txt not found\n&quot;);
    return -1;
  }

Of course, there may be several reasons that you can't open the file. It may not exist, or there may be a permission error, or there may be an IO error (disk failure). In C this information is stored in a global variable called '''errno''' which you need to inspect:

  File *f = fopen(&quot;filename.txt&quot;,&quot;r&quot;);
  if(f==0) {
    if(errno==ENOENT) {
      printf(&quot;File filename.txt not found\n&quot;);
      return -1;
    }
    if(errno==EPERM){
       printf(&quot;You do not have permission to open filename.txt\n&quot;);
       exit(0);
    }
    if(errno==EIO){
      printf(&quot;I/O error on opening the file. Get help! Your hard drive is crashing!\n&quot;);
      get_help();
    }
  }

To read the file we need to use the '''fread()''' function, which can also return errors --- it can return end-of-file, but it can also return I/O errors and other errors as well. Then you need to close the file with '''close()''', and that can generate errors too. Each time you call a system call, you need to check all of the return codes and handle them appropriate. Ick. This is getting way out of control!

Java takes a different approach: any method can ''throw an exception.'' This creates an error condition which must be '''caught'''.  Exception handling roughly follows this procedure:
# Is the exception caught in the method that generated the exception?
## if so, run the code that catches the exception.
## If not, go to the method that called the current method and repeat step #1
# If you reach the top of the callstack, then this is an ''uncaught exception.'' Print the stack trace and terminate the current thread.

In your code, you were getting a stack trace and having your program terminated because you were not catching the Null reference exception. Your error, incidentally, is not that you were not catching the exception --- your error was that you were not setting the instance variable. '''In general you should not catch the null reference exception when you are developing code.''' You should, instead, write your code so that you don't get null reference exceptions.


==Typical Java exceptions==

Here are some typical Java exceptions and examples of what an intelligent program might want to do with them:

{|class=wikitable
|'''Exception'''
|'''Typical uses'''
|-
|ArithmeticException
| Division by 0.
|-
| IllegalFormatConversionException
| Illeagal format in a printf statement
|-
| IOException
| Something bad happened when your program was trying to read or write a file.  Perhaps the file didn't exist, perhaps the disk is failing. 
|-
| URISyntaxException
| An invalid URL or URI was given to a parser. For example, you may have tried to open the URL httpx://www.nps.edu/.
|-
| PrintException
| Your program tried to print something, and for some reason it can't print.
|-
|SQLException
| Your program sent invalid SQL to the database server.
|-
| UnsupportedLookAndFeelException
| Your program asked to use a look and feel that is not available on the current platform. For example, you may have told your program to use the Macintosh look and feel and it may be running on Windows.
|-
| SAXException
| You attempted to parse invalid XML
|}

==Catching One Exception==
Here is some simple code that calculates the mysterious B function: 
&lt;pre&gt;
public class B {
    int total=0;
    public B(int startValue){
        this.total = startValue;
    }
    int calc(){
        /* Calculate a complicated function of i,j and k */
        for(int q = 1; q&lt; 20;q+=1){
            total += total/q;
            total += (total-30) / (total);
        }
        return total;
    }

    public static void main(String[] args){
        int initialValue = Integer.parseInt(args[0]);
        B b = new B(initialValue);
        System.out.printf(&quot;b.calc()=%d %n&quot;,b.calc());
    }
}
&lt;/pre&gt;
Let's run it a few times:
&lt;pre&gt;
$ java B 1
b.calc()=-20 

$ java B 2
b.calc()=8 
&lt;/pre&gt;



And here's the exception:
&lt;pre&gt;
$ java B 3
Exception in thread &quot;main&quot; java.lang.ArithmeticException: / by zero
	at B.calc(B.java:10)
	at B.main(B.java:19)
&lt;/pre&gt;

So now we have a complicated piece of code which sometimes generates a fatal error. We could try to figure out every possible condition that might generate the error, but that's not the correct approach. This is an error based on user input. We just need to tell the user that the function doesn't work with that input. To do this, we need to catch the exception:

&lt;pre&gt;
    public static void main(String[] args){
        int initialValue = Integer.parseInt(args[0]);
        B b = new B(initialValue);
        try{
            System.out.printf(&quot;b.calc()=%d %n&quot;,b.calc());
        } catch (ArithmeticException e){
            System.out.printf(&quot;The B function cannot be calcualted for %d %n&quot;,initialValue);
        }
    }
&lt;/pre&gt;

When this runs, we get:

&lt;pre&gt;
$ java B 3
The B function cannot be calculated for 3 
$
&lt;/pre&gt;

==Catching Multiple Exceptions==
It turns out that there are two different ways that the user can give us invalid input:
# The user can supply a non-numeric argument
# The user can supply no  argument

These generate different exceptions:

&lt;pre&gt;
$ java B f
Exception in thread &quot;main&quot; java.lang.NumberFormatException: For input string: &quot;f&quot;
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
	at java.lang.Integer.parseInt(Integer.java:447)
	at java.lang.Integer.parseInt(Integer.java:497)
	at B.main(B.java:16)
$ java B 
Exception in thread &quot;main&quot; java.lang.ArrayIndexOutOfBoundsException: 0
	at B.main(B.java:16)
$ 
&lt;/pre&gt;

This code catches both exceptions:
&lt;pre&gt;
    public static void main(String[] args){
        int initialValue;
        try {
            initialValue = Integer.parseInt(args[0]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(&quot;You must supply at least one argument&quot;);
            return;
        } catch	(NumberFormatException e){
            System.out.println(&quot;You must supply a number.&quot;);
            return;
	}

        B b = new B(initialValue);
        try {
            System.out.printf(&quot;b.calc()=%d %n&quot;,b.calc());
        } catch (ArithmeticException e){
            System.out.printf(&quot;The B function cannot be calcualted for %d %n&quot;,initialValue);
        }
    }
&lt;/pre&gt;

==Java Exception Classes and Instances ==
In this code:
        } catch (ArithmeticException e){
The variable '''e''' is your exception variable. it's actually a local variable that is set to be the value of the exception.

There are some important things about Java exceptions that make them very different from C++ exceptions (but very similar to Python exceptions):
* Exceptions generated in your code are represented as '''instances''' of '''Exception Classes'''
* All exception classes inherit from the base class ''java.lang.Exception'' which, itself, is a subclass of ''java.lang.Throwable''
* You can create your own exceptions by subclassing Exception.
* You can throw your own exceptions with the '''throw''' statement.
* There is another subclass of Throwable called Error. These generally aren't caught.

==Printing the stack trace==
Even if you catch the exception, you may still want to print the stack trace. You do this by calling the exception object's '''printStackTrace()''' method, like this:

&lt;pre&gt;
        B b = new B(initialValue);
        try {
            System.out.printf(&quot;b.calc()=%d %n&quot;,b.calc());
        } catch (ArithmeticException e){
            System.out.printf(&quot;The B function cannot be calcualted for %d %n&quot;,initialValue);
            e.printStackTrace();
        }
&lt;/pre&gt;

And here is the code in action:

&lt;pre&gt;
$ java B 3
The B function cannot be calcualted for 3 
java.lang.ArithmeticException: / by zero
	at B.calc(B.java:10)
	at B.main(B.java:30)
$ %
&lt;/pre&gt;
Notice that the stack trace is printed for '''where the exception happened,''' not where it was printed.


==The '''finally''' statement==
You may want to have some code that '''always runs''':
* If an exception is thrown.
* If no exception is thrown.
* If there is a '''return''' statement.

This is what the '''finally''' statement is for.  You might use it:
* To erase a temporary file.
* To print some kind of special message.

Here is an example:
        B b = new B(initialValue);
        try {
            System.out.printf(&quot;b.calc()=%d %n&quot;,b.calc());
        } catch (ArithmeticException e){
            System.out.printf(&quot;The B function cannot be calcualted for %d %n&quot;,initialValue);
            e.printStackTrace();
            return;
        } finally {
            System.out.println(&quot;This code always runs&quot;);
        }

Notice that the '''return''' statement now appears after the '''e.printStackTrace();'''

Here's what it looks like when the code runs:
&lt;pre&gt;
$ java B 2
b.calc()=8 
This code always runs
$ java B 3
The B function cannot be calcualted for 3 
java.lang.ArithmeticException: / by zero
	at B.calc(B.java:10)
	at B.main(B.java:30)
This code always runs
$ 
&lt;/pre&gt;

==Checked vs. Unchecked Exceptions==
Java programmers use the term '''checked exception''' to indicate that method call that might generate an exception that happens within an appropriate '''try {} catch {}''' block. The phrase '''unchecked exception''' refers to an exception that is thrown without being in an appropriate block. 

; Checked Exceptions
* Used for runtime error conditions that are ''expected to occur'' and must be handled.
* Occur even after a program has been tested and deployed in the field.
* Must be declared if you throw them (see below)

; Unchecked Exceptions
* Used for runtime errors that are not expected to occur. 
* Things you want to catch when the program is in development.
* Usually the result of a bug in your program.
* Represent ''defects in the program''

The compiler will force you to check all methods that can throw an exception unless the exception is a subclass of '''RuntimeException''' or any of its subclasses.  

'''java.lang.ArithmeticException''' is a subclass of '''java.lang.RuntimeException''' and is therefore '''unchecked'''. You do not need to check for this exception. If it were a checked exception, then every time you wanted to have a division, you would need to put it in a '''try {} catch {}''' block, and that would be a huge pain.

==Throwing Exception==
So let's say you want to throw an exception....

In the ChargedBot() class, you may have a method that computes the electrostatic attractive force between two bots:

&lt;pre&gt;
    public double electrostaticForce(ChargedBot cb){
        double range = rangeToObject(cb);
        return -(charge * cb.charge) / (range*range);
    }
&lt;/pre&gt;

What happens if two bots are in the same position?
* range will be 0
* This will generate a divide-by-zero error.
* This will make NO SENSE TO THE PROGRAMMER!

We want to generate an ArithmeticException, but don't want it to say &quot;divide by 0.&quot; We want it to say '''something that will make sense to the programmer.'''

Here is the code that does it:
&lt;pre&gt;
    public double electrostaticForce(ChargedBot cb){
        double range = rangeToObject(cb);
        if(range==0) throw new ArithmeticException(&quot;Two bots cannot occupy the same space&quot;);
        return -(charge * cb.charge) / (range*range);
    }
&lt;/pre&gt;

Notice:
* To throw an exception, we say '''throw &lt;object&gt;'''
* Before we can throw, we need to make the exception object ('''new ArithmeticException(&quot;&quot;)''')
* ArithmeticException's constructor takes an optional '''String s''' which creates a ''detail message''. http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ArithmeticException.html

Instead of saying this:
            if(range==0) throw new ArithmeticException(&quot;Two bots cannot occupy the same space&quot;);
We could use ''ugly code'':
&lt;pre&gt;
            if(range==0){
               ArithmeticException e = new ArithmeticException(&quot;Two bots cannot occupy the same space&quot;);
               throw e;
             }
&lt;/pre&gt;

That '''e''' is the same instance that would be picked up by the appropriate '''catch''' statement.

==Throwing Another Exception==
We could '''bullet-proof''' the ChaseBot.setTarget method to make sure that nobody ever sets a bot to chase itself:

&lt;pre&gt;
    public void setTarget(FlatlandObject aTarget){
	if(aTarget==this) throw	new RuntimeException(&quot;ChaseBots cannot chase themselves&quot;);
        target = aTarget;
    }
&lt;/pre&gt;

==Making your own exceptions==
Instead of having electrostaticForce() throw an ArithmeticException, we may wish to create a new Exception class --- call it a '''RangeException.'''

    public class RangeException extends RuntimeException {
        RangeException(String message){
            super(message);
        }
    }

Then to throw it, you would say:

            if(range==0) throw new RangeException(&quot;Two bots cannot occupy the same space&quot;);

There are two places you could put the RangeException:
* In a file called '''RangeException.java'''
* As an inner class within the ChargeBot.java file, like this:

&lt;pre&gt;
    /** Inner exception class for invalid electrostatic force calculation                                             
     */
    public class RangeException extends RuntimeException {
        RangeException(String message){
            super(message);
        }
    }

    /**                                                                                                               
     * returns the electrostatic force applied by the provided object.                                                
     * where the electrostatic force is proportional to the product                                                   
     * of the two charge divided by the distance between them.                                                        
     */
    public double electrostaticForce(ChargedBot cb){
        double range = rangeToObject(cb);
        if(range==0) throw new RangeException(&quot;Two bots cannot occupy the same space&quot;);
        return -(charge * cb.charge) / (range*range);
    }
&lt;/pre&gt;

==Reporting Exceptions==
Methods that can throw a checked exceptions must report which exceptions they throw.

Because RangeException extends RuntimeException, it doesn't need to be checked.

Here is a weird X class and related function:
&lt;pre&gt;
public class X {
    int tally = 0;
    public int calc(int n){
	if(n==5) throw new RuntimeException(&quot;We do not like n==5&quot;);
	tally += n;
	return tally+n*n;
    }

    public void print10(){
	for(int i=0;i&lt;10;i++){
	    System.out.printf(&quot;calc(%d)=%d %n&quot;,i,calc(i));
	}
    }

    public static void main(String[] args){
	X obj = new X();

	obj.print10();
    }
}
&lt;/pre&gt;

And here's it running:

&lt;pre&gt;
$ java X
calc(0)=0 
calc(1)=2 
calc(2)=7 
calc(3)=15 
calc(4)=26 
Exception in thread &quot;main&quot; java.lang.RuntimeException: We do not like n==5
	at X.calc(X.java:4)
	at X.print10(X.java:11)
	at X.main(X.java:18)
$ 
&lt;/pre&gt;

If calc threw an Exception and not a RuntimeException, it wouldn't compile.

Here is the modified code:
&lt;pre&gt;
    public int calc(int n){
	if(n==5) throw new Exception(&quot;We do not like n==5&quot;);
	tally += n;
	return tally+n*n;
    }
&lt;/pre&gt;

And here is what happens when it is compiled:
&lt;pre&gt;
$ javac X.java
X.java:4: unreported exception java.lang.Exception; must be caught or declared to be thrown
	if(n==5) throw new Exception(&quot;We do not like n==5&quot;);
                 ^
1 error
$
&lt;/pre&gt;


The calc() method needs to be modified:

&lt;pre&gt;
    public int calc(int n) throws Exception{
        if(n==5) throw new Exception(&quot;We do not like n==5&quot;);
        tally += n;
        return tally+n*n;
    }
&lt;/pre&gt;

But the X.class still won't compile:

&lt;pre&gt;
$ javac X.java
X.java:11: unreported exception java.lang.Exception; must be caught or declared to be thrown
	    System.out.printf(&quot;calc(%d)=%d %n&quot;,i,calc(i));
                                                     ^
1 error
$ 
&lt;/pre&gt;

Look at the code:

&lt;pre&gt;
public class X {
    int tally = 0;
    public int calc(int n) throws Exception{
        if(n==5) throw new Exception(&quot;We do not like n==5&quot;);
        tally += n;
        return tally+n*n;
    }

    public void print10(){
        for(int i=0;i&lt;10;i++){
            System.out.printf(&quot;calc(%d)=%d %n&quot;,i,calc(i));
        }
    }

    public static void main(String[] args){
        X obj = new X();

        obj.print10();
    }
}
&lt;/pre&gt;

* print10 doesn't catch the Exception().
* You can see this by looking at the code.
* So can the compiler!


;Two ways to get the code to compile
; Approach #1 --- Catch the Exception

&lt;pre&gt;
public class X {
    int tally = 0;
    public int calc(int n) throws Exception{
	if(n==5) throw new Exception(&quot;We do not like n==5&quot;);
	tally += n;
	return tally+n*n;
    }

    public void print10(){
	for(int i=0;i&lt;10;i++){
	    try{
		System.out.printf(&quot;calc(%d)=%d %n&quot;,i,calc(i));
	    } catch(Exception e){
		System.out.println(&quot;Woot! Got an exception:&quot;);
		e.printStackTrace();
	    }
	}
    }

    public static void main(String[] args){
	X obj = new X();

	obj.print10();
    }
}
&lt;/pre&gt;

&lt;pre&gt;
$ javac X.java
$ java X
calc(0)=0 
calc(1)=2 
calc(2)=7 
calc(3)=15 
calc(4)=26 
Woot! Got an exception:
java.lang.Exception: We do not like n==5
	at X.calc(X.java:4)
	at X.print10(X.java:12)
	at X.main(X.java:23)
calc(6)=52 
calc(7)=72 
calc(8)=95 
calc(9)=121 
$ 
&lt;/pre&gt;

; Approach #2 --- Declare print10() as throwing the exception:
&lt;pre&gt;
public class X {
    int tally = 0;
    public int calc(int n) throws Exception{
        if(n==5) throw new Exception(&quot;We do not like n==5&quot;);
        tally += n;
        return tally+n*n;
    }

    public void print10() throws Exception {
        for(int i=0;i&lt;10;i++){
            System.out.printf(&quot;calc(%d)=%d %n&quot;,i,calc(i));
        }
    }

    public static void main(String[] args){
        X obj = new X();
        obj.print10();
    }
}
&lt;/pre&gt;

Compile it:

&lt;pre&gt;
$ javac X.java
X.java:17: unreported exception java.lang.Exception; must be caught or declared to be thrown
	obj.print10();
                   ^
1 error
$ 
&lt;/pre&gt;

Now the compiler knows that main() is not catching the exception. It needs to be fixed too:

&lt;pre&gt;
public class X {
    int tally = 0;
    public int calc(int n) throws Exception{
        if(n==5) throw new Exception(&quot;We do not like n==5&quot;);
        tally += n;
        return tally+n*n;
    }

    public void print10() throws Exception {
        for(int i=0;i&lt;10;i++){
            System.out.printf(&quot;calc(%d)=%d %n&quot;,i,calc(i));
        }
    }

    public static void main(String[] args){
        X obj = new X();
        try{
            obj.print10();
        } catch(Exception e){
            System.out.println(&quot;Woot! Got an exception:&quot;);
	    e.printStackTrace();
	}
    }
}
&lt;/pre&gt;

&lt;pre&gt;
$ javac X.java
$ java X
calc(0)=0 
calc(1)=2 
calc(2)=7 
calc(3)=15 
calc(4)=26 
Woot! Got an exception:
java.lang.Exception: We do not like n==5
	at X.calc(X.java:4)
	at X.print10(X.java:11)
	at X.main(X.java:18)
$ 
&lt;/pre&gt;

Note:
* This time the loop doesn't restart. (why not?)

==Notes on Exceptions==
* Exceptions are SLOW --- use them only for exceptional conditions (Bloch Item 39)
* Avoid Unnecessary use of checked exceptions (Bloch Item 41) --- Frequently the exceptions you throw should be unchecked.
* Throw exceptions appropriate to the abstraction (Bloch item 43) (NoSuchUser instead of SQLException) [http://www.ibm.com/developerworks/java/library/j-jtp05254.html]

==Assertions==
Java has a system called '''Assertions''' which allow you to specify invariants.  This is done with the '''assert''' keyword.

This code:
&lt;pre&gt;
    public void setTarget(FlatlandObject aTarget){
	if(aTarget==this) throw new RuntimeException(&quot;ChaseBots cannot chase themselves&quot;);
	target = aTarget;
    }
&lt;/pre&gt;
Could be rewritten like this:

&lt;pre&gt;
    public void setTarget(FlatlandObject aTarget){
	assert aTarget!=this;
	target = aTarget;
    }
&lt;/pre&gt;

When you run a program with assertions, you must give the Java runtime the '''-ea''' or '''-enableassertions''' flag (enable assertions). 

Here is a little demo program:
&lt;pre&gt;
public class x {
    public static void main(String[] args){
        assert false;
    }
}
&lt;/pre&gt;

And let's run it:

&lt;pre&gt;
$ java x
$ java -ea x 
Exception in thread &quot;main&quot; java.lang.AssertionError
	at x.main(x.java:3)
$ java -enableassertions x
Exception in thread &quot;main&quot; java.lang.AssertionError
	at x.main(x.java:3)
&lt;/pre&gt;

Assertion theory:
* Put lots of assertions in when developing the code.
* Run with -ea during Q&amp;A.
* Run without -ea when the product is shipped and running in the field.


Advantages of assertions:
* Clear language Support
* Clearly document expected internal state (e.g., assert radius&gt;0)
* Easy to disable in production code without having to edit your source file.


Disadvantages of assertions:
* They get disabled in the field, so people don't know if the program is not performing properly.
* Hard to give meaningful feedback other than '''assertion failed.'''
* An assertion statement that has a side-effect will change behavior if assertions are turned off.

BAD PROGRAM EXAMPLE:
&lt;pre&gt;
assert (i=j) == k;
&lt;/pre&gt;

See also: [http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html Programming with Assertions]

=Readings=
For Tuesday:
* [http://java.sun.com/docs/books/tutorial/essential/exceptions/ Java Tutorial trail on exceptions]

For Wednesday:
* [[Media:P33-zaidman.pdf|Teaching Defensive Programming in Java]], Marsha Zaidman, 2003.

This Week:
*Day 7: Exceptions, Assertions, and Threads, in ''Teach Yourself Java in 21 days''

If you purchased  Head First Java, you should now be familiar with these chapters:
* Chapter 1, Breaking the Surface
* Chapter 2, A Trip to Objectville
* Chapter 3, Know your Variables
* Chapter 4, How Objects Behave
* Chapter 7, Better Living in Objectville
* Chapter 9, Life and Death of an Object
* Chapter 10, Numbers Matter

For this week, read:
* Chapter 11, Risky Behavior.

=Technologies=


=See Also=
;Checked vs. unchecked exceptions:
* http://www.javapractices.com/topic/TopicAction.do?Id=129
* http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html
* http://www.ibm.com/developerworks/java/library/j-jtp05254.html
* http://www.psynixis.com/blog/2007/06/06/the-ungreat-checkedunchecked-exceptions-debate/
* http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html</text>
    </revision>
  </page>
  <page>
    <title>Week 05: Basic Graphics and GUI with AWT and Swing</title>
    <id>21</id>
    <revision>
      <id>831</id>
      <timestamp>2008-02-08T16:25:08Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>/* =Information on CSS */</comment>
      <text xml:space="preserve">*'''Previous: ''' [[Week_04:_I/O|Week 04: I/O]]
*'''Next: ''' [[Week_06:_Java_2D_and_3D|Week 06: Java 2D and 3D]]
* '''Slides:''' [[Media:Week5.pdf]] Week 5 slides are posted.
* [[Media:Week5b.pdf]] Tuesday's slides
* [[Media:Week5c.pdf]] Thursday's slides

{{JavaWeek
|week=5
|name= Basic Graphics and GUI with AWT and Swing
|shortname=Swing
}}



=Goals=
* Anonymous classes and pseudo-function pointers
* Swing
* HelloWorldSwing (anonymous classes)
* Basic GUI components
* Containment Hierarchy
* Frames, event-driven programming,
* Events &amp; Listeners.
* http://java.sun.com/docs/books/tutorial/uiswing/components/jcomponent.html
=Notes=
Additions onto the class notes:

* The Java Tutorial has a [http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html nice page] on Using Top-Level Containers JFrame, JDialog, and JApplet.
==JFrame==
==JComponent==
==Layout Managers==
Layout managers describe how JComponents added to a JComponent or a JFrame are layed out.

* [http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html Java Layout Page]

The one &quot;gatcha,&quot; as Sun calls it, is that the ''contentPane'' of the JFrame is a &lt;tt&gt;Container&lt;/tt&gt; and not a &lt;tt&gt;JComponent&lt;/tt&gt;. Sun says you need to do one of the following:

# Typecast the return value.
# Create your own component to cover the content pane.

Sun recommends the following. Here is an easy way to do it:

&lt;pre&gt;
//Create a panel and add components to it.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(someBorder);
contentPane.add(someComponent, BorderLayout.CENTER);
contentPane.add(anotherComponent, BorderLayout.PAGE_END);


topLevelContainer.setContentPane(contentPane);
&lt;/pre&gt;

Fourth GUI in the SVN repository has been updated to follow this approach.

=Consider a simple Swing Program:=

&lt;pre&gt;
import javax.swing.*;

public class FirstGUI {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,300);
       frame.setVisible(true);
    }
}
&lt;/pre&gt;

This program will create a window with no functionality.  All Swing objects are JFrame objects.
This includes windows, buttons, etc.

Now we add a clickable button 

&lt;pre&gt;
public class FirstGUI {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton button = new JButton(&quot;click me&quot;);
        frame.getContentPane().add(button);
        frame.setSize(300,300);
        frame.setVisible(true);
    }
}
&lt;/pre&gt;

=See Also=
==Some good examples of Swing applications==
* http://examples.oreilly.com/jswing2/code/
* http://www.javabeginner.com/java-swing-tutorial.htm
==Information on CSS==
* http://www.w3schools.com/css/

=Readings=

* Read the [http://en.wikipedia.org/wiki/Therac-25 Wikipedia article on the Therac-25]
* Please skim the [[Media:Therac-25.pdf|Therac-25 article]]

*A streaming lecture on the Therac-25 [http://wla.berkeley.edu/data/cs61a_spring2005/lec_37_cs61a_therac25.html#software_reliability_therac_failures_title]

= =
*'''Previous: ''' [[Week_04:_I/O|Week 04: I/O]]
*'''Next: ''' [[Week_06:_Java_2D_and_3D|Week 06: Java 2D and 3D]]</text>
    </revision>
  </page>
  <page>
    <title>Week 06: Java 2D and 3D</title>
    <id>112</id>
    <revision>
      <id>833</id>
      <timestamp>2008-02-10T00:06:59Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <comment>[[Week 06: Java 2D and 3D]] moved to [[Week 06: More Swing]]: We're not going to be doing Java 2D and 3D</comment>
      <text xml:space="preserve">#REDIRECT [[Week 06: More Swing]]</text>
    </revision>
  </page>
  <page>
    <title>Week 06: More Swing</title>
    <id>22</id>
    <revision>
      <id>866</id>
      <timestamp>2008-02-14T16:24:50Z</timestamp>
      <contributor>
        <username>Bmhawkin</username>
        <id>7</id>
      </contributor>
      <text xml:space="preserve">*'''Previous: ''' [[Week_05:_Basic_Graphics_and_GUI_with_AWT_and_Swing|Week 05: Basic Graphics and GUI with AWT and Swing]]
*'''Next: ''' [[Week_07:_Unicode%2C_Text_%26_Internationalization|Week 07: Unicode, Text &amp; Internationalization]]

* [[Media:week6.pdf|Week 6 Slides - Monday]]
* [[Media:week6b.pdf|Week 6 Slides - Thursday]]


*[[Media:Lecture15.pdf]]

{{JavaWeek
|week=6
|name=Java 2D and 3D
|shortname=2D and 3D
}}

=Goals=
* Applets
* Really understand Swing
* Building GUI's with the NetBeans GUI builder.

=Class Notes=
* [[mime.types|A mime.types file]]
* [http://www.iana.org/assignments/media-types/ IANA's official mime.types]

==Applet Examples==
* [https://java3d.dev.java.net/applets/FourByFour.html Java3D with applet tags]
* [https://domex.nps.edu/cs3773/week6 Week6 Applet Demo]

==NetBeans GUI Builder (Matisse)==
* [http://form.netbeans.org/ GUI Builder home page]
* [http://www.netbeans.org/kb/50/quickstart-gui.html Quick Start Guide]
* [http://www.netbeans.org/kb/articles/matisse.html Java GUIs and Project Matisse Learning Trail] at netbeans.org
* [http://weblogs.java.net/blog/joconner/archive/2006/10/fighting_with_n.html John O'Conner's Java.net blog post]

=Readings=
By the end of this week you should be comfortable writing programs using JFC/Swing. In our book ''Teach Yourself Java in 21 Days'' you should read and be familiar with the material in these chapters:
* Day 9: Working with Swing
* Day 10: Building a Swing Interface
* Day 11: Arranging Components on a User Interface
* Day 12: Responding to User Input
* Day 13: Using Color, Fonts, and Graphics

If you are working in ''Head First Java,'' be familiar with these chapters:
* Chapter 12: A Very Graphic Story
* Chapter 13: Work on your Swing

Wednesday Reading: 
Originally we were going to read this article:
* [[Media:P57-reiss.pdf|Visualizing Java in Action]], Steven P. Reiss, Software Visualization, 2003
Instead, we will try something different.

Pick one of the following Java visualization toolkits. Spend 30 minutes learning what you can about it. Read the documentation, look at the screen shots, see if you can download a demo and get something to work. Be prepared to speak for 2-3 minutes about the toolkit of your choice (those in bold were from the original list):
* '''[http://jung.sourceforge.net/ JUNG]'''
* '''[http://www.personal.psu.edu/faculty/c/e/cew15/improvise/index.html Improvise]'''
* [http://csbi.sourceforge.net/index.html Graph Interface Library (GINY)] - Java
* [http://www.gravisto.org/ Gravisto: Graph Visualization Toolkit] - An editor and toolkit for developing graph visualization algorithms. 
*  [http://hypergraph.sourceforge.net/ HyperGraph] - Hyperbolic trees, in Java. Check out the home page. Try clicking on the logo...
* '''[http://ivtk.sourceforge.net/ InfoViz Toolkit] - Java, originally developed at [[INRA]].  Does not appear to be currently maintained ''' [[User:Tmrashid|Tmrashid]] 08:41, 13 February 2008 (PST)
* [https://jdigraph.dev.java.net/ Jdigrah] - Java Directed Graphs.
* [http://jgrapht.sourceforge.net/ JGraphT] - A Java visualization kit designed to be simple and extensible. 
* [http://www.softwaresecretweapons.com/jspwiki/Wiki.jsp?page=LinguineMaps Linguine Maps] - An open-source Java-based system for visualizing software call maps.
* '''[http://prefuse.org/ Perfuse] - A Java-based toolkit for building interactive information visualization applications'''
* [http://www.gnu.frb.br:8080/rox Rox Graph Theory Framework] - An open-source plug-in framework for graph theory visualization.
* [http://touchgraph.sourceforge.net/ TouchGraph] - Library for building graph-based interfaces.
* [http://www.ssec.wisc.edu/~billh/visad.html#intro VisAD] - A Java component library for interactive and collaborative visualization.
* '''[http://public.kitware.com/VTK/ The Visualization Toolkit] - C++ multi-platform with interfaces available for Tcl/Tk,''' Java and Python. Professional support provided by [http://www.kitware.com/ Kitware].
* [http://zvtm.sourceforge.net/index.html Zoomable Visual Transformation Machine] - Java. Originally started at Xerox Research Europe.
* '''[http://processing.org/ Processing.org] - A new language for doing graphics and visualization.'''

=References=
* [http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JPanel.html javax.swing.JPanel]
* [http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html java.awt.Desktop]
* [http://java.sun.com/javase/6/docs/api/java/awt/SystemTray.html java.awt.SystemTray]
* [http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/systemtray/ Article about using the System Tray]
* [http://java.sun.com/products/jfc/tsc/articles/painting/ Painting in AWT and Swing: Good Painting Code Is the Key to App Performance, by Amy Fowler]

= =
*'''Previous: ''' [[Week_05:_Basic_Graphics_and_GUI_with_AWT_and_Swing|Week 05: Basic Graphics and GUI with AWT and Swing]]
*'''Next: ''' [[Week_07:_Unicode%2C_Text_%26_Internationalization|Week 07: Unicode, Text &amp; Internationalization]]</text>
    </revision>
  </page>
  <page>
    <title>Week 07: Unicode, Text &amp; Internationalization</title>
    <id>23</id>
    <revision>
      <id>889</id>
      <timestamp>2008-02-21T06:02:46Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>/* Lucene */</comment>
      <text xml:space="preserve">*'''Previous: ''' [[Week_06:_Java_2D_and_3D|Week 06: Java 2D and 3D]]
*'''Next: ''' [[Week_08:_Threads_and_the_System|Week 08: Threads and the System]]

{{JavaWeek
|week=7
|name=Unicode, Text &amp; Internationalization
|shortname=Text
}}

* [[Media:week7.pdf]] 

=Goals=
* Understand ASCII, Latin1 and Unicode
* Learn about Lucene, the open source indexing kit.
* Build an application using Lucene that will index the files on your computer.

=Lucene=
Lucene is the open source indexing kit. Lucene can build an index of documents on your hard drive or on a website, and then provide you with tools for rapidly searching that index for words or phrases. 

We are learning about Lucene for several reasons:
* Working with text is hard, and Lucene does an excellent job.
* In many of your programs you may wish to rapidly search through some data. Lucene is a fast way to do it.
* You're almost always better off using debugged code than trying to develop something on your own.
* Using Lucene will teach you more about using other people's code.

Below are some links that you may find helpful in trying to understand Lucene:
* [http://lucene.apache.org/java/docs/ Lucene home page]
* [http://lucene.apache.org/java/2_3_0/api/index.html JavaDocs for Lucene 2.3]
* [http://lucene.apache.org/java/2_3_0/gettingstarted.html Lucene getting started guide]
* [http://www.apache.org/dyn/closer.cgi/lucene/java/ Lucene Download]
** [http://lucene.apache.org/java/2_3_0/demo.html Lucene command-line demo] (try it!)
* [[org.apache.lucene.demo.SearchFiles source]]
* [[org.apache.lucene.demo.IndexFiles source]]

==See Also==
* [http://wordnet.princeton.edu/ WordNet]

=Readings=

We were going to read this:
* [[Media:P109-prechelt.pdf|Comparing Java vs. C/C++ Efficiency Differences to Interpersonal Differences]], Lutz Prechelt, October 1999

You are still welcome to read it, but we will be discussing this in class:
* [http://www.ddj.com/architect/184414603 Your Passport to Proper Internationalization], Benson I. Margulies, Dr. Dobb's Journal, May 2000.


Please read Chapter 2 of the Unicode book:
* [http://www.unicode.org/versions/Unicode4.0.0/ch02.pdf Chapter 02]

= =
*'''Previous: ''' [[Week_06:_Java_2D_and_3D|Week 06: Java 2D and 3D]]
*'''Next: ''' [[Week_08:_Threads_and_the_System|Week 08: Threads and the System]]</text>
    </revision>
  </page>
  <page>
    <title>Week 08: Threads and the System</title>
    <id>24</id>
    <revision>
      <id>931</id>
      <timestamp>2008-02-28T08:07:12Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>/* Serialization */</comment>
      <text xml:space="preserve">*'''Previous: ''' [[Week_07:_Unicode%2C_Text_%26_Internationalization|Week 07: Unicode, Text &amp; Internationalization]]
*'''Next: ''' [[Week_09:_Network_programming_with_Java|Week 09: Network programming with Java]]

{{JavaWeek
|week=8
|name=Threads and the System
|shortname=Threads
}}




=Goals=
* Threads
* Synchronization
* Serialization

=Slides=
* [[Media:week8.pdf]]
* [[The Life Cycle of a Thread]]

=Notes on Class Topics=
==Serialization==

When an object is serialized, java writes a '''serialVersionUID'' into the object archive. This is supposed to be a unique version number for the object that you are using. Whenever you change the object's instance variables that are not transient, you need to change the serialVersionUID.

If you do not declare your own '''serialVersionUID,''' the compiler will figure one up for you at runtime. The problem with this approach, though, is that newer versions of your object can't read older versions.

Some people put things like this into their class files:

	//Added to make warning go away.
	private static final long serialVersionUID = 1L;

This is usually a bad idea, because it means that any change to the class will not result in the object serialVesionUID being saved in the archive. That's fine if you want to write code that can handle reading the older versions of your objects. 

To get the UID, you can use the java program '''serialver'''.

Here is a sample class:

&lt;pre&gt;
import java.io.*;

public class y implements Serializable {
    int f;
}
&lt;/pre&gt;



To get the serialVersionUID, compile it and then run '''serialver''':

&lt;pre&gt;
$ javac y.java
$ serialver y
y:    static final long serialVersionUID = 1534365507996228659L;
$
&lt;/pre&gt;

The class should now look like this:

&lt;pre&gt;
import java.io.*;

public class y implements Serializable {
    int f;
    static final long serialVersionUID = 1534365507996228659L;
}
&lt;/pre&gt;

If you make a change to the class, you get a different '''serialVersionUID:'''

&lt;pre&gt;
import java.io.*;

public class y implements Serializable {
    int f;
    int g;
}
&lt;/pre&gt;


&lt;pre&gt;
$ javac y.java
$ serialver y
y:    static final long serialVersionUID = -4791259395666985996L;
$
&lt;/pre&gt;

Note that Eclipse (but not NetBeans) can figure this out for you if you click the lightbulb.

* [http://java.sun.com/javase/6/docs/technotes/tools/solaris/serialver.html Sun documentation on '''serialver''' command]
* [http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html Sun documentation on Serializable]
* [http://forum.java.sun.com/thread.jspa?messageID=3491115&amp;tstart=0 Discussion on the Sun chat boards]

==Reflection==
=See Also=
* [http://www.ibm.com/developerworks/java/library/j-jtp06197.html Managing Volatility]: Guidelines for using volatile variables, Brian Goetz, Senior Staff Engineer, Sun Microsystems, IBM Developer Works.
* [http://weblogs.java.net/blog/kgh/archive/2004/10/multithreaded_t.html Multithreaded toolkits: A failed dream?], Graham Hamilton, java.net developer's blog, October 19, 2004.
* [http://java.sun.com/docs/books/performance/1st_edition/html/JPIOPerformance.fm.html Java Performance Chapter 4 - I/O Performance] - Nice discussion about Basic I/O, Buffered Streams, and Serialization.

=Readings=
[[Media:A3-yamauchi.pdf|Writing Solaris Device Drivers in Java]]
==See Also==
* http://en.wikipedia.org/wiki/Trampoline_(computers)

= =
*'''Previous: ''' [[Week_07:_Unicode%2C_Text_%26_Internationalization|Week 07: Unicode, Text &amp; Internationalization]]
*'''Next: ''' [[Week_09:_Network_programming_with_Java|Week 09: Network programming with Java]]</text>
    </revision>
  </page>
  <page>
    <title>Week 09: Network programming with Java</title>
    <id>25</id>
    <revision>
      <id>979</id>
      <timestamp>2008-03-05T08:47:22Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>/* Lesson Plan: Tuesday */</comment>
      <text xml:space="preserve">*'''Previous: ''' [[Week_08:_Threads_and_the_System|Week 08: Threads and the System]]
*'''Next: ''' [[Week_10:_Style_and_Performance|Week 10: Style and Performance]]

{{JavaWeek
|week=9
|name=Network programming with Java
|shortname=net
}}


=Goals=
You should know this by the end of this week:
* Theory: TCP/IP, client/server computing, OSI Stack, Sockets 
* SOAP, XMLRPC, and REST
* Downloading a web pages

You may wish to know this:
* JavaSocket, Server Socket

=Lesson Plan: Monday=
* Review Final Project
* Show how to add a web page to the wiki
* Discuss Networking (See Goals above)

=Lesson Plan: Tuesday=
Things to think about:
* We use the HttpURLConnection, InputStreamReader, and BufferedReader classes to read from a URL. 
** Is it better to read the entire web page at one time, or to read it line-by-line, or something else?
** Can you always read an '''entire''' web page?
=Lesson Plan: Wednesday=
* Go over [[modified single-threaded server]]
** Show with one client
** Show with two simultaneous clients
* Go over [[modified multi-threaded server]]
** Examine synchronize methods.
** Show with one client
** Show with two simultaneous clients

= Readings =
Please review the following chapters in Teach Yourself Java 6 in 21 Days:
* Day 17, Communicating Across the Internet

You may also find these chapter sot be useful for work that we have previously discussed:
* Day 14, Developing Swing Applications (especially the section about java Web Start)
* Day 16, Serializing and Examining Objects (just read pages 433-442)
* Day 15, Working with Input and Output (especially pages 422-429)

There is no reading for Wednesday; instead, David Pollack will give a special presentation about [http://www.scala-lang.org/ Scala Programming Language] on Thursday.


Good article on threading:
* [http://www.ibm.com/developerworks/java/library/j-threads1.html Threading Lightly, Part 1: Synchronization is not the enemy]

= =
*'''Previous: ''' [[Week_08:_Threads_and_the_System|Week 08: Threads and the System]]
*'''Next: ''' [[Week_10:_Style_and_Performance|Week 10: Style and Performance]]</text>
    </revision>
  </page>
  <page>
    <title>Week 10: Style and Performance</title>
    <id>26</id>
    <revision>
      <id>1067</id>
      <timestamp>2008-03-14T16:39:19Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <comment>/* Handling Document Events */</comment>
      <text xml:space="preserve">*'''Previous: ''' [[Week_09:_Network_programming_with_Java|Week 09: Network programming with Java]]

{{JavaWeek
|week=10
|name=Style and Performance
|shortname=style
}}

Possible Topics:
* Reflection
* Memory Management
* Profiling
* GCJ
* Security Policy
* [http://java.sun.com/javase/technologies/core/basic/rmi/index.jsp Java RMI]

=Reflection=
Here is a little program that prints the methods for java.lang.String:
&lt;pre&gt;
import java.lang.reflect.*;

public class ReflectionDemo {
    public static void main(String[] args){
        System.out.println(&quot;Get a String class and show the methods that it implements&quot;);

        try {
            Class stringClass = Class.forName(&quot;java.lang.String&quot;);
            System.out.println(&quot;Class: &quot;+stringClass.getName());
            System.out.println(&quot;Methods:&quot;);
            Method[] methods = stringClass.getMethods();
            for(Method m: methods){
                System.out.println(&quot;   &quot;+m.getName());
            }
        } catch (ClassNotFoundException e){
            System.out.println(&quot;Class not found: &quot;+e.getMessage());
        }
    }
}
&lt;/pre&gt;
[[Output 1]]


Change the print line to do this see the return type of each:
&lt;pre&gt;
                System.out.printf(&quot;  (%s) %s %n&quot;,m.getReturnType().getName(),m.getName());
&lt;/pre&gt;
[[Output 2]]

=Notes For Effective Java=
==Comparable==
* [http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html Interface Comparable&lt;t&gt;]
* [http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html article on pre-Java5 Comparable]
Advantages of new Comparable:
* You don't need to do instanceof (type safety)
* Less code to implement.

Here is a simple class that implements comparable:
&lt;pre&gt;
public class Person implements Comparable&lt;Person&gt;{
    String name;
    int age;
    public int compareTo(Person p){
        int r = name.compareTo(p.name);
        if(r!=0) return r;
        if(age&lt;p.age) return -1;
        if(age&gt;p.age) return 1;
        return 0;
    }
}
&lt;/pre&gt;

==Clone==
* Note that &quot;cloneable&quot; is misspelled.
* Please see the [http://domex.nps.edu/cs3773/svn/week10/src/week10/CloneDemo.java CloneDemo.java] and [http://domex.nps.edu/cs3773/svn/week10/src/week10/Person.java Person.java] in the subversion repository.
* If the class you are extending implements clone(), your class must implement clone()
* To clone:
** First make a copy with super.clone()
** Next, clone (or copy) the instance variables that are mutable.
* JavaPractices.com recommends avoiding clone entirely:
** [http://www.javapractices.com/topic/TopicAction.do?Id=71 Avoid clone]
** use [http://www.javapractices.com/topic/TopicAction.do?Id=12 Copy constructors] instead.
** Use [http://www.javapractices.com/topic/TopicAction.do?Id=29 Immutable objects] when possible.

String is an immutable object. They have a lot of advantages:
* Are thread-safe
* Do not need a copy constructor
* Do not need an implementation of clone (since copying the fields is fine)
* Lots of other advantages (see  [http://www.javapractices.com/topic/TopicAction.do?Id=29 Immutable objects]).

=Choices for Text Field Validation=
==Handling Document Events==
The correct way to do validation of a text field is by creating a DocumentEvent handler class and object. The object receives document changed events. a removeUpdate() event is generated when text is removed from the text field and an insertUpdate() event is generated when text is added.

Here is some code from the JPanel constructor of my test program:
&lt;pre&gt;
        initComponents();
        textField.getDocument().addDocumentListener(new DocumentListener() {
            public void changedUpdate(DocumentEvent e){
                String text = textField.getText();
                dlStatus.setText(&quot;changedUpdate: textField has &quot; + text.length() + &quot; characters&quot;);
            }
            public void removeUpdate(DocumentEvent e){
                String text = textField.getText();
                dlStatus.setText(&quot;removeUpdate: textField has &quot; + text.length() + &quot; characters&quot;);
                
            }
            public void insertUpdate(DocumentEvent e){
                String text = textField.getText();
                dlStatus.setText(&quot;insertUpdate textField has &quot; + text.length() + &quot; characters&quot;);                
            }
        });
        dlStatus.setText(&quot;dlListener created&quot;);
&lt;/pre&gt;
the '''initComponents()''' is put in by the NetBeans GUI builder. This creates an anonymous subclass of the DocumentListener interface. The changedUpdate() event is called when a document's ATTRIBUTES change (like bold), not when its text changes.

This is a better approach for input validation than picking up the keyTyped() events because it will pick up changes to the &quot;document&quot; (the text of the text field) that are caused by copy and paste.

==Another way to do it==
Another way to make this work is to use java's '''invokeLater''' method which causes a piece of code to be run ''after'' the current event is processed. This works (as shown below), but it has a problem: document change events that are not the result of keyboard characters (like a cut and paste) will not cause the textFieldKeyTyped event to be sent.
&lt;pre&gt;
    private void textFieldKeyTyped(java.awt.event.KeyEvent evt) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                String text = textField.getText();
                statusLabel.setText(&quot;textField has &quot; + text.length() + &quot; characters&quot;);

            }
        });
        
    }
&lt;/pre&gt;


==References==
Lots of people seem confused by this. Here are some relevant URLs:
* [http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JTextField.html JTextField] documentation.
* [http://www.velocityreviews.com/forums/t132891-keypressed-event-problem.html Java Forum Key Pressed Event Problem discussion]
* [http://java.sun.com/docs/books/tutorial/uiswing/events/documentlistener.html Java Tutorial How to write a document listener]

=Readings=
*[http://java.sun.com/docs/books/tutorial/reflect/index.html The Reflection API]

Readings From [http://java.sun.com/docs/books/effective/chapters.html ''Effective Java'']:
* [http://books.google.com/books?id=ZZOiqZQIbRMC&amp;dq=effective+java&amp;pg=PP1&amp;ots=UZK04vgK80&amp;sig=GjYD6P3Ydw2PTCzDoXdYgefWcnM&amp;hl=en&amp;prev=http://www.google.com/search?client=safari&amp;rls=en-us&amp;q=effective+java&amp;ie=UTF-8&amp;oe=UTF-8&amp;sa=X&amp;oi=print&amp;ct=title&amp;cad=one-book-with-thumbnail#PPA5,M1 Chapter 1 (bits) - on Google Books]
* [http://developer.java.sun.com/developer/Books/effectivejava/Chapter3.pdf Chapter 3 - Methods Common to All Objects]
* [http://developer.java.sun.com/developer/Books/effectivejava/Chapter5.pdf Chapter 5 - Substitutes for C Constructions]
* [http://www.informit.com/articles/article.aspx?p=31551 Chapter 6 - Methods]
* [http://www.informit.com/content/images/0201310058/samplechapter/ch7generalp.pdf Chapter 7 - General Programming]

= =
*'''Previous: ''' [[Week_09:_Network_programming_with_Java|Week 09: Network programming with Java]]</text>
    </revision>
  </page>
  <page>
    <title>Week 11: The Big Finish</title>
    <id>157</id>
    <revision>
      <id>1168</id>
      <timestamp>2008-03-21T01:14:59Z</timestamp>
      <contributor>
        <username>Crfitzpa</username>
        <id>16</id>
      </contributor>
      <comment>/* Friday */</comment>
      <text xml:space="preserve">{{JavaWeek
|week=11
|name=The Big Finish
|shortname=Finish
}}


=Goals=
* Answer all outstanding questions
* Final Project Presentations
* Tuesday: [[SQL &amp; JDBC]]
* Wednesday: [[JAVA Security]]
* Thursday: [[My favorite Tools]]

=Bloch, Chapter 4: Classes and Interfaces=
==Item 12: Minimize the accessibility of classes and members==
[http://www.google.com/search?client=safari&amp;rls=en-us&amp;q=%22Item+12:+Minimize+the+accessibility+of+classes+and+members%22&amp;ie=UTF-8&amp;oe=UTF-8 find copyright violations]
* Make each class or member as inaccessible as possible.
* Accessibility hiearchies:
** public
** protected
** package-private (default access)
** Private
** local
* Make things final unless they need to be modifiable
* Make things static unless they need to access instance variables.
* Don't use public fields---if a field is non-final or a final reference to a mutable object, you give up the ability to:
** validate a field
** Take an action when a field is modified
**  Contents of a final array are modifiable!
==Item 13: Favor Immutability==
# Don't provide any methods that modify the object (mutators)
# Ensure that no methods may be overridden
# Make all fields final
# Make all fields private
# Ensure exclusive access to any mutable components

Advantages of immutable objects:
* They are thread-safe and require no synchronization
* They can be shared freely
* The internals can also be shared
* Immutable objects make great building blocks for other objects
* Use static factories instead of constructors

==Item 14: Favor composition over inheritance==
* Subclasses need to understand their parent classes
==Item 15: Design and Document for inheritance or else prohibit it==

==Item 16: Prefer interfaces to abstract classes==
* Existing classes can be easily retrofitted to implement new interfaces
* Interfaces are ideal for defining mixins.

==Item 17: Use interfaces only to define types==

* Don't define constants in interfaces

==Item 18: Favor static member classes over nonstatic==

=Sign-up for Final Projects=
==Thursday==
0800 - Craig Schwetje

==Friday==
0800 - 0815: Jason Nelson

0815 - 0830: Brian Hawkins

0830 - 0845: Tariq Rashid

0845 - 0900: 

0900 - 0915: 

0915 - 0930: 

0930 - 0945: 

0945 - 1000:</text>
    </revision>
  </page>
  <page>
    <title>Week 2: Classes</title>
    <id>28</id>
    <revision>
      <id>156</id>
      <timestamp>2007-12-02T06:21:11Z</timestamp>
      <contributor>
        <username>Simsong</username>
        <id>1</id>
      </contributor>
      <comment>[[Week 2: Classes]] moved to [[Week 02: Classes]]</comment>
      <text xml:space="preserve">#REDIRECT [[Week 02: Classes]]</text>
    </revision>
  </page>
  <page>
    <title>Week 3 Grading Rubrick</title>
    <id>101</id>
    <revision>
      <id>781</id>
      <timestamp>2008-02-04T07:44:59Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <minor/>
      <text xml:space="preserve">Week 3's homework had a total of 100 possible points. Here is how they were divided:

{|class=&quot;wikitable&quot;
|-
|'''Problem Part''' 
|'''Possible Points'''
|-
| Something Submitted
| 10
|-
| Snake Submitted
| 10
|-
| Snake Works
| 10
|-
| AffinityBot.java submitted
| 10
|-
| AffinityBot code clarity
| 10
|-
| Affinity Bot works
| 10
|-
| ChargeBot submitted
| 10
|-
| ChargeBot implemented as a clean subclass of ChaseBot
| 10
|-
| ChargeBot has valid electrostatic implementation
| 10
|-
| ChargeBot simulation works
| 10
|}</text>
    </revision>
  </page>
  <page>
    <title>Week 3 Redux</title>
    <id>92</id>
    <revision>
      <id>674</id>
      <timestamp>2008-01-28T15:57:51Z</timestamp>
      <contributor>
        <username>Slgarfin</username>
        <id>1</id>
      </contributor>
      <text xml:space="preserve">Week 3 grading policy:

Full credit for:
* Working Snake
* Beautiful Code

Additional Credit for:
* Something with Charge bots &amp; electrostatic simulation
* Something with Schelling

Automatic Homework Submission Link:
* Modified to tell you what you submitted 
* Will warn if you didn't submit source code or compiled code.

Week 4 homework plans:
* Simple set of Q&amp;A
* Simple code to test and try exceptions
* Simple code to test and try SQL access.

Week 5 homework plans:
* We will return to Flatland with a new architecture that's more resistant to the problem.</text>
    </revision>
  </page>
  <page>
    <title>Wyatt - Final Project Proposal</title>
    <id>158</id>
    <revision>
      <id>1194</id>
      <timestamp>2008-03-27T22:19:39Z</timestamp>
      <contributor>
        <username>Tdwyatt</username>
        <id>11</id>
      </contributor>
      <comment>/* Summary */</comment>
      <text xml:space="preserve">[[Category:Final Projects]]
=Final Project Proposal: Java-based pattern scanning and exporting engine.=

==Summary==

I propose to create a java application that can read a data source, looking for a pattern to match, and output matching text to screen or file.  The application will be written as an applet, will run in any web browser, and will use a Swing-based GUI.  Application will use plain text, or regular expressions for the scanning pattern.

==Requirements==

* Swing-based GUI will allow the user to specify the input and output parameters
* User will be able to scan with full Regular Expressions (REGEX) support
* GUI will have a button to start the scan, as well as to specify the input/output files
* GUI will let the user specify which backreference group to use as the output. Ex: &quot;abc(0-9*)&quot;. 
* GUI lets the user pre-compile the regular expression and has error handling.

==Practical Use==

I am also designing this as a tool to use in my daily work.  The intial requirement is to scan a Rich Text doc of arbitrary size, to collect a unique survey password.  Ideally the person in NPS admin who needs this data can eventually use this applet themselves, to gather up the passwords, then send them on to me for distribution.

==DELIVERABLES==

Final Project Documentation is [[:media:Final_Project_Wyatt.pdf|available in PDF format]].  I have also emailed the application JAR file and documentation to Prof. Garfinkel.</text>
    </revision>
  </page>
</mediawiki>
