Starting from:
$35

$29

Homework #8: Stock Market (Phase 1) Solution


Submission Instructions

This homework assignment must be turned-in electronically via Canvas CODE plug-in. Ensure your C++ source code is named MUID_homework8.cpp, where MUID is your Miami University Unique ID (e.g., raodm_homework8.cpp). Ensure your program compiles without any warnings or style violations. Ensure you thoroughly test operations of your program as indicated. Once you have tested your implementation, upload the following onto Canvas:

1.    The 1 C++ source file developed for this homework.

General Note: Upload each file associated with homework individually to Canvas. Do not upload archive file formats such as zip/tar/gz/7zip/rar etc.



Objective

The objective of this homework is to develop a custom “stock market” web-server to:

    • Understand the use of multiple detached threads.

    • Understand the use of critical sections created using a std::mutex and std::lock_guard.

    • Understand the use of synchronization constructs with object-oriented design

    • Continue to gain experience with HTTP protocol and working with sockets.

    • Demonstrate expertise with straightforward string processing.

    • Continue to gain familiarity with automated functional testing.

    • Using shared variables with a namespace.

Grading Rubric:


The program submitted for this homework must pass necessary base case test(s) in order to qualify for earning any score at all. Programs that do not meet base case requirements will be assigned zero score!

Program that do not compile, have a method longer than 25 lines, or just some skeleton code will be assigned zero score.


    • Base case [8 points]: Correctly process transactions (as described below) by implementing clientThread method.


Page 1 of 6
Due before:    Deadline posted on canvas


    • Extra function [8 points]: Avoid race conditions in buy, sell, and status operations using std::lock_guard and mutex associated with each stock

    • 4 points: Reserved overall structure, organization, Javadoc-style documentation, variable-names, etc.

    • -1 Points: for each warning generated by the compiler (warnings are most likely sources of errors in C++ programs)


NOTE: Violating CSE programming style guidelines is a compiler error! Your program should not have any style violations.

Starter code

A short starter code is supplied in homework8.cpp to get you started. The supplied main.cpp has code to help with testing and running the program as a multithreaded web-server. You are also supplied with a Stock.h file (do not modify it) to encapsulate information pertaining to a stock. So, you may reuse code from previous homework and exercises as you see fit.

For testing, a custom client is supplied in stock_client.cpp along with input text files.

You should not be modifying the stock_client.cpp or the supplied input text files. You should not add stock_client.cpp to your NetBeans project. You are expected to separately compile and run this stock_client.cpp program for testing as shown further below.


Despite all the testing, it still takes a human to review a program to decide if a program is correctly multithreaded. Hence, the even if your program passes all the tests in the CODE plug-in it could still be incorrectly multithreaded. Consequently, double-check your solution to ensure you are correctly multithreading your program in order to earn full points for this homework.

Responses

The responses from your server should be in the following standard HTTP format, with each HTTP header lines only terminated with a "\r\n". The message at the end of the headers does not have any newline characters.


HTTP/1.1 200 OK

Server: StockServer

Content-Length: 36
Connection: Close

Content-Type: text/plain

Stock msft created with balance = 10

Note: The Content-Length corresponds to the length of the message in the HTTP response. The message should not have any newline characters in it. If needed, see homework #1 on how to create a response message easily.






Page 2 of 6
Due before:    Deadline posted on canvas


Requirements

In this homework, you are expected to develop a simple multithreaded stock market web-server that operates using standard HTTP requests and responses. The stock market consists of a collection of stocks stored as an unordered_map, with the stock’s name as the key. You are supplied with a Stock.h file that contains the definition for a Stock class. Each stock is identified by a unique name (a std::string). Each stock has a balance field that indicates number of available stocks.

Your stock market web-server is expected operate as follows:

    1. The server should be developed by implementing the supplied clientThread method (see starter code) as the top-level method. You may add helper methods as you see fit.

    2. Each request will be a standard HTTP GET request in the form (with each line terminated with a "\r\n"):

General structure
Eample request(s)

GET /TransactionInfo HTTP/1.1\r\n
GET /trans=buy&stock=0x1&amount=5 HTTP/1.1\r\n

Host: localhost:4000\r\n
Host: localhost:4000\r\n

Connection: close\r\n
Connection: close\r\n

// More headers may be here\r\n
// More headers not shown\r\n

// They are not shown\r\n
\r\n

// For brevity\r\n



GET /trans=status&stock=msft HTTP/1.1\r\n

\r\n
Host: localhost:4000\r\n


Connection: close\r\n


// More headers not shown\r\n


\r\n




Where, TransactionInfo is a HTTP-query string in the form:

"trans=cmd&stock=StockName&amount=amt". The cmd indicates type of operation to perform. The stock and amount information are optional. The expected operation and responses (or outputs) for each command is shown below.

Note: The commands below assume that stock name is 0x01. However, the name can be different/vary. So do not hardcode stock name to 0x01.


TransactionInfo (all

Description of required operation


Expected msg from


on 1 line)





server in HTTP response


A request that is not

Browsers may make additional requests


Invalid request


one of the 4 below

(e.g., for facicon.ico). You should







handle those correctly.





trans=reset
Clear out all stocks.

Stocks reset



