package api.webservice.implementation;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import api.beans.request.ModuleBeanRequest;
import api.error.entity.ErrorEntity;
import iaik.pkcs.pkcs11.Module;
import iaik.pkcs.pkcs11.TokenException;

public class ModuleWebServiceImplementation {

	public Response setModule(HttpServletRequest req, ModuleBeanRequest m) {
		Module module;
		try {
			module = Module.getInstance(m.getPath());
		} catch (IOException e) {
			throw new WebApplicationException(
					Response.status(Status.BAD_REQUEST).entity(new ErrorEntity("Library not accessible (permision or location)")).build());
		}
		
		try {
			module.initialize(null);
			req.getSession().setAttribute("module", module);
			return Response.status(Status.NO_CONTENT).build();
		} catch (TokenException e) {
			throw new WebApplicationException(
					Response.status(Status.BAD_REQUEST).entity(new ErrorEntity("Module already initialized or not initializable")).build());
		}
		
	}

	public Response unsetModule(HttpServletRequest req) {
		Module m = (Module) req.getSession().getAttribute("module");
		if(m == null)
			throw new WebApplicationException(
					Response.status(Status.BAD_REQUEST).entity(new ErrorEntity("Module not initialized")).build());
		try {
			m.finalize();
			req.getSession().removeAttribute("module");
			return Response.status(Status.NO_CONTENT).build();
		} catch (Throwable e) {
			throw new WebApplicationException(
					Response.status(Status.BAD_REQUEST).entity(new ErrorEntity("Module can't be finalized")).build());
		}
		
	}

}

@@ -814,110 +814,8 @@
 %0A%09%09%09
-req.getSession().setAttribute(%22module%22, module);%0A%09%09%09return Response.status(Status.NO_CONTENT).build();
 %0A%09%09%7D
@@ -837,32 +837,34 @@
 ception e) %7B%0A%09%09%09
+//
 throw new WebApp
@@ -877,32 +877,34 @@
 onException(%0A%09%09%09
+//
 %09%09Response.statu
@@ -1010,24 +1010,128 @@
 ild());%0A%09%09%7D%0A
+%09%09req.getSession().setAttribute(%22module%22, module);%0A%09%09return Response.status(Status.NO_CONTENT).build();%0A
 %09%09%0A%09%7D%0A%0A%09publ
@@ -1430,105 +1430,8 @@
 %0A%09%09%09
-req.getSession().removeAttribute(%22module%22);%0A%09%09%09return Response.status(Status.NO_CONTENT).build();
 %0A%09%09%7D
@@ -1448,32 +1448,34 @@
 rowable e) %7B%0A%09%09%09
+//
 throw new WebApp
@@ -1488,32 +1488,34 @@
 onException(%0A%09%09%09
+//
 %09%09Response.statu
@@ -1599,21 +1599,120 @@
 ild());%0A%09%09%7D%0A
+%09%09req.getSession().removeAttribute(%22module%22);%0A%09%09return Response.status(Status.NO_CONTENT).build();%0A
 %09%09%0A%09%7D%0A%0A%7D%0A

Fix ModuleWS