<commit_before>/*
 * Copyright 2011 - 2012 by the CloudRAID Team
 * see AUTHORS for more details
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at

 * http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package de.dhbw_mannheim.cloudraid.api.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;

import de.dhbw_mannheim.cloudraid.api.impl.RestApiUrlMapping.MatchResult;
import de.dhbw_mannheim.cloudraid.api.impl.responses.IRestApiResponse;
import de.dhbw_mannheim.cloudraid.api.impl.responses.PlainApiResponse;
import de.dhbw_mannheim.cloudraid.config.ICloudRAIDConfig;
import de.dhbw_mannheim.cloudraid.core.ICloudRAIDService;
import de.dhbw_mannheim.cloudraid.core.ICoreAccess;
import de.dhbw_mannheim.cloudraid.metadatamgr.IMetadataManager;

/**
 * @author <NAME>, <NAME>
 * 
 */
public class RestApiServlet extends HttpServlet {

	/**
	 * Stores all URL mappings.
	 */
	private static ArrayList<RestApiUrlMapping> mappings = new ArrayList<RestApiUrlMapping>();

	/**
	 * 
	 */
	private static final long serialVersionUID = 1967811240645738359L;

	/**
	 * Indicates the version of the API.
	 */
	private static final String API_VERSION = "0.1";

	private ICloudRAIDConfig config;
	private Pattern userpattern;

	/**
	 * A reference to the database that is used
	 */
	private IMetadataManager metadata = null;

	private ICloudRAIDService coreService = null;

