<commit_before>package com.sixsq.slipstream.module;

/*
 * +=================================================================+
 * SlipStream Server (WAR)
 * =====
 * Copyright (C) 2013 SixSq Sarl (sixsq.com)
 * =====
 * Licensed 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.
 * -=================================================================-
 */

import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.restlet.Request;
import org.restlet.data.Form;
import org.restlet.data.Status;
import org.restlet.ext.fileupload.RestletFileUpload;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Delete;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.Put;
import org.restlet.resource.ResourceException;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.sixsq.slipstream.connector.ConnectorFactory;
import com.sixsq.slipstream.connector.ParametersFactory;
import com.sixsq.slipstream.exceptions.BadlyFormedElementException;
import com.sixsq.slipstream.exceptions.ConfigurationException;
import com.sixsq.slipstream.exceptions.SlipStreamClientException;
import com.sixsq.slipstream.exceptions.ValidationException;
import com.sixsq.slipstream.persistence.Authz;
import com.sixsq.slipstream.persistence.CloudImageIdentifier;
import com.sixsq.slipstream.persistence.DeploymentModule;
import com.sixsq.slipstream.persistence.ImageModule;
import com.sixsq.slipstream.persistence.Metadata;
import com.sixsq.slipstream.persistence.Module;
import com.sixsq.slipstream.persistence.ModuleCategory;
import com.sixsq.slipstream.persistence.ModuleParameter;
import com.sixsq.slipstream.persistence.ProjectModule;
import com.sixsq.slipstream.resource.ParameterizedResource;
import com.sixsq.slipstream.run.RunFactory;
import com.sixsq.slipstream.util.ModuleUriUtil;
import com.sixsq.slipstream.util.SerializationUtil;
import com.sixsq.slipstream.util.XmlUtil;

/**
 * Unit test see
 * 
 * @see ModuleResourceTest
 * 
 */
public class ModuleResource extends ParameterizedResource<Module> {

	private ModuleCategory category = null;
	public static final String COPY_SOURCE_FORM_PARAMETER_NAME = "source_uri";
	public static final String COPY_TARGET_FORM_PARAMETER_NAME = "target_name";

	protected String getPageRepresentation() {
		return "module";
	}

	@Get("xml")
	public Representation toXml() {
		checkCanGet();

		String result = XmlUtil.normalize(getParameterized());
		return new StringRepresentation(result);
	}

	@Post("form")
	public void copyTo(Representation entity) throws ValidationException {
		Form form = new Form(entity);

		if (!isExisting()) {
			throwClientForbiddenError("Target project doesn't exist: "
					+ getParameterized().getName());
		}

		String sourceUri = form.getFirstValue(COPY_SOURCE_FORM_PARAMETER_NAME);
		if (sourceUri == null) {
			throwClientBadRequest("Missing source uri form parameter");
		}

		String targetName = form.getFirstValue(COPY_TARGET_FORM_PARAMETER_NAME);
		if (targetName == null) {
			throwClientBadRequest("Missing target name form parameter");
		}

		Module source = Module.load(sourceUri);
		if (source == null) {
			throwClientBadRequest("Unknown source module: " + sourceUri);
		}

		if (!source.getAuthz().canGet(getUser())) {
			throwClientForbiddenError("You do not have read rights on the source module: "
					+ source.getName());
		}

		String targetFullName = getParameterized().getName() + "/" + targetName;
		String targetUri = Module.constructResourceUri(targetFullName);

		Module target = Module.load(targetUri);
		if (target != null) {
			throwClientForbiddenError("Target module already exists: "
					+ targetUri);
		}

		if (!getParameterized().getAuthz().canCreateChildren(getUser())) {
			throwClientForbiddenError("You do not have rights to create modules in this project");
		}

		target = source.copy();
		target.getAuthz().setUser(getUser().getName());
		target.getAuthz().clear();
		target.setName(targetFullName);
		target.store(); 

		getResponse().redirectSeeOther("/" + target.getResourceUri());
	}

	@Delete
	public void deleteModule() {

		super.deleteResource();
		Module latest = null;
		latest = Module.loadLatest(getParameterized().getResourceUri());
		try {
			if (latest == null) {
				redirectToParent();
			} else {
				redirectToLatest(latest);
			}
		} catch (ValidationException e) {
			throwClientConflicError(e.getMessage());
		}
	}

	private void redirectToParent() throws ValidationException {
		String resourceUri = getParameterized().getResourceUri();
		String parentResourceUri = ModuleUriUtil
				.extractParentUriFromResourceUri(resourceUri);
		String location = getRequest().getRootRef().toString() + "/"
				+ parentResourceUri;
		getResponse().setLocationRef(location);
		getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
	}

	private void redirectToLatest(Module latest) {
		String location = getRequest().getRootRef().toString() + "/"
				+ latest.getResourceUri();
		getResponse().setLocationRef(location);
		getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
	}

