Getting Familiar with Linux for Java Programmers

The purpose of this tutorial is to familiarize Java programmers with the Linux Operating System, an environment that is becoming the operating system of choice for Computer Science professionals. The advantage of using this OS are many. It is stable; it is fast; you can access our system from home; and it is free!!! Most computer science schools use some form of UNIX whether it is Linux (a UNIX variant) or something else. Knowing Linux will be a big plus for you. The Linux material needed for this class is covered in this lab.

Some Java programming will be done on a Linux machine named cs.stcc.edu. You will maintain a public website on the machine as well. Your linux account is temporary and will last only until the end of the semester.

The first thing you will need to understand is that the console terminal is strickly keyboard based.  There is no graphics or mouse interaction with the cs machine.

Follow these steps to get acquainted with our system:

Step 1: Read the Authorized Computer Usage Policy

Read the Authorized Computer Usage Policy. This document describes what is expected from responsible users of our system. Violations to this policy will result in having your account removed; serious violations will be referred to the Dean of Students Office.


Step 2: Remote Login and File Transfer Software Usage

Originally. you use telnet to logon to a Linux machine. However, most companies and schools have abandoned telnet for a program called an ssh client to perform the same function. ssh stands for Secure Shell; ssh encrypts all communication between your workstation and the Linux Server. Microsoft provides no support for ssh in any of its products; you’ll need to get it from a third party. Without encryption, it is possible for a third party to intercept your passwords or any other data you may type. This is a tremendous security problem, therefore support for telnet has been removed from cs.

If you want secure communications and there is no ssh client on your machine, download PuTTY, a free program that you can download from this URL:

http://www.chiark.greenend.org.uk/~sgtatham/putty/

You only need to download the file putty.exe. Once downloaded there is no installation; you just run it.

To connect to cs, enter in the Host Name box:

cs.stcc.edu

And then click the “SSH” button under Protocol. Click the Open button. You will be presented with a command prompt window. Enter your username and password and should see the dollar sign ($) prompt. When interacting with a UNIX operating system, you must remember that Linux is CASE SENSITIVE!!! While Windows may be more forgiving on case, Linux will not accept your username, password, or any command unless you have the proper case. If everything goes well, your putty window should display a dollar sign ($) prompt. At this prompt, you type commands. We will review a number of the more important commands in this lab.

Another program that you need to use is a file transfer program. File Transfer programs move files to and from remote computers and your personal workstations. They do not allow for individual command execution like telnet or ssh. Like the remote terminal programs just discussed, there are secure and insecure versions. The insecure version is called ftp which stands for File Transfer Protocol. Ftp has been disabled on the cs machine for the same reason that telnet was disabled; it is an inherently insecure program. It suffers from the problem that passwords and data can be intercepted by eavesdroppers.

The secure version of a file transfer program is scp which stands for secure copy. Like ftp, scp is a way to copy files from one remote system to another. Just as with ssh, all data is encrypted so a third party can’t eavesdrop and intercept the contents of the file. scp is not support by Microsoft so you’ll need to load a third party program. A free graphical scp program you can download is WinSCP. If your machine doesn’t already have an scp program, download WinSCP from http://winscp.net/.

These programs are useful when you want to transfer files from one computer to another over the Internet. For example, you might develop files on your home computer and want to upload them to cs.


Step 3: Learn Common Linux Commands

If you haven’t already done so, change your pre-assigned password.  Your username is your last name; your initial password is your 7 digit student id (including leading zeros). You may be required to change it on initial login.  If not, use the passwd command and follow the prompts:

$ passwd

If you need help with a command, Linux provides an excellent help system. Manual pages on UNIX commands are available. Simply enter man followed by the name of the command on which you want help. Try the following:

$ man passwd

Important man keystrokes include space to skip to next page and q for quit.

