• May 15, 2020



“>”:将内容输入到之后的文件中;exit:退出命令行系统。 涉及知识点:字符处理、文件系统、JAVA更多可加微信讨论微信号:yzr5211234pdf

CS 131: Operating Systems Programming Assignment 1, Part 1Released: Monday, September 16th 2019Highly Encouraged Project Tutorial: Tuesday, September 17th 2019, 7pm, Gerstenzang 123Due (hard deadline): Tuesday, September 24th (on Latte)Getting StartedYour assignment is going to be to build a basic command line environment for interactingwith a file system. This command line environment (or shell) will be written in Java. The firstpart of this assignment is designed to refresh your coding ability in Java, and ensure that youhave the coding pre-requisites to be able to complete this course. You will do this while learningabout Unix and practicing your Java-based System calls.Common shellEssential to this assignment is understanding the fundamentals of a UNIX shell, and thefunctionality that is expected from a UNIX like operating system. The following pages can helpyou get a sufficient understanding of the expected behavior of UNIX to allow you to completethis project. After reading through these resources, it is highly recommended that you playaround on a UNIX console before you attempt to construct your own:Theoretical http://www.ee.surrey.ac.uk/Teaching/Unix/unixintro.htmlls, cd, . , .. , pwd http://www.ee.surrey.ac.uk/Teaching/Unix/unix1.htmlcat, grep, wc, uniq http://www.ee.surrey.ac.uk/Teaching/Unix/unix2.htmlRedirection, Piping,> |http://www.ee.surrey.ac.uk/Teaching/Unix/unix3.htmlREPL LoopYour main program will include a loop that prints a simple prompt (“> ”), accepts acommand (or multiple commands separated by pipes), and prints the output from that command(if any). This type of loop is sometimes called a read-eval-print loop, or REPL. The REPL loopshould only exit upon user request. For example:> Welcome to the Unix-ish command line.> cat hello-world.txthelloworld!> not-a-commandThe command [not-a-command] was not recognized.> cat hello-world.txt | grep worldworld!> cat hello-world.txt | grep world > output.txt> cat output.txtworld!> lssrchello-world.txtoutput.txt> exitThank you for using the Unix-ish command line. Goodbye!Your REPL must read user commands from System.in. There are two critical functionswithin this loop. (1) Correctly parsing commands in a way that allows the creation of pipedfilters. Using Scanner and String.split will help you with this task. (2) Each functionidentifies and reports different errors as follows.> not-a-commandThe command [not-a-command] was not recognized.> catThe command [cat] is missing an argument.> cat file.txt | grepThe command [grep] is missing an argument.> grep world | cat hello.txtThe command [grep world] requires input.> wc | cat hello.txtThe command [wc] requires input.> cat nonExistantFile.txtAt least one of the files in the command [catnonExistantFile.txt] was not found.> cd not-a-directoryThe directory specified by the command [cdnot-a-directory] was not found.Your REPL loop must support simple directory commands: ls, cd, and pwd. cd is the onlycommand you will implement that does not use String queues, because it does not take pipedinput and does not produce output. You may handle this case without inheriting from theSequentialFilterclass (see REPL classes defined below). ls and pwd do create piped output,even though they don’t need piped input (the same is true for cat).The directory from which you start the command line program should be initialized as thecurrent working directory that your Java program is initialized to. The working directory can bemodified with the cd command. You use the command ls to list the contents of the currentworking directory. This will be a little more challenging than you might think because you arenot allowed to modify the invoking environment’s working directory. You’ll need to manage aseparate working directory for your shell. This can be as simple as maintaining a String thatkeeps track of your present working directory.Filter CommandsAll commands that you have to implement within this half of the programmingassignment must implement the abstract SequentialFilter.java class. The sequential filter is aconvenient abstraction: it reads from an input queue (linked list), and writes to an output queue,by calling a method called process(). The queue that it writes to is the input queue for thenext filter (if there is a next filter). Shown below is the abstract class SequentialFilter,which should greatly help you along in this project. SequentialFilter inherits fromFilter, a class that is not displayed here, but is given along with this assignment.On the next page of the assignment, there is a table detailing the commands you areresponsible for implementing. A proper implementation of each should refer back to the correcterror messages to print, and the behavior expected of each in a Unix-like system.package cs131.pa1.filter.sequential;import java.util.LinkedList;import java.util.Queue;import cs131.pa1.filter.Filter;public abstract class SequentialFilter extends Filter {protected Queue input;protected Queue output;public void setPrevFilter(Filter prevFilter) {prevFilter.setNextFilter(this);}public void setNextFilter(Filter nextFilter) {if (nextFilter instanceof SequentialFilter){SequentialFilter sequentialNext =(SequentialFilter) nextFilter;this.next = sequentialNext;sequentialNext.prev = this;if (this.output == null){this.output = new LinkedList();}sequentialNext.input = this.output;} else {throw new RuntimeException(“Should notattempt to link dissimilar filter types.”);}}public void process(){while (!input.isEmpty()){String line = input.poll();String processedLine = processLine(line);if (processedLine != null){output.add(processedLine);}}}public boolean isDone() { return input.size() == 0; }protected abstract String processLine(String line);}Note that in implementing the filters, some of them can be simple, five or six line classeswho solely implement the processLine(String) method. (Examples of this include grep,> and the default filter to print to the command line, and uniq). Some other filters (cat, ls, pwd)will need to override the process() method, as they don’t need to use theprocessLine(String) method to process any piped input. These classes and others mayalso need to override the isDone() method…No YesPipes the workingdirectory to theoutput messagequeueYou may want to use the Java File class(also see the slide about the File class inthe slides from the first tutorial). Youcan also use System calls to achievethis.No YesPipes the contents ofthe current workingdirectory to theoutput messagequeueYou do not need to allow arguments tols, that is, ls can just always output thecontents of the current workingdirectory. You do not need to include”.” or “..” in the list. You also do notneed to mark directories with anyspecial characters.No NoChange to anotherdirectory relative tothe current directoryMake sure you can accept the specialdirectories “.” (the current directory)and “..” (one directory up in thedirectory hierarchy). You do not needto support absolute paths. You do notNo YesOutput the entirety ofone or more files tothe output messagequeueUnlike in UNIX, cat does not acceptpiped input. I.e. for your program, catwill always be first in a string ofcommands separated by pipes. The catcommand in a proper UNIX shell hassignificantly more functionality than theversion we require you to implement,you need only implement the outputcapability.Yes YesRead lines frompiped input, and onlyoutput lines with agiven search stringYou do not need to do regularexpression matching. You should do asimple case-sensitive string search, andcount any line containing that searchstring as a match. You can assume thatthis argument (as well as all file names)will never contain >, or |.Yes YesRead lines frompiped input andoutput the number oflines, words andcharacters, separatedwith spaceNote that this command heavily relieson figuring out when it is going to stopgetting more input lines to count.Consider the possibility that there areno lines returned. Make sure that youutilize the isDone()method of thisfilter and the previous filter.Yes Yes Filters out duplicatelines from the inputOnly permits lines of input to passthrough if they have not been detectedbefore (the Collections framework canbe useful here).Yes NoReads piped input,and writes it to a filespecified after the >symbolMake sure to utilize the java File classfor this operation. If a file exists withthe name given by the command, itshould be overwritten by a new filecreated in its place.Wrap It Up: What Do You Have And What You Need To DoThe project is intended to be developed and run on Eclipse (a Java IDE).You will be provided the following files:SequentialREPL.java:Your REPL implementation should reside in this file, and should begin when themain(String[])method is called. It should take its input from System.in (using ascanner is suggested).Filter.java:An abstract class extended by the SequentialFilter class. You should not modify thisclass.SequentialFilter.java:An abstract class extending the Filter class. To implement the commands mentioned above,you need to extend this class. You should not modify this class. A successful implementationof this project will demand a rigorous understanding of what this class is doing.Understand it before writing any code.SequentialCommandBuilder.java:The SequentialCommandBuilder manages the parsing and execution of a command. Itsplits the raw input into separated subcommands, creates subcommand filters, and links theminto a list. We have provided you with some suggested method declarations (a good way to breakdown the task), but you can feel free to approach this code as you see fit.AllSequentialTests.java, RedirectionTests.java, REPLTests.java,TextProcessingTests.java, WorkingDirectoryTests.java:These files contain multiple tests that examine your implementation of the various commands.You should not modify these classes (besides for debugging purposes). Note that a failure ofany of these tests will certainly lead to deducted points. All perfect assignments will pass alltests, but passing the tests does not guarantee a perfect score (Implication).Testing and GradingSuccessful completion of this project is nearly impossible withoutappropriately testing against the provided JUnit Tests. If you cannot run the testswhen you import your project, please see a TA at office hours as soon as possible.Importing and exporting properly is crucial to allow us to grade yourprojects properly. Please import and export based on the instructions in the tutorialslides and on LATTE, and submit the zip file that you exported from Eclipse. If youfail to export your project properly, you may be penalized.To allow us to test without changing your code, please name the class whichhouses your main method SequentialREPL.java, this will be called when the test suite isrun. Because we will be using unit tests that will compare your output (System.out)character for character against our samples, please make sure that your error messages areexactly the same as the ones given, and that there are no intentional or unintentionaldiscrepancies (whitespaces, prompt, wording) between your result and the examplesprovided. Tests will fail if these discrepancies exist, and a good first place to check atest failure is the exact strings being compared.There is a helpful Boolean variable called “DEBUGGING_MODE” (In the TestSuite), which when set to true will not clean up after the created files and directories afterunit tests are run. This can allow you to see the error in your output (files stored in thecurrent working directory), and potentially understand any disconnect between ourexpectations and your code. Feel free to play around with the tests (modify them as ishelpful for your debugging, etc.), but know that you will be graded against the set oftests that we sent out originally. Any attempt to tamper with the tests will be considereda breach of academic integrity, and will result in point penalties and potentially furtherdiscipline.Note on differences between Unit Tests and Integration TestsPlease note that though JUnit is being used to run this suite of tests, these are notunit tests, but integration tests. Do not take this test design as an appropriate way to testthe code that you are writing. Unit tests test specific functions and small, incrementalpieces of code. These tests are predicated on the entirety of your code being complete, andthis assumption breaks most of the conventions of unit test writing.Note on Platform IndependencyWindows and Unix based operating systems differ on whether to use the “\” or “/”as their preferred file separator. In order to ensure your code will run in either case it isnecessary to request this information at runtime, we have already included the necessarycommand in the starting code. cs131.pa1.Filter contains a static fieldFILE_SEPARATOR that will be set to this value for you to easily reference. Using ahardcoded “/” or “\” in your code instead of Filter.FILE_SEPARATOR to handlechanging directories may result in a loss of points.However, if your code is not platform independent when you submit it, do not fret; we will doour best to run your code on both a Windows and a Mac machine. This part of theassignment is not critical to the learning goal, and will be worth less than five points ofyour final grade. If you want to make sure your code works on both machines, dual bootcomputers are available in the library to allow you to try your code in the otherenvironment.Note on MessagesIn order for the test cases to properly evaluate your code, everyone must use theexact same messages for when your REPL loop starts, ends, reports an error, or requestsa new command. We’ve included the expected messages in an enum for you to use tohelp with consistency. The enum cs131.pa1.filter.Message contains 11messages that you will need to use throughout your project to report information to theuser. Note that the 8 error messages contain a placeholder where the invalid commandshould be placed. Calling the function with_parameter(String parameter)for these 8 messages will replace the placeholder %s with parameter i.e. callingMessage.REQUIRES_INPUT(“grep foobar”) will generate the String “Thecommand [grep foobar] requires input.” which is expected by the test cases.A Note on the FutureIn this half of the assignment, you will be building a lot of code, but everythingthat is mentioned should be complete-able if you have taken COSI 12b (focusing oninheritance and file processing), and COSI 21a (Focusing on data structures and codedesign). Right now, all of this activity is Sequential (so in the command “cat hello.txt |grep foo | uniq | wc”, each filter is run in order, and terminates before the next one begins).In the next part of the assignment, you will use the skills that you will learn in this courseto begin using concurrent stream processing, where each filter runs when it can, and thetasks of each filter are processed simultaneously (by multiple cores), or simplyconcurrently by one core.