Commits

Anonymous committed 78e3fd4

added IntegerServer.java
It demonstrate features of HttpServer in Java library

  • Participants
  • Parent commits dccafcf

Comments (0)

Files changed (1)

File src/IntegerServer.java

+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.net.HttpURLConnection;
+import java.net.InetSocketAddress;
+import java.net.URL;
+import java.util.Random;
+import java.util.concurrent.Executors;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+import com.sun.net.httpserver.HttpServer;
+
+/**
+ * A simple server to demonstrate Java HTTPServer's functionality.
+ * This server starts with an array of random integers. The main
+ * function post REST request with its own random integers to check if
+ * they are on the server.
+ *
+ * @author Absolute Noob
+ *
+ */
+public class IntegerServer {
+	public static final int SERVER_PORT = 9090; // default server port
+	public static final int MAX_BACKLOG = 50;
+	public static final int MAX_DATA = 20; // maximum integer on
+											// server
+
+	private static final int DATA_SIZE = 10; // number of integer
+	private static final Random RAND = new Random();
+
+	private final HttpServer server;
+	private final int[] data;
+
+	/**
+	 * Create a IntegerServer
+	 *
+	 * @param serverPort
+	 *            port to accept incoming connections
+	 * @param maxBacklog
+	 *            maximum number of backlog
+	 * @throws IOException
+	 */
+	public IntegerServer(int serverPort, int maxBacklog)
+			throws IOException {
+		server = HttpServer.create(new InetSocketAddress(serverPort),
+				maxBacklog);
+		// specify REST callback
+		server.createContext("/find", new FindHandler());
+		server.setExecutor(Executors.newCachedThreadPool());
+
+		data = new int[DATA_SIZE];
+		for (int i = 0; i < data.length; i++) {
+			data[i] = RAND.nextInt(MAX_DATA);
+		}
+	}
+
+	/**
+	 * start server and print initialized data to console
+	 */
+	public void start() {
+		server.start();
+		System.out.println("Server started with data: "
+				+ this.getData());
+	}
+
+	/**
+	 * stop server
+	 *
+	 * @param exitCode
+	 *            exit code
+	 */
+	public void Stop(int exitCode) {
+		server.stop(exitCode);
+	}
+
+	/**
+	 * Get integers on the server
+	 *
+	 * @return string contains all integers from the server separated
+	 *         by a space character
+	 */
+	public String getData() {
+		StringBuilder sb = new StringBuilder();
+		for (int i = 0; i < data.length; i++) {
+			sb.append(data[i]);
+			sb.append(' ');
+		}
+		return sb.toString();
+	}
+
+	/**
+	 * find the specified integer
+	 *
+	 * @param intToFind
+	 *            integer to be found
+	 * @return index of the integer on the server. -1 if not found.
+	 */
+	public int find(int intToFind) {
+		int index = -1;
+		for (int i = 0; i < data.length; i++) {
+			if (data[i] == intToFind) {
+				return i;
+			}
+		}
+		return index;
+	}
+
+	/**
+	 * Handles find REST request
+	 *
+	 * @author Absolute Noob
+	 *
+	 */
+	class FindHandler implements HttpHandler {
+		public void handle(HttpExchange httpEx) throws IOException {
+			// request body is not needed, but it needs to be close as
+			// part of the response
+			httpEx.getRequestBody().close();
+			String reqURI = httpEx.getRequestURI().toString();
+			String[] tmp = reqURI.split("/find/");
+
+			int intToFind = Integer.valueOf(tmp[1]);
+			int index = find(intToFind);
+
+			if (index == -1) {
+				// integer not found
+				httpEx.sendResponseHeaders(
+						HttpURLConnection.HTTP_NOT_FOUND, 0);
+				httpEx.getResponseBody().close();
+			} else {
+				httpEx.sendResponseHeaders(HttpURLConnection.HTTP_OK,
+						0);
+				OutputStreamWriter writer = new OutputStreamWriter(
+						httpEx.getResponseBody());
+				// have to convert index to string, write function
+				// doesn't accept int
+				writer.write(String.valueOf(index));
+				writer.flush();
+				writer.close();
+			}
+		}
+	}
+
+	/**
+	 * simple function to find specified integer on the server
+	 *
+	 * @param serverPort
+	 *            port of server that accepts REST request
+	 * @param intToFind
+	 *            integer to be found
+	 * @throws IOException
+	 */
+	public static void findIntOnServer(int serverPort, int intToFind)
+			throws IOException {
+		String urlString = String.format(
+				"http://localhost:%d/find/%d", serverPort, intToFind);
+
+		URL url = new URL(urlString);
+		HttpURLConnection con = ((HttpURLConnection) url
+				.openConnection());
+		int responseCode = con.getResponseCode();
+
+		if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
+			System.out.printf("%d is not found on server\n",
+					intToFind);
+		} else if (responseCode == HttpURLConnection.HTTP_OK) {
+			int index = -1;
+			BufferedReader r = new BufferedReader(
+					new InputStreamReader(con.getInputStream()));
+			index = Integer.valueOf(r.readLine());
+
+			System.out.printf("%d is found on server at index %d\n",
+					intToFind, index);
+			r.close();
+		} else {
+			System.err.printf("unexpected response code: %d\n",
+					responseCode);
+		}
+	}
+
+	public static void main(String[] args) {
+		Random rand = new Random();
+		try {
+			IntegerServer server = new IntegerServer(SERVER_PORT,
+					MAX_BACKLOG);
+			server.start();
+			for (int i = 0; i < DATA_SIZE; i++) {
+				findIntOnServer(SERVER_PORT, rand.nextInt(MAX_DATA));
+			}
+			server.Stop(0);
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+	}
+}