UNIX has a hierarchical file structure where you may change directories, copy files, delete files, etc. In Unix, the files are organized into a tree structure with a root named by the character ‘/’. There are four types of files in the file system:

  1. an ordinary file contains a program or data
  2. a directory contains name and address information of the files in the directory
  3. a device file acts as a gateway between physical devices by representing the device (e.g. printer, speaker) as a file
  4. link files are pointers to other files.

As a normal Linux user, you will be primarily concerned with ordinary files and directories.

Every Java assignment and project should be created in its own directory. You must first make a new directory (do this only once!!!), then change your default directory to this directory. The commands to do this are:

$ mkdir assignment1     // Make Directory Command -- you do this once!!!
$ cd assignment1        // This is the actual Change Directory command

If you ever need to return to your home directory, use these commands:

$ cd ..                 // Go up to the parent directory
$ cd ~                  // Go directly to your home directory

To view the contents of a directory, use either the dir, ls, or ls -la commands. Go to your home directory and give these commands a try.

Some other useful commands you should experiment with:

  • mv file1 file2 – Rename file1 to file2
  • cp file1 file2 – Copy file1 to file2
  • rm file – Delete (remove) a file
  • rmdir dirname – Delete directory named “dirname”
  • more filename – View filename page by page
  • less filename – View filename, more powerful than more
  • diff file1 file2 – Find differences between file1 and file2
  • javac filename – Compile file filename using the JAVA compiler
  • java filename – Execute the JAVA-compiled program filename
  • nano filename – Edit filename with the nano editor
  • emacs filename – Edit filename with the EMACS editor
  • lpr filename – Prints a text file to the default printer
  • script – Begin saving what goes to the screen
  • exit – End a script or log out of a terminal window
  • pwd – Prints the Working Default Directory
  • cat – View Files

For a more complete listing of linux commands, check out a PDF of THE ONE PAGE LINUX MANUAL.

Try the following sequence of commands to familiarize yourself with the Linux file system:

$ cd ~                             # change to home directory
$ cp /home/silvestri/alice alice   # copy a file from silvestri's directory to your directory
$ cat alice                        # File will scroll by very fast
$ more alice                       # File will be displayed again, press spacebar for the next page
$ rm alice                         # Delete the file
$ cd assignment1                   # make the directory created above the default directory

Be very careful when using the “rm” command! After a file has been deleted, it cannot be recovered! Consequently, you should make sure that you don’t want the files you are deleting anymore when you remove them.


Step 4: Configuring Linux to Host Your Website

You need to follow this procedure only once!:

  1. Every website needs to be created in a subdirectory called public_html. You must first make a new directory, then change your default directory to this directory. The commands to do this are:
$ cd                    // Change to your home directory
$ mkdir public_html     // Make a directory called public_html
  1. You now need to set the proper permissions for your public_html and home directories. Once set, your address will show up on the internet as http://cs.stcc.edu/~username where “username” is your login name. Follow the directions listed below to do this:

Make sure your home directory is executable by others. To accomplish this, type the following command:

$ chmod 711 ../username

where “username” is your login name. NOTE: Others will still not be able to see or browse information in your personal directory on the system

Make sure you set the permissions on the public_html directory using the following command:

$ cd
$ chcon -R -t httpd_sys_content_t public_html
  1. Anything you create in this “public_html” directory will be visible to the world under the URL mentioned above. You MUST also make an “index.html” file in this directory as the main, default web page.  In the next step, you will create an index.html that will greet a visitor to your site using nano.

This is all you need to do to configure Linux to host your website. Remember you only need to do this once.


Step 5: Learn nano

You need to become familiar with an editor. nano is a simple full screen editor similar to notepad in windows. Nano is not a word processor; it resembles one, in that it lets you type in and modify text.

Editing commands are displayed at the bottom of the screen and are invoked using control-key combinations. In the display, the ^ character is used to represent the Ctrl key. You make a choice by holding down the Ctrl key and pressing a letter key. For example, ^G means you hold down the Ctrl key and press the G key. Some commands prompt you for information. These prompts will be displayed at the bottom of your editing window, just above the command labels.