	/**
	 * Initializes all URL mappings and stores a reference to the
	 * {@link IMetadataManager}
	 * 
	 * @throws IllegalArgumentException
	 *             Thrown if the pattern or the function is invalid.
	 * @throws SecurityException
	 *             Thrown if the function cannot be accessed
	 * @throws NoSuchMethodException
	 *             Thrown if no such function can be found
	 * @throws InstantiationException
	 *             Thrown if at least one of {@link IMetadataManager},
	 *             {@link ICloudRAIDConfig} or {@link ICloudRAIDService} cannot
	 *             be found.
	 */
	public RestApiServlet() throws IllegalArgumentException, SecurityException,
			NoSuchMethodException, InstantiationException {
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/api/info/$",
				"GET", RestApiServlet.class, "apiInfo"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/file/([^/]+)/$",
				"DELETE", RestApiServlet.class, "fileDelete"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/file/([^/]+)/$",
				"GET", RestApiServlet.class, "fileDownload"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/file/([^/]+)/$",
				"PUT", RestApiServlet.class, "fileNew"));
		RestApiServlet.mappings.add(new RestApiUrlMapping(
				"^/file/([^/]+)/info/$", "GET", RestApiServlet.class,
				"fileInfo"));
		RestApiServlet.mappings.add(new RestApiUrlMapping(
				"^/file/([^/]+)/update/$", "PUT", RestApiServlet.class,
				"fileUpdate"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/list/$", "GET",
				RestApiServlet.class, "list"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/user/add/$",
				"POST", RestApiServlet.class, "userAdd"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/user/auth/$",
				"POST", RestApiServlet.class, "userAuth"));
		RestApiServlet.mappings.add(new RestApiUrlMapping(
				"^/user/auth/logout/$", "GET", RestApiServlet.class,
				"userLogout"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/user/chgpw/$",
				"POST", RestApiServlet.class, "userChangePass"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/user/del/$",
				"DELETE", RestApiServlet.class, "userDelete"));

		BundleContext ctx = FrameworkUtil.getBundle(RestApiServlet.class)
				.getBundleContext();

		ServiceReference<IMetadataManager> srm = ctx
				.getServiceReference(IMetadataManager.class);
		this.metadata = ctx.getService(srm);
		if (this.metadata == null) {
			throw new InstantiationException(
					"No running metadata manager found");
		}

		ServiceReference<ICloudRAIDConfig> src = ctx
				.getServiceReference(ICloudRAIDConfig.class);
		this.config = ctx.getService(src);
		if (this.config == null) {
			throw new InstantiationException("No running config found");
		}

		ServiceReference<ICloudRAIDService> srcore = ctx
				.getServiceReference(ICloudRAIDService.class);
		this.coreService = ctx.getService(srcore);
		if (this.coreService == null) {
			throw new InstantiationException("No core service found");
		}

		this.userpattern = Pattern.compile("[a-zA-Z0-9]");
	}

	/**
	 * View to get the API information. Method must be <code>GET</code> and path
	 * pattern <code>^/api/info/$</code>.
	 * 
	 * @param req
	 *            The request. Needs no HTTP header attributes.
	 * @param resp
	 *            Status codes:
	 *            <ul>
	 *            <li>200 - Success</li>
	 *            </ul>
	 * @param args
	 *            No arguments.
	 */
	public void apiInfo(HttpServletRequest req, IRestApiResponse resp,
			ArrayList<String> args) {
		resp.setStatusCode(200);
		resp.writeField("Core-Service",
				bundleVersionFromClass(this.coreService.getClass()));
		resp.writeField(<commit_msg>fix username pattern in RESTful API<commit_after>/*
 * Copyright 2011 - 2012 by the CloudRAID Team
 * see AUTHORS for more details
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at

 * http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package de.dhbw_mannheim.cloudraid.api.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;

import de.dhbw_mannheim.cloudraid.api.impl.RestApiUrlMapping.MatchResult;
import de.dhbw_mannheim.cloudraid.api.impl.responses.IRestApiResponse;
import de.dhbw_mannheim.cloudraid.api.impl.responses.PlainApiResponse;
import de.dhbw_mannheim.cloudraid.config.ICloudRAIDConfig;
import de.dhbw_mannheim.cloudraid.core.ICloudRAIDService;
import de.dhbw_mannheim.cloudraid.core.ICoreAccess;
import de.dhbw_mannheim.cloudraid.metadatamgr.IMetadataManager;

/**
 * @author <NAME>, <NAME>
 * 
 */
public class RestApiServlet extends HttpServlet {

	/**
	 * Stores all URL mappings.
	 */
	private static ArrayList<RestApiUrlMapping> mappings = new ArrayList<RestApiUrlMapping>();

	/**
	 * 
	 */
	private static final long serialVersionUID = 1967811240645738359L;

	/**
	 * Indicates the version of the API.
	 */
	private static final String API_VERSION = "0.1";

	private ICloudRAIDConfig config;
	private Pattern userpattern;

	/**
	 * A reference to the database that is used
	 */
	private IMetadataManager metadata = null;

	private ICloudRAIDService coreService = null;

	/**
	 * Initializes all URL mappings and stores a reference to the
	 * {@link IMetadataManager}
	 * 
	 * @throws IllegalArgumentException
	 *             Thrown if the pattern or the function is invalid.
	 * @throws SecurityException
	 *             Thrown if the function cannot be accessed
	 * @throws NoSuchMethodException
	 *             Thrown if no such function can be found
	 * @throws InstantiationException
	 *             Thrown if at least one of {@link IMetadataManager},
	 *             {@link ICloudRAIDConfig} or {@link ICloudRAIDService} cannot
	 *             be found.
	 */
	public RestApiServlet() throws IllegalArgumentException, SecurityException,
			NoSuchMethodException, InstantiationException {
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/api/info/$",
				"GET", RestApiServlet.class, "apiInfo"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/file/([^/]+)/$",
				"DELETE", RestApiServlet.class, "fileDelete"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/file/([^/]+)/$",
				"GET", RestApiServlet.class, "fileDownload"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/file/([^/]+)/$",
				"PUT", RestApiServlet.class, "fileNew"));
		RestApiServlet.mappings.add(new RestApiUrlMapping(
				"^/file/([^/]+)/info/$", "GET", RestApiServlet.class,
				"fileInfo"));
		RestApiServlet.mappings.add(new RestApiUrlMapping(
				"^/file/([^/]+)/update/$", "PUT", RestApiServlet.class,
				"fileUpdate"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/list/$", "GET",
				RestApiServlet.class, "list"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/user/add/$",
				"POST", RestApiServlet.class, "userAdd"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/user/auth/$",
				"POST", RestApiServlet.class, "userAuth"));
		RestApiServlet.mappings.add(new RestApiUrlMapping(
				"^/user/auth/logout/$", "GET", RestApiServlet.class,
				"userLogout"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/user/chgpw/$",
				"POST", RestApiServlet.class, "userChangePass"));
		RestApiServlet.mappings.add(new RestApiUrlMapping("^/user/del/$",
				"DELETE", RestApiServlet.class, "userDelete"));

		BundleContext ctx = FrameworkUtil.getBundle(RestApiServlet.class)
				.getBundleContext();

		ServiceReference<IMetadataManager> srm = ctx
				.getServiceReference(IMetadataManager.class);
		this.metadata = ctx.getService(srm);
		if (this.metadata == null) {
			throw new InstantiationException(
					"No running metadata manager found");
		}

		ServiceReference<ICloudRAIDConfig> src = ctx
				.getServiceReference(ICloudRAIDConfig.class);
		this.config = ctx.getService(src);
		if (this.config == null) {
			throw new InstantiationException("No running config found");
		}

		ServiceReference<ICloudRAIDService> srcore = ctx
				.getServiceReference(ICloudRAIDService.class);
		this.coreService = ctx.getService(srcore);
		if (this.coreService == null) {
			throw new InstantiationException("No core service found");
		}

		this.userpattern = Pattern.compile("[a-zA-Z0-9]+");
	}

	/**
	 * View to get the API information. Method must be <code>GET</code> and path
	 * pattern <code>^/api/info/$</code>.
	 * 
	 * @param req
	 *            The request. Needs no HTTP header attributes.
	 * @param resp
	 *            Status codes:
	 *            <ul>
	 *            <li>200 - Success</li>
	 *            </ul>
	 * @param args
	 *            No arguments.
	 */
	public void apiInfo(HttpServletRequest req, IRestApiResponse resp,
			ArrayList<String> args) {
		resp.setStatusCode(200);
		resp.writeField("Core-Service",
				bundleVersionFromClass(this.coreService.getClass()));
		resp.writeField(
{'fraction_non_alphanumeric': 0.11724783524455885, 'fraction_numerical': 0.006396754817068414, 'mean_word_length': 4.190283400809717, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5999885', 'n_tokens_mistral': 4112, 'n_tokens_neox': 3723, 'n_words': 942}