Note: Stock resetting requests will be







performed in single-threaded mode only.





trans=create&stock

Add stock (to unordered_map) with


Stock 0x01 created


=0x01&amount=10

optional
balance=amount (default is 0)


with balance = 10 or

















Stock 0x01 already




if stock with same name does not exist.










exists




Note: Stock creation requests will be















performed in single-threaded mode only







by stock_client.cpp.

















Page 3 of 6




Due before:    Deadline posted on canvas



trans=buy&stock=0x

Subtract specified amount from stock’s
Stock 0x01’s balance

01&amount=5

balance, if stock exists. If stock does
updated or









not exist, generate error.






Stock not found








trans=sell&stock=0

Add specified amount to stock’s

Stock 0x01’s balance


x01&amount=20

balance, if stock exists. Otherwise

updated or




generate error.

Stock not found









trans=status&stock

Return stock’s balance, if stock exists.
Balance for stock

=0x01

Otherwise generate error.
0x01 = 24




Stock not found








Note: The message "Stock not found" is returned if the specified stock name does not exist (in the unordered_map stockMap). The response is always in the format shown earlier but the specific message in the response will vary as shown above.

Important Notes & Implementation Tips:

    • The starter code already does multithreading using detached threads for you.

    • Processing HTTP requests in the clientThread method is more-or-less just a repeat from prior projects/exercises.

    • Don’t forget to read (and ignore) request headers from the client. Otherwise, your server will not operate correctly with the web-browser or any standard web-clients.

    • You will need to URL decode the request prior to processing it.

    • Extracting the values from the request is relatively straightforward as suggested in the
example code fragment below:


std::string request = "trans=sell&stock=0x01&amount=20"; request = url_decode(request);
    • Replace '&' and '=' characters in the request to make it

    • easier to parse out the data. std::replace(request.begin(), request.end(), '&', ' '); std::replace(request.begin(), request.end(), '=', ' ');

    • Create a string input stream to read words out.
std::string trans, stock;
unsigned int amount = 0;

std::istringstream(request) >> dummy >> trans >> dummy >> stock >> dummy >> amount;

    • Note that, stock creation requests will be performed in single-threaded mode only (by stock_client.cpp). However, for non-base case functionality, rest of the operations will be performed in multithreaded mode.

    • To add new stock entries, you can use the following simple approach: std::string stock = “msft”;

sm::stockMap[stock].name
=
stock;
sm::stockMap[stock].balance =
10;

    • Ensure you appropriately lock & unlock the mutex for a Stock prior to sell/buy/status operations to avoid race conditions. Ensure you use a std::lock_guard to automatically lock & unlock a mutex.

    • Do not perform I/O in the critical section. Keep critical sections as short as possible.

    • All changes to a stock must be completed before sending response to client.



Page 4 of 6
Due before:    Deadline posted on canvas


Basic Testing

Run your web-browser, in the debugger to help troubleshoot issues. Next, you can test your web-server using the following URLs, after changing the port number:
    • http://localhost:12345/trans=create&stock=msft

    • http://localhost:12345/trans=buy&stock=msft&amount=10

    • http://localhost:12345/trans=sell&stock=msft&amount=5

    • http://localhost:12345/trans=status&stock=msft

Functional testing
A custom multithreaded test client is supplied along with this homework for testing your server.
You will need to compile the tester program from a terminal once as shown below:


$ g++ -g -Wall -std=c++14 stock_client.cpp -o stock_client -lboost_system -lpthread

Base case -- Will be strictly enforced

The base case tests require the server to operate correctly. The base case is relatively simple string processing. The base case testing should be conducted as shown below, assuming your server is listening on port 6000.


$ ./stock_client base_case_req.txt 6000

Note: On correct operation, the client generates the following output:

Finished block #0 testing phase.
Testing completed.

Optional Feature: Simple multithreading case

Once the base case is operating correctly, handling race conditions in multithreaded mode is relatively straightforward. Ensure you lock/unlock the mutex with a given stock prior to operations to avoid race conditions. In this feature, you are guaranteed that a stock will always have sufficient balance when buying a stock. The multithreading testing should be conducted as shown below, assuming your server is listening on port 6000.


$ ./stock_client mt_test_req.txt 6000

Note: On correct operation, the client will generate the following output:

Finished block #0 testing phase.

Finished block #1 testing phase.
Finished block #2 testing phase.

Finished block #3 testing phase.

Finished block #4 testing phase.

Finished block #5 testing phase.
Testing completed.

Submit to Canvas

This homework assignment must be turned-in electronically via Canvas. Ensure your C++ source files are named appropriately. Ensure your program compiles (without any warnings or style errors) successfully. Ensure you have tested operations of your program as indicated. Once you have tested your implementation, upload the following onto Canvas:



Page 5 of 6
Due before:    Deadline posted on canvas


The 1 C++ source file named with the convention you modified for this homework.
Ensure your source file is named with the convention MUID_homework8.cpp, where
MUID is your Miami University Unique ID (e.g., raodm_homework8.cpp).

Upload all the necessary C++ source files to onto Canvas independently. Do not submit zip/7zip/tar/gzip files. Upload each file independently.


























































Page 6 of 6

More products