	@Put("form")
	public void updateOrCreateFromForm(Representation entity)
			throws ResourceException {

		Module module = null;
		try {
			module = (Module) processEntityAsForm(entity);
		} catch (ValidationException e) {
			throwClientValidationError(e.getMessage());
		}

		updateOrCreate(module);

		getResponse().setLocationRef("/" + module.getResourceUri());<commit_msg>Added test for empty entity<commit_after>package com.sixsq.slipstream.module;

/*
 * +=================================================================+
 * SlipStream Server (WAR)
 * =====
 * Copyright (C) 2013 Six<NAME> (six<EMAIL>)
 * =====
 * Licensed 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.
 * -=================================================================-
 */

import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.restlet.Request;
import org.restlet.data.Form;
import org.restlet.data.Status;
import org.restlet.ext.fileupload.RestletFileUpload;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Delete;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.Put;
import org.restlet.resource.ResourceException;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.sixsq.slipstream.connector.ConnectorFactory;
import com.sixsq.slipstream.connector.ParametersFactory;
import com.sixsq.slipstream.exceptions.BadlyFormedElementException;
import com.sixsq.slipstream.exceptions.ConfigurationException;
import com.sixsq.slipstream.exceptions.SlipStreamClientException;
import com.sixsq.slipstream.exceptions.ValidationException;
import com.sixsq.slipstream.persistence.Authz;
import com.sixsq.slipstream.persistence.CloudImageIdentifier;
import com.sixsq.slipstream.persistence.DeploymentModule;
import com.sixsq.slipstream.persistence.ImageModule;
import com.sixsq.slipstream.persistence.Metadata;
import com.sixsq.slipstream.persistence.Module;
import com.sixsq.slipstream.persistence.ModuleCategory;
import com.sixsq.slipstream.persistence.ModuleParameter;
import com.sixsq.slipstream.persistence.ProjectModule;
import com.sixsq.slipstream.resource.ParameterizedResource;
import com.sixsq.slipstream.run.RunFactory;
import com.sixsq.slipstream.util.ModuleUriUtil;
import com.sixsq.slipstream.util.SerializationUtil;
import com.sixsq.slipstream.util.XmlUtil;

/**
 * Unit test see
 * 
 * @see ModuleResourceTest
 * 
 */
public class ModuleResource extends ParameterizedResource<Module> {

	private ModuleCategory category = null;
	public static final String COPY_SOURCE_FORM_PARAMETER_NAME = "source_uri";
	public static final String COPY_TARGET_FORM_PARAMETER_NAME = "target_name";

	protected String getPageRepresentation() {
		return "module";
	}

	@Get("xml")
	public Representation toXml() {
		checkCanGet();

		String result = XmlUtil.normalize(getParameterized());
		return new StringRepresentation(result);
	}

	@Post("form")
	public void copyTo(Representation entity) throws ValidationException {
		Form form = new Form(entity);

		if (!isExisting()) {
			throwClientForbiddenError("Target project doesn't exist: "
					+ getParameterized().getName());
		}

		String sourceUri = form.getFirstValue(COPY_SOURCE_FORM_PARAMETER_NAME);
		if (sourceUri == null) {
			throwClientBadRequest("Missing source uri form parameter");
		}

		String targetName = form.getFirstValue(COPY_TARGET_FORM_PARAMETER_NAME);
		if (targetName == null) {
			throwClientBadRequest("Missing target name form parameter");
		}

		Module source = Module.load(sourceUri);
		if (source == null) {
			throwClientBadRequest("Unknown source module: " + sourceUri);
		}

		if (!source.getAuthz().canGet(getUser())) {
			throwClientForbiddenError("You do not have read rights on the source module: "
					+ source.getName());
		}

		String targetFullName = getParameterized().getName() + "/" + targetName;
		String targetUri = Module.constructResourceUri(targetFullName);

		Module target = Module.load(targetUri);
		if (target != null) {
			throwClientForbiddenError("Target module already exists: "
					+ targetUri);
		}

		if (!getParameterized().getAuthz().canCreateChildren(getUser())) {
			throwClientForbiddenError("You do not have rights to create modules in this project");
		}

		target = source.copy();
		target.getAuthz().setUser(getUser().getName());
		target.getAuthz().clear();
		target.setName(targetFullName);
		target.store(); 

		getResponse().redirectSeeOther("/" + target.getResourceUri());
	}

	@Delete
	public void deleteModule() {

		super.deleteResource();
		Module latest = null;
		latest = Module.loadLatest(getParameterized().getResourceUri());
		try {
			if (latest == null) {
				redirectToParent();
			} else {
				redirectToLatest(latest);
			}
		} catch (ValidationException e) {
			throwClientConflicError(e.getMessage());
		}
	}

	private void redirectToParent() throws ValidationException {
		String resourceUri = getParameterized().getResourceUri();
		String parentResourceUri = ModuleUriUtil
				.extractParentUriFromResourceUri(resourceUri);
		String location = getRequest().getRootRef().toString() + "/"
				+ parentResourceUri;
		getResponse().setLocationRef(location);
		getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
	}

	private void redirectToLatest(Module latest) {
		String location = getRequest().getRootRef().toString() + "/"
				+ latest.getResourceUri();
		getResponse().setLocationRef(location);
		getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
	}

	@Put("form")
	public void updateOrCreateFromForm(Representation entity)
			throws ResourceException {

		if(entity == null) {
			throwClientBadRequest("Empty form");
		}
		
		Module module = null;
		try {
			module = (Module) processEntityAsForm(entity);
		} catch (ValidationException e) {
			throwClientValidationError(e.getMessage());
		}

		updateOrCreate(module);

		getResponse().setLocationRef("/" + module.getResourceUri());
{'fraction_non_alphanumeric': 0.12947958865690246, 'fraction_numerical': 0.0014023060143346837, 'mean_word_length': 5.470262096774194, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 12}, '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': '5395820', 'n_tokens_mistral': 3929, 'n_tokens_neox': 3673, 'n_words': 784}