Starting Nano:

To start nano, enter the follow command at the Linux prompt:

$ nano filename

replacing filename with the name of the file you want to create or edit. For example, to create a file and name it letter.txt, type

$ nano letter.txt

If the file already exits, Nano opens it for you to edit. If it doesn’t exist yet, nano creates it and places you in an editing screen. If you start nano without giving a filename, you must provide one when you exit the program.

Lines that continue beyond the edge of the display are indicated by a $ character at the end of the line. Long lines are scrolled horizontally as the cursor moves through them. Nano displays a menu bar of commonly-used commands at the bottom of the screen. Nano accepts commands from your keyboard but not from your mouse.

To insert text into your Nano editing screen at the cursor, just begin typing. Nano inserts the text to the left of the cursor, moving any existing text along to the right. Each time the cursor reaches the end of a line, Nano’s word wrap feature automatically moves it to the beginning of the next line.

Common Editor Tasks:

To move the cursor, use the arrow keys or use ^f (forward), ^b (back), ^n (next line), ^p (previous line).

To delete the character to the left of the cursor, press BACKSPACE, DELETE, or ^h.

To delete the character highlighted by the cursor, press ^d. To delete the current line, press ^k.

The command ^K (Cut Text) will delete the entire line that the cursor is currently on. You can then move the cursor to another position and use ^U (Uncut Text) to insert the previously deleted line of text at the current position. If a group of lines is deleted successively using the ^K (Cut Text) repeatedly with no other commands in between, they can be pasted back into the text at the current cursor position, using ^U (Uncut Text).

Searches:

To see what line number you are on, use ^C (Current Position). To search for a word or partial word, use ^W (Where is) and you will be asked to supply the search string. String searches are not case-sensitive. A search begins at the current cursor position and wraps around the end of the text.

File Browsing:

The file browser is offered as an option in the ^R (Read File) and ^O (Write Out) command prompts. The option is labeled ^T (to Files). It is intended to help in searching for specific files and navigating your directories. The browser displays file names with sizes and directory names. The browser always starts with your home directory and not with your current working directory. The current directory is displayed on the top line of the display while the list of available commands is displayed at the bottom of your screen. Note that these commands do not need to use the Ctrl key. Several basic file manipulation functions are supported: file renaming, copying, and deletion.

Saving Your Work:

To save your changes part way through your editing session, use the command ^O (WriteOut) and a message similar to the following will be displayed near the bottom of your screen:

File Name to write : letter.txt

Press Return to save your changes. You will be left inside the editor. At this point you can exit your editing session or continue with more changes.

Exiting Nano:

To exit nano, use the command ^X (Exit). If you have not made changes to the file or if you have already saved your changes, you will be returned to your Unix prompt. If changes have been made but not saved, you will be prompted with the following:

Save modified buffer (ANSWERING “No” WILL DESTROY CHANGES) (y/n)?

If you respond with y the name of the file you are editing will be displayed. For the above example, you will see the following:

File Name to write : letter.txt

Press Return and then you will have completed your editing session and be returned to your Unix prompt.

If you wish to change the name of the file, when the current name is displayed you can supply a new name by typing over the given name. If you give the name of an existing file you will warned:

File “letter.txt” exists, OVERWRITE? [n] :

If you get disconnected

If you are disconnected while running nano, your current work may be saved before exiting. The work will be saved in the current filename with .save appended. If you have not yet named the file you were editing, it will be saved with the name nano.save.

Getting Help

More specific help is available in nano’s on-line help which is provided by context sensitive help screens. The command ^G (Get Help) is used to invoke the help system. A Unix manual page for nano is also available by typing man nano at your Unix prompt.

