<commit_before>/**
 * $$\\ToureNPlaner\\$$
 */

package server;

import static org.jboss.netty.handler.codec.http.HttpHeaders.isKeepAlive;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Random;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferInputStream;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.base64.Base64;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.codec.http.QueryStringDecoder;
import org.jboss.netty.util.CharsetUtil;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import computecore.ComputeCore;
import computecore.ComputeRequest;

import config.ConfigManager;
import database.DatabaseManager;
import database.UsersDBRow;

/**
 * This handler handles HTTP Requests on the normal operation socket including *
 * 
 * @author <NAME>, <NAME>
 * @version 0.1
 * 
 *          Initially based on: http://docs.jboss.org/netty/3.2/xref
 *          /org/jboss/netty/example/http/snoop/package-summary.html
 */
public class HttpRequestHandler extends SimpleChannelUpstreamHandler {

	/** JSONParser we can reuse **/
	private final JSONParser parser = new JSONParser();

	/** The ComputeCore managing the threads **/
	private final ComputeCore computer;

	private final Map<String, Object> serverInfo;

	private boolean isPrivate;

	private DatabaseManager dbm;

	private MessageDigest digester;

	/**
	 * Constructs a new RequestHandler using the given ComputeCore and
	 * ServerInfo
	 * 
	 * @param cCore
	 * @param serverInfo
	 */
	public HttpRequestHandler(ComputeCore cCore,
			Map<String, Object> serverInfo, boolean isPrivate) {
		super();
		ConfigManager cm = ConfigManager.getInstance();
		computer = cCore;
		this.serverInfo = serverInfo;
		this.isPrivate = isPrivate;
		if (isPrivate) {
			try {

				this.dbm = new DatabaseManager(cm.getEntryString("dburi",
						"jdbc:mysql://localhost:3306/"), cm.getEntryString(
						"dbname", "tourenplaner"), cm.getEntryString("dbuser",
						"toureNPlaner"), cm.getEntryString("dbpw",
						"toureNPlaner"));
			} catch (SQLException e) {
				System.err
						.println("Can't connect to database (switching to public mode) "
								+ e.getMessage());
				this.isPrivate = false;
			}
		}

		if (isPrivate) {
			try {
				digester = MessageDigest.getInstance("SHA-1");
			} catch (NoSuchAlgorithmException e) {
				System.err
						.println("Can't load SHA-1 Digester. Will now switch to public mode");
				this.isPrivate = false;
			}
		}
	}

	/**
	 * Called when a message is received
	 */
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {

		HttpRequest request = (HttpRequest) e.getMessage();
		Channel channel = e.getChannel();
		// System.out.print(request.toString());
		// Handle preflighted requests so wee need to work with OPTION Requests
		if (request.getMethod().equals(HttpMethod.OPTIONS)) {
			handlePreflights(request, channel);
			return;
		}

		Responder responder = new Responder(channel, isKeepAlive(request));

		// Get the Requeststring e.g. /info
		QueryStringDecoder queryStringDecoder = new QueryStringDecoder(
				request.getUri());

		String path = queryStringDecoder.getPath();

		if (path.equals("/info")) {

			handleInfo(request, responder);

		} else if (isPrivate && path.equals("/registeruser")) {

			handleRegisterUser(request, responder);

		} else if (isPrivate && path.equals("/authuser")) {

			handleAuthUser(request, responder);

		} else if (isPrivate && path.equals("/getuser")) {

			handleGetUser(request, responder);

		} else if (isPrivate && path.equals("/updateuser")) {

			handleUpdateUser(request, responder);

		} else if (isPrivate && path.equals("/listrequests")) {

			handleListRequests(request, responder);

		} else if (isPrivate && path.equals("/listusers")) {

			handleListUsers(request, responder);

		} else if (path.startsWith("/alg")) {

			if (!isPrivate || auth(request, responder) != null) {
				String algName = queryStringDecoder.getPath().substring(4);
				handleAlg(request, responder, algName);
			} else {
				responder.writeUnauthorizedClose();
			}
		}

	}

	private void handleAlg(HttpRequest request, Responder responder,
			String algName) throws IOException {

		Map<String, Object> objmap = getJSONContent(responder, request);
		if (objmap != null) {
			// Create ComputeRequest and commit to workqueue
			ComputeRequest req = new ComputeRequest(responder, algName, objmap);
			boolean sucess = computer.submit(req);

			if (!sucess) {
				responder
						.writeErrorMessage(
								"EBUSY",
								"This server is currently too busy to fullfill the request",
								null, HttpResponseStatus.SERVICE_UNAVAILABLE);
			}
		}
	}

