Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Trading Engine Test Client
import java.util.Date;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class TradingEngineTestClient implements Runnable {
private static final String BASE_URL = "http://192.168.1.117:8082/training9_spring4-web";
//private static final String BASE_URL = "http://192.168.1.117:3000";
private static final int SALES_QUANTITY_FACTOR = 2;
private static final long WAIT_TIME_AFTER_RUNNING = 50L;
private static final int NUM_CONCURRENT_USERS = 30;
private static final int NUM_PRODUCTS = 99;
private static final int MAX_QUANTITY = 100;
private static final int NUM_SELLERS = 500;
private static final int NUM_BUYERS = 500;
private static final double[] PRICES = {9.99};
private final Random r = new Random();
public static void main(String[] args) throws Exception {
System.out.println("starting...");
new TradingEngineTestClient().go();
System.out.println("done!");
}
private ExecutorService pool = Executors.newFixedThreadPool(NUM_CONCURRENT_USERS); //lots of concurrent users!
public void go() throws Exception {
for(int i = 0; i < NUM_CONCURRENT_USERS; i++){
pool.execute(this);
}
}
@Override
public void run() {
try{
URL url = new URL(BASE_URL + "/sell2?productId=" + (r.nextInt(NUM_PRODUCTS)+1) +
"&quantity=" + SALES_QUANTITY_FACTOR * (1+r.nextInt(MAX_QUANTITY)) +
"&userId=seller-" + r.nextInt(NUM_SELLERS) +
"&price=" + PRICES[r.nextInt(PRICES.length)]);
if(r.nextBoolean()){
url = new URL(BASE_URL + "/buy2?productId=" + (r.nextInt(NUM_PRODUCTS)+1) +
"&quantity=" + (1+r.nextInt(MAX_QUANTITY)) +
"&userId=buyer-" + r.nextInt(NUM_BUYERS));
}
String reply = sendRequest(url, true);
int i = reply.indexOf("\"id\":");
int i2 = reply.indexOf(",", i);
String id = reply.substring(i+5, i2).trim();
System.out.println(id + ") " + url);
}catch(Exception e){
System.err.println(e);
}finally{
//resubmit the job
pool.execute(this);
}
}
private static String sendRequest(URL url, boolean waitAtEnd) throws Exception {
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int current;
try{
while ((current = br.read()) != -1) {
baos.write(current);
}
}finally{
baos.close();
br.close();
}
String reply = baos.toString();
if(waitAtEnd) Thread.sleep(WAIT_TIME_AFTER_RUNNING);
return reply;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.