Create an index.html page

  1. Change your working directory to public_html
  2. Start nano and enter the follow html code and ultimately create an index.html file:
    <html>
      <head>
        <title>[Enter Your Name}'s CSC-112 Intermediate Java Programming Website</title>
      </head>
      <body>
        <h1>Welcome to [Enter Your Name}'s CSC-112 Intermediate Java Programming Website</h1>
        <p>Here is where I will post my homework assignments</p>
      </body>
    </html>
  3. If you are successful, use your browser and navigate to: http://cs.stcc.edu/~username to view the page.

Step 6: Editing and Compiling your first Java Program

Be sure you are in your private assignment directory. There you’ll edit your first Java program on the linux box. What follows is a short Java application that will be used to demonstrate the edit and compile sequence in Linux. An Java application is similar to console or command-line programs you may have written in your previous programming work. This program will be called Hello1.java.

// Hello1.java
// A first program in Java
// (More Information needs to be entered in this global documentation section).

public class Hello1 { 
   public static void main( String args[] )
   {
      System.out.println( "Welcome to Java Programming!" );
   }
}

Enter the code using nano. To invoke nano, type the following:

$ nano Hello1.java

Remember that nano does not respond to mouse input only keyboard commands. The hardest part of learning any operating system is learning its editors. Take your time and get accustomed to the control keys and their functions. The nano screen should offer enough help to get you through the editing process.

Once you are done typing the program, save the file and exit nano. To view the contents of a file, use the cat <filename> command. Try out this command and see if Hello1.java exists and contains the proper information.

Once you save Hello1.java, you need to compile it. This process requires the javac compiler. Type the following:

$ javac Hello1.java

If the compiler complains about syntax errors, you must go back to step 5 and edit the problem code. After changing the code, a recompile must be performed with step 6. If no errors result, you will find a file called Hello1.class in your working directory. This is the typical sequence of events involved in coding a program. To execute the program, type the following command:

$ java Hello1

This instructs the java virtual machine (JVM) to interpret the byte codes found in Hello1.class. If the output of your executable file is in error, you have a logic error or run time error that needs to be corrected. You must look at your code and determine the error in your logic. In essence, you must go back to step 5 to edit your source code. This is the program development cycle you will follow throughout this semester and in your career as a programmer.


Step 7: (Optional) The Linux Printer

There are NO printers attached to cs.stcc.edu so NOTHING will print and errors will present themselves!!!!

To submit your Linux homework, it will be helpful to make a “recording” of your program’s output. While this is not required for all assignments, I would appreciate receiving the output as it helps speed along the grading process!

Linux contains a command that allows you to create one file containing both the source code and the execution of your program. This command is script. The script command operates similarly to the record command on a VCR. When you record, the broadcast is captured on tape until the recording is terminated. When you issue the script command, everything that is displayed on your Linux screen is captured in a file called typescript until you terminate the recording using the exit command. Once you exit, you can review your recording (the file called typescript) on the monitor and send it to the printer.

The steps to follow to produce a homework submission file:

  1. Make sure everything works fine before executing the script command. If you are turning in a program, make sure the program runs. If you are turning in a text file you created, make sure the file is created first.
  2. Once everything is working and ready to be turned in, type script to begin creating the typescript file.
  3. Display the files you created. For example, enter cat Hello1.java to display the contents of the java program and save it in the typescript file. It will scroll quickly but it is all being captured in the typescript file.
  4. Compile and run any programs you created. Once again, all the commands and the output are being recorded in the file.
  5. When finished, type exit . This stops logging to the typescript file. If you execute the ls command, it will now show that there is a new file named typescript created in the directory.
  6. Type more typescript to view your file to make sure it is okay. If you backspaced, those characters might not display properly.
  7. If contents of typescript is not good, you’ll need to delete typescript and start over again to create it.

At this point, you now have a typescript file that’s to your liking. You’ll need to make a hardcopy of this file. The command to print a file is:

$ lpr <filename>

In this case substitute typescript for <filename>. Please make sure you only print source code and text. Do not print executable files!!! You’ll now they are executable when garbage is displayed when viewing them on the screen. You should probably also run an ls -la <filename> command before you do the lpr. This command displays the file’s size; if the file size is a large number >20,000 bytes, you’re probably attempting to print a bad script output that was not properly terminated with the exit command.