	/**<commit_msg>Fix not closing connection for unknown url<commit_after>/**
 * $$\\ToureNPlaner\\$$
 */

package server;

import static org.jboss.netty.handler.codec.http.HttpHeaders.isKeepAlive;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Random;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferInputStream;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.base64.Base64;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.codec.http.QueryStringDecoder;
import org.jboss.netty.util.CharsetUtil;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import computecore.ComputeCore;
import computecore.ComputeRequest;

import config.ConfigManager;
import database.DatabaseManager;
import database.UsersDBRow;

/**
 * This handler handles HTTP Requests on the normal operation socket including *
 * 
 * @author <NAME>, <NAME>
 * @version 0.1
 * 
 *          Initially based on: http://docs.jboss.org/netty/3.2/xref
 *          /org/jboss/netty/example/http/snoop/package-summary.html
 */
public class HttpRequestHandler extends SimpleChannelUpstreamHandler {

	/** JSONParser we can reuse **/
	private final JSONParser parser = new JSONParser();

	/** The ComputeCore managing the threads **/
	private final ComputeCore computer;

	private final Map<String, Object> serverInfo;

	private boolean isPrivate;

	private DatabaseManager dbm;

	private MessageDigest digester;

	/**
	 * Constructs a new RequestHandler using the given ComputeCore and
	 * ServerInfo
	 * 
	 * @param cCore
	 * @param serverInfo
	 */
	public HttpRequestHandler(ComputeCore cCore,
			Map<String, Object> serverInfo, boolean isPrivate) {
		super();
		ConfigManager cm = ConfigManager.getInstance();
		computer = cCore;
		this.serverInfo = serverInfo;
		this.isPrivate = isPrivate;
		if (isPrivate) {
			try {

				this.dbm = new DatabaseManager(cm.getEntryString("dburi",
						"jdbc:mysql://localhost:3306/"), cm.getEntryString(
						"dbname", "tourenplaner"), cm.getEntryString("dbuser",
						"toureNPlaner"), cm.getEntryString("dbpw",
						"toureNPlaner"));
			} catch (SQLException e) {
				System.err
						.println("Can't connect to database (switching to public mode) "
								+ e.getMessage());
				this.isPrivate = false;
			}
		}

		if (isPrivate) {
			try {
				digester = MessageDigest.getInstance("SHA-1");
			} catch (NoSuchAlgorithmException e) {
				System.err
						.println("Can't load SHA-1 Digester. Will now switch to public mode");
				this.isPrivate = false;
			}
		}
	}

	/**
	 * Called when a message is received
	 */
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {

		HttpRequest request = (HttpRequest) e.getMessage();
		Channel channel = e.getChannel();
		// System.out.print(request.toString());
		// Handle preflighted requests so wee need to work with OPTION Requests
		if (request.getMethod().equals(HttpMethod.OPTIONS)) {
			handlePreflights(request, channel);
			return;
		}

		Responder responder = new Responder(channel, isKeepAlive(request));

		// Get the Requeststring e.g. /info
		QueryStringDecoder queryStringDecoder = new QueryStringDecoder(
				request.getUri());

		String path = queryStringDecoder.getPath();

		if (path.equals("/info")) {

			handleInfo(request, responder);

		} else if (isPrivate && path.equals("/registeruser")) {

			handleRegisterUser(request, responder);

		} else if (isPrivate && path.equals("/authuser")) {

			handleAuthUser(request, responder);

		} else if (isPrivate && path.equals("/getuser")) {

			handleGetUser(request, responder);

		} else if (isPrivate && path.equals("/updateuser")) {

			handleUpdateUser(request, responder);

		} else if (isPrivate && path.equals("/listrequests")) {

			handleListRequests(request, responder);

		} else if (isPrivate && path.equals("/listusers")) {

			handleListUsers(request, responder);

		} else if (path.startsWith("/alg")) {

			if (!isPrivate || auth(request, responder) != null) {
				String algName = queryStringDecoder.getPath().substring(4);
				handleAlg(request, responder, algName);
			} else {
				responder.writeUnauthorizedClose();
			}
		} else {
			// Unknown request, close connection
			responder.writeErrorMessage("EUNKNOWNURL",
					"An unknown URL was requested", null,
					HttpResponseStatus.NOT_FOUND);
		}

	}

	private void handleAlg(HttpRequest request, Responder responder,
			String algName) throws IOException {

		Map<String, Object> objmap = getJSONContent(responder, request);
		if (objmap != null) {
			// Create ComputeRequest and commit to workqueue
			ComputeRequest req = new ComputeRequest(responder, algName, objmap);
			boolean sucess = computer.submit(req);

			if (!sucess) {
				responder
						.writeErrorMessage(
								"EBUSY",
								"This server is currently too busy to fullfill the request",
								null, HttpResponseStatus.SERVICE_UNAVAILABLE);
			}
		}
	}

	/**
{'fraction_non_alphanumeric': 0.1169576264240636, 'fraction_numerical': 0.002786656831407262, 'mean_word_length': 4.3214129960750105, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1989915', 'n_tokens_mistral': 4233, 'n_tokens_neox': 3693, 'n_words': 807}