Don’t print large files. They end up jamming the printer, wasting paper and time.

It is worth noting that entering the lpr command from Linux will always print on the laser printer located in the CS lab. This means that if you are logged in from somewhere else, for example, from home via modem, then if you enter the lpr command your output will print in the lab, not on your printer at home.


Step 8: Learn to use Linux’s Email Capabilities

Every user on our Linux box has an email account. People can send you email using an address similar to username@cs.stcc.edu (where username is your normal login account name). For instance my internet email address on cs is silvestri@cs.stcc.edu. To send email to a local user (someone who has an account on cs), it is not necessary to include the @cs.stcc.edu.

Use the mail command to send or receive email. Use the command man mail to learn how to send mail from the command line. If the mail command is too complicated, you might want to try the mutt program which is an alternate mail client.

Using the mail command will give you a deep appreciation for the graphical programs you take for granted.  It’s quite cryptic! For instance, if you want to send mail to me, you’ll enter:

$ mail -s "Test Email" silvestri@stcc.edu

The cursor will go to the next line where you enter a plain text message body.  The finish the mail you enter a single period as the first character on it’s own line.

You may already have an email account that you use and don’t wish to use your new Linux’s email system. You can configure your account to forward all emails sent to your cs account to your other email address. You will need to create a .forward file in your home directory. (It’s a period followed by the word forward with no intervening spaces.) Create the file using the nano editor. Enter the email address of where emails should be sent on the first line. Make sure you press Enter at the end of the line. Once you are done entering this one line email address, save the file and exit nano.

Use the cat .forward command to see if .forward exists and contains the proper information. Make sure the .forward file has the proper permissions by executing the following command:

$ cd
$ chmod 644 .forward
$ restorecon -v .forward

Step 9: Logout

Make sure you always exit the system by typing the following command:

$ logout

If you leave without logging out, your files and account will be susceptible to individuals with too much time on their hands. Such individuals delete files, send obscene emails (with your name on them), and generally do nasty things to people. Be forewarned!!!


Step 10: Configuring WinSCP

You will be developing your web pages on your home/lab PCs. Once these pages are in state where they can be viewed by the world, you will need to sftp (secure file transfer protocol) them to your public_html directory. Make sure all the files you intend to publish on your web site are in that directory. Otherwise, you will not be publishing anything.

Make sure you have a copy of WinSCP on your machine. Like ftp, scp is a way to copy files from one remote system to another. Just as with ssh, all data is encrypted so a third party can’t eavesdrop and intercept the contents of the file. If your machine doesn’t already have an scp program, download WinSCP from http://winscp.net/.

Configure WinSCP with the hostname cs.stcc.edu, your username and password. Launch the program and you should see two panes: one that represents the remote cs machine, and one that lists your local files. Transferring files is a simple matter of dragging and dropping files from the local and remote panes.

Take some time to get accustomed with WinSCP and its configuration.


Step 11: Creating files to upload

Using Eclipse, you will now create two files that will ultimately be uploaded to your website.

Let’s create a simple JavaFX program. JavaFX is the latest technology used to create graphics programs.  Type the following into  a new Eclipse project:

If you encounter errors that indicate classes are not being found, do this to fix it:

  1. Right click on the project and choose Properties
  2. Click Java Build Path, then double click JRE System Library. An Edit Library popup box should appear.
  3. Choose Workspace default JRE, then click Finish
  4. Click Apply, then OK and you should be good to go.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class ShowCircleCentered extends Application {

    public void start(Stage primaryStage) {
        // Create a pane to hold the circle
        Pane pane = new Pane();

        // Create a circle and set its properties
        Circle circle = new Circle();
        circle.centerXProperty().bind(pane.widthProperty().divide(2));
        circle.centerYProperty().bind(pane.heightProperty().divide(2));
        circle.setRadius(50);
        circle.setStroke(Color.BLACK);
        circle.setFill(Color.RED);
        pane.getChildren().add(circle); // Add circle to the pane

        // Create a scene and place it in the stage
        Scene scene = new Scene(pane, 200, 200);
        primaryStage.setTitle("ShowCircleCentered"); // Set the stage title
        primaryStage.setScene(scene); // Place the scene in the stage
        primaryStage.show(); // Display the stage
    }

    /**
     * The main method is only needed for the IDE with limited JavaFX support.
     * Not needed for running from the command line.
     */
    public static void main(String[] args) {
        launch(args);
    }
}

Provided you entered the code properly, you should see a beautiful red circle centered in a window. If you don’t, check your code.  You cannot proceed until a beautiful red circle is displayed in eclipse!

If you see the beautiful red circle, it’s time to share it.  It’s not enough for you to see this beautiful red circle, you want to show the world this beautiful red circle.  Here’s where the web server you configured comes into play.  You’re going to upload your creation to the web server! To do this you need to create a Runnable JAR file.  Here is how to do that:

  1. Right click on the project and choose Export, a popup box appears.
  2. Choose Java, and then Runnable JAR file, click Next. Another popup appears.
  3. Make sure the Launch configuration is your Circle Project.  If not, choose it in the drop down. (It’s usually the very last item in the drop down.)
  4. Browse to a directory where you’d like to store this Runnable JAR File in the Export Destination section. Give the jar file a proper name, I called mine RedCircle.jar and put it on desktop.
  5. Choose Library Handling to be the Extract required … option.
  6. Click Finish.

You should now now have a jar file stored on your machine.  Navigate to that jar file, double click it, and you’ll see the red circle!  If you don’t, go back to the beginning and make sure you completed all the steps properly.


Step 12: Transfer files to your public_html directory

Again, make sure all the files you intend to publish on your web site are in that directory. Otherwise, you will not be publishing anything.

Open WinSCP, log into your account, and go into the public_html directory.  Create a folder there called RedCircle.  Upload the runnable jar file into the RedCircle folder.  Remember, never upload source code anywhere in the public_html directory as it can be copied be some unscrupulous internet troll.

Source code .java files will be submitted via http://pastebin.com/.

Modify your index.html file located in the public_html folder so it includes a link to the runnable jar. Here is what the html code do to this:

<!DOCTYPE html>
<html lang="en">

<head>
<title>Tony Silvestri CSC-112 Course Website</title>
<meta charset="utf-8" />
</head>

<body>
<p>Hi! My name is Tony Silvestri. Welcome to My Website. </p>
<p>Contact me at: <a href="mailto:silvestri@stcc.edu">silvestri@stcc.edu</a></p>
<p>Here are my applications:</p>
<ul>
<li><a href="RedCircle/RedCircle.jar">Beautiful Red Circle</a></li>
</ul>
<p><a href="https://cs.stcc.edu/spring_2017_csc-112_student_websites/">CSC-112 Student Websites</a></p>

</body>

</html>

Substitute your name above.


Lab Requirements

Perform the following tasks to earn a passing grade on this lab:

  1. Add a .forward file to your home directory.
  2. Perform Step 6 to produce the Hello1 program. Make sure you have the following information typed into the header of your program source code:
  1. Your name
  2. Date
  3. Course Name and Number
  4. Problem Number
  5. Short Description of the Problem
  6. The email address where you can be reached.
  1. Send me an email with a subject stating that you have read the Authorized Computer Usage Policy and understand the ramifications if you do not follow the rules.   In this same email, include a link to the Hello1.java program. Place a copy of it in the public_html directory and include a link to it in your email. I’ll click the link and verify everything is fine.  Do this through the mail command on linux.  Not in windows.
  2. Create your own the runnable RedCircle jar file.
  3. Upload this file and make an index page with a link to it.  View the html code located at http://cs.stcc.edu/~silvestri/ as a sample to see how this is done.