diff --git a/.classpath b/.classpath index 44ae34cd..b702eca8 100755 --- a/.classpath +++ b/.classpath @@ -4,59 +4,79 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/etc/ant_configuration/service.properties b/etc/ant_configuration/service.properties index 603a3ed9..9c5d3b5d 100755 --- a/etc/ant_configuration/service.properties +++ b/etc/ant_configuration/service.properties @@ -1,48 +1,48 @@ -service.0.version=0.2 +service.0.version=0.3 service.0.name=de.rwth.dbis.acis.bazaar.service service.0.path=de/rwth/dbis/acis/bazaar/service service.0.class=BazaarService service.0.passphrase=Passphrase -service.0.dependencies= +service.0.dependencies=commons-codec;version="1.9",commons-dbcp2;version="2.0",commons-io;version="2.4",commons-logging;version="1.2",commons-pool2;version="2.2",emoji-java;version="3.1.3",gson;version="2.3",httpclient;version="4.5.1",httpcore;version="4.4.3",jodd-bean;version="3.6.1",jodd-core;version="3.6.1",jodd-vtor;version="3.6.1",jooq;version="3.8.2",jooq-codegen;version="3.8.2",jooq-meta;version="3.8.2",json;version="20140107",mysql-connector-java;version="5.1.6" -service.1.version=0.2 +service.1.version=0.3 service.1.name=de.rwth.dbis.acis.bazaar.service service.1.path=de/rwth/dbis/acis/bazaar/service service.1.class=ProjectsResource service.1.passphrase=Passphrase -service.1.dependencies= +service.1.dependencies=commons-codec;version="1.9",commons-dbcp2;version="2.0",commons-io;version="2.4",commons-logging;version="1.2",commons-pool2;version="2.2",emoji-java;version="3.1.3",gson;version="2.3",httpclient;version="4.5.1",httpcore;version="4.4.3",jodd-bean;version="3.6.1",jodd-core;version="3.6.1",jodd-vtor;version="3.6.1",jooq;version="3.8.2",jooq-codegen;version="3.8.2",jooq-meta;version="3.8.2",json;version="20140107",mysql-connector-java;version="5.1.6" -service.2.version=0.2 +service.2.version=0.3 service.2.name=de.rwth.dbis.acis.bazaar.service service.2.path=de/rwth/dbis/acis/bazaar/service service.2.class=ComponentsResource service.2.passphrase=Passphrase -service.2.dependencies= +service.2.dependencies=commons-codec;version="1.9",commons-dbcp2;version="2.0",commons-io;version="2.4",commons-logging;version="1.2",commons-pool2;version="2.2",emoji-java;version="3.1.3",gson;version="2.3",httpclient;version="4.5.1",httpcore;version="4.4.3",jodd-bean;version="3.6.1",jodd-core;version="3.6.1",jodd-vtor;version="3.6.1",jooq;version="3.8.2",jooq-codegen;version="3.8.2",jooq-meta;version="3.8.2",json;version="20140107",mysql-connector-java;version="5.1.6" -service.3.version=0.2 +service.3.version=0.3 service.3.name=de.rwth.dbis.acis.bazaar.service service.3.path=de/rwth/dbis/acis/bazaar/service service.3.class=RequirementsResource service.3.passphrase=Passphrase -service.3.dependencies= +service.3.dependencies=commons-codec;version="1.9",commons-dbcp2;version="2.0",commons-io;version="2.4",commons-logging;version="1.2",commons-pool2;version="2.2",emoji-java;version="3.1.3",gson;version="2.3",httpclient;version="4.5.1",httpcore;version="4.4.3",jodd-bean;version="3.6.1",jodd-core;version="3.6.1",jodd-vtor;version="3.6.1",jooq;version="3.8.2",jooq-codegen;version="3.8.2",jooq-meta;version="3.8.2",json;version="20140107",mysql-connector-java;version="5.1.6" -service.4.version=0.2 +service.4.version=0.3 service.4.name=de.rwth.dbis.acis.bazaar.service service.4.path=de/rwth/dbis/acis/bazaar/service service.4.class=CommentsResource service.4.passphrase=Passphrase -service.4.dependencies= +service.4.dependencies=commons-codec;version="1.9",commons-dbcp2;version="2.0",commons-io;version="2.4",commons-logging;version="1.2",commons-pool2;version="2.2",emoji-java;version="3.1.3",gson;version="2.3",httpclient;version="4.5.1",httpcore;version="4.4.3",jodd-bean;version="3.6.1",jodd-core;version="3.6.1",jodd-vtor;version="3.6.1",jooq;version="3.8.2",jooq-codegen;version="3.8.2",jooq-meta;version="3.8.2",json;version="20140107",mysql-connector-java;version="5.1.6" -service.5.version=0.2 +service.5.version=0.3 service.5.name=de.rwth.dbis.acis.bazaar.service service.5.path=de/rwth/dbis/acis/bazaar/service service.5.class=AttachmentsResource service.5.passphrase=Passphrase -service.5.dependencies= +service.5.dependencies=commons-codec;version="1.9",commons-dbcp2;version="2.0",commons-io;version="2.4",commons-logging;version="1.2",commons-pool2;version="2.2",emoji-java;version="3.1.3",gson;version="2.3",httpclient;version="4.5.1",httpcore;version="4.4.3",jodd-bean;version="3.6.1",jodd-core;version="3.6.1",jodd-vtor;version="3.6.1",jooq;version="3.8.2",jooq-codegen;version="3.8.2",jooq-meta;version="3.8.2",json;version="20140107",mysql-connector-java;version="5.1.6" -service.6.version=0.2 +service.6.version=0.3 service.6.name=de.rwth.dbis.acis.bazaar.service service.6.path=de/rwth/dbis/acis/bazaar/service service.6.class=UsersResource service.6.passphrase=Passphrase -service.6.dependencies= +service.6.dependencies=commons-codec;version="1.9",commons-dbcp2;version="2.0",commons-io;version="2.4",commons-logging;version="1.2",commons-pool2;version="2.2",emoji-java;version="3.1.3",gson;version="2.3",httpclient;version="4.5.1",httpcore;version="4.4.3",jodd-bean;version="3.6.1",jodd-core;version="3.6.1",jodd-vtor;version="3.6.1",jooq;version="3.8.2",jooq-codegen;version="3.8.2",jooq-meta;version="3.8.2",json;version="20140107",mysql-connector-java;version="5.1.6" diff --git a/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties b/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties index 879daa8a..4da64302 100644 --- a/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties +++ b/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties @@ -5,6 +5,6 @@ lang=eng country=us baseURL=http://localhost:8080/bazaar/ frontendBaseURL=http://localhost:5000/ -activityTrackerService=de.rwth.dbis.acis.activitytracker.service.ActivityTrackerService@0.1 +activityTrackerService=de.rwth.dbis.acis.activitytracker.service.ActivityTrackerService@0.2 smtpServer= emailFromAddress= \ No newline at end of file diff --git a/etc/ivy/ivy.xml b/etc/ivy/ivy.xml index 6082458a..61e4e39b 100755 --- a/etc/ivy/ivy.xml +++ b/etc/ivy/ivy.xml @@ -10,20 +10,20 @@ - - + + - - - - - - - - - - - + + + + + + + + + + + diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/AttachmentsResource.java b/src/main/de/rwth/dbis/acis/bazaar/service/AttachmentsResource.java index fc71322c..6efdfc97 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/AttachmentsResource.java +++ b/src/main/de/rwth/dbis/acis/bazaar/service/AttachmentsResource.java @@ -1,6 +1,5 @@ package de.rwth.dbis.acis.bazaar.service; - import com.google.gson.Gson; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.Attachment; @@ -12,209 +11,203 @@ import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; -import i5.las2peer.api.Service; -import i5.las2peer.restMapper.HttpResponse; -import i5.las2peer.restMapper.MediaType; -import i5.las2peer.restMapper.RESTMapper; -import i5.las2peer.restMapper.annotations.ContentParam; +import i5.las2peer.api.Context; +import i5.las2peer.restMapper.RESTService; +import i5.las2peer.restMapper.annotations.ServicePath; import i5.las2peer.security.UserAgent; import io.swagger.annotations.*; import jodd.vtor.Vtor; import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import java.net.HttpURLConnection; import java.util.Arrays; import java.util.EnumSet; -@Path("/bazaar/attachments") -@Api(value = "/attachments", description = "Attachments resource") -public class AttachmentsResource extends Service { +@ServicePath("/bazaar/attachments") +public class AttachmentsResource extends RESTService { private BazaarService bazaarService; - /** - * This method is needed for every RESTful application in LAS2peer. - * - * @return the mapping to the REST interface. - */ - public String getRESTMapping() { - String result = ""; - try { - result = RESTMapper.getMethodsAsXML(this.getClass()); - } catch (Exception e) { - - e.printStackTrace(); - } - return result; + @Override + protected void initResources() { + getResourceConfig().register(AttachmentsResource.Resource.class); } public AttachmentsResource() throws Exception { bazaarService = new BazaarService(); } - /** - * This method allows to retrieve a certain attachment. - * - * @param attachmentId id of the attachment - * @return Response with attachment as a JSON object. - */ - @GET - @Path("/{attachmentId}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to retrieve a certain attachment") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain attachment"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse getAttachment(@PathParam("attachmentId") int attachmentId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Attachment attachment = dalFacade.getAttachmentById(attachmentId); - Requirement requirement = dalFacade.getRequirementById(attachment.getRequirementId(), internalUserId); - if (dalFacade.isProjectPublic(requirement.getProjectId())) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_ATTACHMENT, String.valueOf(requirement.getProjectId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + @Path("/") + public static class Resource { + + private final AttachmentsResource service = (AttachmentsResource) Context.getCurrent().getService(); + + /** + * This method allows to retrieve a certain attachment. + * + * @param attachmentId id of the attachment + * @return Response with attachment as a JSON object. + */ + @GET + @Path("/{attachmentId}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to retrieve a certain attachment") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain attachment"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getAttachment(@PathParam("attachmentId") int attachmentId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); } - } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_ATTACHMENT, String.valueOf(requirement.getProjectId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.attachment.read")); + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + Attachment attachment = dalFacade.getAttachmentById(attachmentId); + Requirement requirement = dalFacade.getRequirementById(attachment.getRequirementId(), internalUserId); + if (dalFacade.isProjectPublic(requirement.getProjectId())) { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_ATTACHMENT, String.valueOf(requirement.getProjectId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + } else { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_ATTACHMENT, String.valueOf(requirement.getProjectId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.attachment.read")); + } } + Gson gson = new Gson(); + return Response.ok(gson.toJson(attachment)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - Gson gson = new Gson(); - return new HttpResponse(gson.toJson(attachment), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); - } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method allows to create a new attachment. - * - * @param attachment as JSON object - * @return Response with the created attachment as JSON object. - */ - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to create a new attachment.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the created attachement"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse createAttachment(@ApiParam(value = "Attachment entity as JSON", required = true) @ContentParam String attachment) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - Gson gson = new Gson(); - Attachment attachmentToCreate = gson.fromJson(attachment, Attachment.class); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(attachmentToCreate); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Requirement requirement = dalFacade.getRequirementById(attachmentToCreate.getRequirementId(), internalUserId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_ATTACHMENT, String.valueOf(requirement.getProjectId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.attachment.create")); - } - attachmentToCreate.setCreatorId(internalUserId); - Attachment createdAttachment = dalFacade.createAttachment(attachmentToCreate); - return new HttpResponse(gson.toJson(createdAttachment), HttpURLConnection.HTTP_CREATED); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method allows to create a new attachment. + * + * @param attachment as JSON object + * @return Response with the created attachment as JSON object. + */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to create a new attachment.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the created attachement"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response createAttachment(@ApiParam(value = "Attachment entity as JSON", required = true) String attachment) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + Gson gson = new Gson(); + Attachment attachmentToCreate = gson.fromJson(attachment, Attachment.class); + Vtor vtor = service.bazaarService.getValidators(); + vtor.validate(attachmentToCreate); + if (vtor.hasViolations()) { + ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + Requirement requirement = dalFacade.getRequirementById(attachmentToCreate.getRequirementId(), internalUserId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_ATTACHMENT, String.valueOf(requirement.getProjectId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.attachment.create")); + } + attachmentToCreate.setCreatorId(internalUserId); + Attachment createdAttachment = dalFacade.createAttachment(attachmentToCreate); + return Response.status(Response.Status.CREATED).entity(gson.toJson(createdAttachment)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method deletes a specific attachment. - * - * @param attachmentId id of the attachment, which should be deleted - * @return Response with the deleted attachment as a JSON object. - */ - @DELETE - @Path("/{attachmentId}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method deletes a specific attachment.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the deleted attachment"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse deleteAttachment(@PathParam("attachmentId") int attachmentId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Requirement requirement = dalFacade.getRequirementById(attachmentId, internalUserId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_ATTACHMENT, Arrays.asList(String.valueOf(attachmentId), String.valueOf(requirement.getProjectId())), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.attachment.modify")); - } - Attachment deletedAttachment = dalFacade.deleteAttachmentById(attachmentId); - Gson gson = new Gson(); - return new HttpResponse(gson.toJson(deletedAttachment), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method deletes a specific attachment. + * + * @param attachmentId id of the attachment, which should be deleted + * @return Response with the deleted attachment as a JSON object. + */ + @DELETE + @Path("/{attachmentId}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method deletes a specific attachment.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the deleted attachment"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response deleteAttachment(@PathParam("attachmentId") int attachmentId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + Requirement requirement = dalFacade.getRequirementById(attachmentId, internalUserId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_ATTACHMENT, Arrays.asList(String.valueOf(attachmentId), String.valueOf(requirement.getProjectId())), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.attachment.modify")); + } + Attachment deletedAttachment = dalFacade.deleteAttachmentById(attachmentId); + Gson gson = new Gson(); + return Response.ok(gson.toJson(deletedAttachment)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } } - } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/BazaarFunctionRegistrator.java b/src/main/de/rwth/dbis/acis/bazaar/service/BazaarFunctionRegistrator.java index f22a6252..ea3737e0 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/BazaarFunctionRegistrator.java +++ b/src/main/de/rwth/dbis/acis/bazaar/service/BazaarFunctionRegistrator.java @@ -27,5 +27,5 @@ * @since 1/9/2015 */ public interface BazaarFunctionRegistrator { - public void registerFunction(EnumSet functions) throws Exception; + void registerFunction(EnumSet functions) throws Exception; } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/BazaarService.java b/src/main/de/rwth/dbis/acis/bazaar/service/BazaarService.java index e175f9dd..2f9f56ca 100755 --- a/src/main/de/rwth/dbis/acis/bazaar/service/BazaarService.java +++ b/src/main/de/rwth/dbis/acis/bazaar/service/BazaarService.java @@ -38,22 +38,19 @@ import de.rwth.dbis.acis.bazaar.service.notification.NotificationDispatcher; import de.rwth.dbis.acis.bazaar.service.notification.NotificationDispatcherImp; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; -import i5.las2peer.api.Service; -import i5.las2peer.restMapper.HttpResponse; -import i5.las2peer.restMapper.RESTMapper; -import i5.las2peer.restMapper.annotations.Version; +import i5.las2peer.restMapper.RESTService; +import i5.las2peer.restMapper.annotations.ServicePath; import i5.las2peer.security.UserAgent; import io.swagger.annotations.*; - import jodd.vtor.Vtor; import org.apache.commons.dbcp2.*; - import org.apache.http.client.utils.URIBuilder; import org.jooq.SQLDialect; +import javax.annotation.Resource; import javax.sql.DataSource; -import javax.ws.rs.Path; -import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.Link; +import javax.ws.rs.core.Response; import java.net.URISyntaxException; import java.util.*; @@ -65,13 +62,12 @@ * * @author István Koren */ -@Path("/bazaar") -@Version("0.2") +@ServicePath("/bazaar/main") @Api @SwaggerDefinition( info = @Info( title = "Requirements Bazaar", - version = "0.2", + version = "0.3", description = "Requirements Bazaar project", termsOfService = "http://requirements-bazaar.org", contact = @Contact( @@ -88,7 +84,7 @@ basePath = "", schemes = SwaggerDefinition.Scheme.HTTPS ) -public class BazaarService extends Service { +public class BazaarService extends RESTService { //CONFIG PROPERTIES protected String dbUserName; @@ -107,20 +103,9 @@ public class BazaarService extends Service { private NotificationDispatcher notificationDispatcher; private DataSource dataSource; - /** - * This method is needed for every RESTful application in LAS2peer. - * - * @return the mapping to the REST interface. - */ - public String getRESTMapping() { - String result = ""; - try { - result = RESTMapper.getMethodsAsXML(this.getClass()); - } catch (Exception e) { - - e.printStackTrace(); - } - return result; + @Override + protected void initResources() { + getResourceConfig().register(Resource.class); } public BazaarService() throws Exception { @@ -170,10 +155,10 @@ public void registerFunction(EnumSet functions) throws Exception }); notificationDispatcher = new NotificationDispatcherImp(); - if (! activityTrackerService.isEmpty()) { + if (!activityTrackerService.isEmpty()) { notificationDispatcher.setActivityDispatcher(new ActivityDispatcher(this, activityTrackerService, baseURL, frontendBaseURL)); } - if (! smtpServer.isEmpty()) { + if (!smtpServer.isEmpty()) { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); notificationDispatcher.setEmailDispatcher(new EmailDispatcher(this, smtpServer, emailFromAddress, frontendBaseURL)); @@ -282,36 +267,37 @@ public void closeDBConnection(DALFacade dalFacade) { dalFacade.close(); } - public HttpResponse addPaginationToHtppResponse(PaginationResult paginationResult, - String path, - Map httpParameter, - HttpResponse httpResponse) throws URISyntaxException { - httpResponse.setHeader("X-Page", String.valueOf(paginationResult.getPageable().getPageNumber())); - httpResponse.setHeader("X-Per-Page", String.valueOf(paginationResult.getPageable().getPageSize())); + public Response.ResponseBuilder paginationLinks(Response.ResponseBuilder responseBuilder, PaginationResult paginationResult, + String path, Map httpParameter) throws URISyntaxException { + List links = new ArrayList<>(); + URIBuilder uriBuilder = new URIBuilder(baseURL + path); + for (Map.Entry entry : httpParameter.entrySet()) { + uriBuilder.addParameter(entry.getKey(), entry.getValue()); + } if (paginationResult.getPrevPage() != -1) { - httpResponse.setHeader("X-Prev-Page", String.valueOf(paginationResult.getPrevPage())); + links.add(Link.fromUri(uriBuilder.setParameter("page", String.valueOf(paginationResult.getPrevPage())).build()).rel("prev").build()); } if (paginationResult.getNextPage() != -1) { - httpResponse.setHeader("X-Next-Page", String.valueOf(paginationResult.getNextPage())); + links.add(Link.fromUri(uriBuilder.setParameter("page", String.valueOf(paginationResult.getNextPage())).build()).rel("next").build()); } - httpResponse.setHeader("X-Total-Pages", String.valueOf(paginationResult.getTotalPages())); - httpResponse.setHeader("X-Total", String.valueOf(paginationResult.getTotal())); + links.add(Link.fromUri(uriBuilder.setParameter("page", "0").build()).rel("first").build()); + links.add(Link.fromUri(uriBuilder.setParameter("page", String.valueOf(paginationResult.getTotalPages())).build()).rel("last").build()); + responseBuilder = responseBuilder.links(links.toArray(new Link[links.size()])); + return responseBuilder; + } - URIBuilder uriBuilder = new URIBuilder(baseURL + path); - for (Map.Entry entry : httpParameter.entrySet()) { - uriBuilder.addParameter(entry.getKey(), entry.getValue()); - } - String links = new String(); + public Response.ResponseBuilder xHeaderFields(Response.ResponseBuilder responseBuilder, PaginationResult paginationResult) { + responseBuilder = responseBuilder.header("X-Page", String.valueOf(paginationResult.getPageable().getPageNumber())); + responseBuilder = responseBuilder.header("X-Per-Page", String.valueOf(paginationResult.getPageable().getPageSize())); if (paginationResult.getPrevPage() != -1) { - links = links.concat("<" + uriBuilder.setParameter("page", String.valueOf(paginationResult.getPrevPage())).build() + ">; rel=\"prev\","); + responseBuilder = responseBuilder.header("X-Prev-Page", String.valueOf(paginationResult.getPrevPage())); } if (paginationResult.getNextPage() != -1) { - links = links.concat("<" + uriBuilder.setParameter("page", String.valueOf(paginationResult.getNextPage())).build() + ">; rel=\"next\","); + responseBuilder = responseBuilder.header("X-Next-Page", String.valueOf(paginationResult.getNextPage())); } - links = links.concat("<" + uriBuilder.setParameter("page", "0") + ">; rel=\"first\","); - links = links.concat("<" + uriBuilder.setParameter("page", String.valueOf(paginationResult.getTotalPages() - 1)).build() + ">; rel=\"last\""); - httpResponse.setHeader("Link", links); - return httpResponse; + responseBuilder = responseBuilder.header("X-Total-Pages", String.valueOf(paginationResult.getTotalPages())); + responseBuilder = responseBuilder.header("X-Total", String.valueOf(paginationResult.getTotal())); + return responseBuilder; } } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/CommentsResource.java b/src/main/de/rwth/dbis/acis/bazaar/service/CommentsResource.java index b177ebc8..ed8308f1 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/CommentsResource.java +++ b/src/main/de/rwth/dbis/acis/bazaar/service/CommentsResource.java @@ -12,218 +12,215 @@ import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; -import i5.las2peer.api.Service; -import i5.las2peer.restMapper.HttpResponse; -import i5.las2peer.restMapper.MediaType; -import i5.las2peer.restMapper.RESTMapper; -import i5.las2peer.restMapper.annotations.ContentParam; + +import i5.las2peer.api.Context; +import i5.las2peer.restMapper.RESTService; +import i5.las2peer.restMapper.annotations.ServicePath; import i5.las2peer.security.UserAgent; import io.swagger.annotations.*; import jodd.vtor.Vtor; import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import java.net.HttpURLConnection; import java.util.Arrays; import java.util.EnumSet; -@Path("/bazaar/comments") -@Api(value = "/comments", description = "Comments resource") -public class CommentsResource extends Service { - private BazaarService bazaarService; +@ServicePath("/bazaar/comments") +public class CommentsResource extends RESTService { - /** - * This method is needed for every RESTful application in LAS2peer. - * - * @return the mapping to the REST interface. - */ - public String getRESTMapping() { - String result = ""; - try { - result = RESTMapper.getMethodsAsXML(this.getClass()); - } catch (Exception e) { + private BazaarService bazaarService; - e.printStackTrace(); - } - return result; + @Override + protected void initResources() { + getResourceConfig().register(CommentsResource.Resource.class); } + public CommentsResource() throws Exception { bazaarService = new BazaarService(); } - /** - * This method allows to retrieve a certain comment. - * - * @param commentId id of the comment - * @return Response with comment as a JSON object. - */ - @GET - @Path("/{commentId}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to retrieve a certain comment") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain comment"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse getComment(@PathParam("commentId") int commentId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Comment comment = dalFacade.getCommentById(commentId); - Requirement requirement = dalFacade.getRequirementById(comment.getRequirementId(), internalUserId); - if (dalFacade.isProjectPublic(requirement.getProjectId())) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, String.valueOf(requirement.getProjectId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + @Path("/") + public static class Resource { + + private final CommentsResource service = (CommentsResource) Context.getCurrent().getService(); + + /** + * This method allows to retrieve a certain comment. + * + * @param commentId id of the comment + * @return Response with comment as a JSON object. + */ + @GET + @Path("/{commentId}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to retrieve a certain comment") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain comment"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getComment(@PathParam("commentId") int commentId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); } - } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMMENT, String.valueOf(requirement.getProjectId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.read")); + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + Comment comment = dalFacade.getCommentById(commentId); + Requirement requirement = dalFacade.getRequirementById(comment.getRequirementId(), internalUserId); + if (dalFacade.isProjectPublic(requirement.getProjectId())) { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, String.valueOf(requirement.getProjectId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + } else { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMMENT, String.valueOf(requirement.getProjectId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.read")); + } } + Gson gson = new Gson(); + return Response.ok(gson.toJson(comment)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - Gson gson = new Gson(); - return new HttpResponse(gson.toJson(comment), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); - } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method allows to create a new comment. - * - * @param comment comment as JSON object - * @return Response with the created comment as JSON object. - */ - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to create a new comment.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the created comment"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse createComment(@ApiParam(value = "Comment entity as JSON", required = true) @ContentParam String comment) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - // TODO: check whether the current user may create a new requirement - // TODO: check whether all required parameters are entered - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - Gson gson = new Gson(); - Comment commentToCreate = gson.fromJson(comment, Comment.class); - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Requirement requirement = dalFacade.getRequirementById(commentToCreate.getRequirementId(), internalUserId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_COMMENT, String.valueOf(requirement.getProjectId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.create")); - } - commentToCreate.setCreatorId(internalUserId); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(commentToCreate); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } - dalFacade.followRequirement(internalUserId, requirement.getId()); - Comment createdComment = dalFacade.createComment(commentToCreate); - bazaarService.getNotificationDispatcher().dispatchNotification(this, createdComment.getCreationTime(), Activity.ActivityAction.CREATE, createdComment.getId(), - Activity.DataType.COMMENT, createdComment.getRequirementId(), Activity.DataType.REQUIREMENT, internalUserId); - return new HttpResponse(gson.toJson(createdComment), HttpURLConnection.HTTP_CREATED); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method allows to create a new comment. + * + * @param comment comment as JSON object + * @return Response with the created comment as JSON object. + */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to create a new comment.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the created comment"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response createComment(@ApiParam(value = "Comment entity as JSON", required = true) String comment) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + // TODO: check whether the current user may create a new requirement + // TODO: check whether all required parameters are entered + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + Gson gson = new Gson(); + Comment commentToCreate = gson.fromJson(comment, Comment.class); + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + Requirement requirement = dalFacade.getRequirementById(commentToCreate.getRequirementId(), internalUserId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_COMMENT, String.valueOf(requirement.getProjectId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.create")); + } + commentToCreate.setCreatorId(internalUserId); + Vtor vtor = service.bazaarService.getValidators(); + vtor.validate(commentToCreate); + if (vtor.hasViolations()) { + ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + } + dalFacade.followRequirement(internalUserId, requirement.getId()); + Comment createdComment = dalFacade.createComment(commentToCreate); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, createdComment.getCreationTime(), Activity.ActivityAction.CREATE, createdComment.getId(), + Activity.DataType.COMMENT, createdComment.getRequirementId(), Activity.DataType.REQUIREMENT, internalUserId); + return Response.status(Response.Status.CREATED).entity(gson.toJson(createdComment)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method deletes a specific comment. - * - * @param commentId id of the comment, which should be deleted - * @return Response with the deleted comment as a JSON object. - */ - @DELETE - @Path("/{commentId}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method deletes a specific comment.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the deleted comment"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse deleteComment(@PathParam("commentId") int commentId) { - DALFacade dalFacade = null; - try { - // TODO: check if the user may delete this requirement. - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Comment commentToDelete = dalFacade.getCommentById(commentId); - Requirement requirement = dalFacade.getRequirementById(commentToDelete.getRequirementId(), internalUserId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_COMMENT, Arrays.asList(String.valueOf(commentId), String.valueOf(requirement.getProjectId())), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.modify")); - } - Gson gson = new Gson(); - Comment deletedComment = dalFacade.deleteCommentById(commentId); - bazaarService.getNotificationDispatcher().dispatchNotification(this, deletedComment.getCreationTime(), Activity.ActivityAction.DELETE, deletedComment.getId(), - Activity.DataType.COMMENT, commentToDelete.getRequirementId(), Activity.DataType.REQUIREMENT, internalUserId); - return new HttpResponse(gson.toJson(deletedComment), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method deletes a specific comment. + * + * @param commentId id of the comment, which should be deleted + * @return Response with the deleted comment as a JSON object. + */ + @DELETE + @Path("/{commentId}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method deletes a specific comment.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the deleted comment"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response deleteComment(@PathParam("commentId") int commentId) { + DALFacade dalFacade = null; + try { + // TODO: check if the user may delete this requirement. + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + Comment commentToDelete = dalFacade.getCommentById(commentId); + Requirement requirement = dalFacade.getRequirementById(commentToDelete.getRequirementId(), internalUserId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_COMMENT, Arrays.asList(String.valueOf(commentId), String.valueOf(requirement.getProjectId())), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.modify")); + } + Gson gson = new Gson(); + Comment deletedComment = dalFacade.deleteCommentById(commentId); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, deletedComment.getCreationTime(), Activity.ActivityAction.DELETE, deletedComment.getId(), + Activity.DataType.COMMENT, commentToDelete.getRequirementId(), Activity.DataType.REQUIREMENT, internalUserId); + return Response.ok(gson.toJson(deletedComment)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } } - } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/ComponentsResource.java b/src/main/de/rwth/dbis/acis/bazaar/service/ComponentsResource.java index 6105a3c9..b0136f11 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/ComponentsResource.java +++ b/src/main/de/rwth/dbis/acis/bazaar/service/ComponentsResource.java @@ -11,464 +11,475 @@ import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; -import i5.las2peer.api.Service; -import i5.las2peer.restMapper.HttpResponse; -import i5.las2peer.restMapper.MediaType; -import i5.las2peer.restMapper.RESTMapper; -import i5.las2peer.restMapper.annotations.ContentParam; +import i5.las2peer.api.Context; +import i5.las2peer.restMapper.RESTService; +import i5.las2peer.restMapper.annotations.ServicePath; import i5.las2peer.security.UserAgent; import io.swagger.annotations.*; import jodd.vtor.Vtor; import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import java.net.HttpURLConnection; import java.text.MessageFormat; import java.util.*; -@Path("/bazaar/components") -@Api(value = "/components", description = "Components resource") -public class ComponentsResource extends Service { - private BazaarService bazaarService; +@ServicePath("/bazaar/components") +public class ComponentsResource extends RESTService { - /** - * This method is needed for every RESTful application in LAS2peer. - * - * @return the mapping to the REST interface. - */ - public String getRESTMapping() { - String result = ""; - try { - result = RESTMapper.getMethodsAsXML(this.getClass()); - } catch (Exception e) { + private BazaarService bazaarService; - e.printStackTrace(); - } - return result; + @Override + protected void initResources() { + getResourceConfig().register(Resource.class); } public ComponentsResource() throws Exception { bazaarService = new BazaarService(); } - /** - * This method allows to retrieve a certain component. - * - * @param componentId id of the component under a given project - * @return Response with a component as a JSON object. - */ - @GET - @Path("/{componentId}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to retrieve a certain component.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain component"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse getComponent(@PathParam("componentId") int componentId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Component componentToReturn = dalFacade.getComponentById(componentId); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - if (dalFacade.isComponentPublic(componentId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMPONENT, String.valueOf(componentId), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + @Path("/") + public static class Resource { + + private final ComponentsResource service = (ComponentsResource) Context.getCurrent().getService(); + + /** + * This method allows to retrieve a certain component. + * + * @param componentId id of the component under a given project + * @return Response with a component as a JSON object. + */ + @GET + @Path("/{componentId}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to retrieve a certain component.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain component"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getComponent(@PathParam("componentId") int componentId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); } - } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMPONENT, String.valueOf(componentId), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.read")); + dalFacade = service.bazaarService.getDBConnection(); + Component componentToReturn = dalFacade.getComponentById(componentId); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + if (dalFacade.isComponentPublic(componentId)) { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMPONENT, String.valueOf(componentId), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + } else { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMPONENT, String.valueOf(componentId), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.read")); + } } + Gson gson = new Gson(); + return Response.ok(gson.toJson(componentToReturn)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - Gson gson = new Gson(); - return new HttpResponse(gson.toJson(componentToReturn), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); - } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method allows to create a new component. - * - * @param component component as a JSON object - * @return Response with the created project as a JSON object. - */ - @POST - @Path("/") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to create a new component under a given a project.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the created component"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse createComponent(@ApiParam(value = "Component entity as JSON", required = true) @ContentParam String component) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - // TODO: check whether the current user may create a new project - // TODO: check whether all required parameters are entered - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - Gson gson = new Gson(); - Component componentToCreate = gson.fromJson(component, Component.class); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(componentToCreate); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_COMPONENT, String.valueOf(componentToCreate.getProjectId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.create")); + /** + * This method allows to create a new component. + * + * @param component component as a JSON object + * @return Response with the created project as a JSON object. + */ + @POST + @Path("/") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to create a new component under a given a project.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the created component"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response createComponent(@ApiParam(value = "Component entity as JSON", required = true) String component) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + // TODO: check whether the current user may create a new project + // TODO: check whether all required parameters are entered + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + Gson gson = new Gson(); + Component componentToCreate = gson.fromJson(component, Component.class); + Vtor vtor = service.bazaarService.getValidators(); + vtor.validate(componentToCreate); + if (vtor.hasViolations()) { + ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_COMPONENT, String.valueOf(componentToCreate.getProjectId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.create")); + } + componentToCreate.setLeaderId(internalUserId); + Component createdComponent = dalFacade.createComponent(componentToCreate); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, createdComponent.getCreation_time(), Activity.ActivityAction.CREATE, createdComponent.getId(), + Activity.DataType.COMPONENT, createdComponent.getProjectId(), Activity.DataType.PROJECT, internalUserId); + return Response.status(Response.Status.CREATED).entity(gson.toJson(createdComponent)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - componentToCreate.setLeaderId(internalUserId); - Component createdComponent = dalFacade.createComponent(componentToCreate); - bazaarService.getNotificationDispatcher().dispatchNotification(this, createdComponent.getCreation_time(), Activity.ActivityAction.CREATE, createdComponent.getId(), - Activity.DataType.COMPONENT, createdComponent.getProjectId(), Activity.DataType.PROJECT, internalUserId); - return new HttpResponse(gson.toJson(createdComponent), HttpURLConnection.HTTP_CREATED); - } catch (BazaarException bex) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * Allows to update a certain component. - * - * @param componentId id of the component under a given project - * @param component updated component as a JSON object - * @return Response with the updated component as a JSON object. - */ - @PUT - @Path("/{componentId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to update a certain component.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the updated component"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse updateComponent(@PathParam("componentId") int componentId, - @ApiParam(value = "Tag entity as JSON", required = true) @ContentParam String component) { - DALFacade dalFacade = null; - try { - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - long userId = ((UserAgent) getActiveAgent()).getId(); - Gson gson = new Gson(); - Component updatedComponent = gson.fromJson(component, Component.class); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(updatedComponent); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_COMPONENT, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.modify")); - } - if (updatedComponent.getId() != 0 && componentId != updatedComponent.getId()) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, "Id does not match"); - } - updatedComponent = dalFacade.modifyComponent(updatedComponent); - bazaarService.getNotificationDispatcher().dispatchNotification(this, updatedComponent.getLastupdated_time(), Activity.ActivityAction.UPDATE, updatedComponent.getId(), - Activity.DataType.COMPONENT, updatedComponent.getProjectId(), Activity.DataType.PROJECT, internalUserId); - return new HttpResponse(gson.toJson(updatedComponent), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * Allows to update a certain component. + * + * @param componentId id of the component under a given project + * @param component updated component as a JSON object + * @return Response with the updated component as a JSON object. + */ + @PUT + @Path("/{componentId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to update a certain component.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the updated component"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response updateComponent(@PathParam("componentId") int componentId, + @ApiParam(value = "Tag entity as JSON", required = true) String component) { + DALFacade dalFacade = null; + try { + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + Gson gson = new Gson(); + Component updatedComponent = gson.fromJson(component, Component.class); + Vtor vtor = service.bazaarService.getValidators(); + vtor.validate(updatedComponent); + if (vtor.hasViolations()) { + ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_COMPONENT, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.modify")); + } + if (updatedComponent.getId() != 0 && componentId != updatedComponent.getId()) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, "Id does not match"); + } + updatedComponent = dalFacade.modifyComponent(updatedComponent); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, updatedComponent.getLastupdated_time(), Activity.ActivityAction.UPDATE, updatedComponent.getId(), + Activity.DataType.COMPONENT, updatedComponent.getProjectId(), Activity.DataType.PROJECT, internalUserId); + return Response.ok(gson.toJson(updatedComponent)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * Allows to delete a component. - * - * @param componentId id of the component to delete - * @return Response with deleted component as a JSON object. - */ - @DELETE - @Path("/{componentId}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method deletes a specific component.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the deleted component"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse deleteComponent(@PathParam("componentId") int componentId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Component componentToDelete = dalFacade.getComponentById(componentId); - Project project = dalFacade.getProjectById(componentToDelete.getProjectId()); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_COMPONENT, String.valueOf(project.getId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.modify")); - } - if (project.getDefaultComponentId() != null && project.getDefaultComponentId() == componentId) { - ExceptionHandler.getInstance().convertAndThrowException( - new Exception(), - ExceptionLocation.BAZAARSERVICE, - ErrorCode.CANNOTDELETE, - MessageFormat.format(Localization.getInstance().getResourceBundle().getString("error.authorization.component.delete"), componentId) - ); - } - Gson gson = new Gson(); - Component deletedComponent = dalFacade.deleteComponentById(componentId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(this, deletedComponent.getLastupdated_time(), Activity.ActivityAction.DELETE, deletedComponent.getId(), - Activity.DataType.COMPONENT, deletedComponent.getProjectId(), Activity.DataType.PROJECT, internalUserId); - return new HttpResponse(gson.toJson(deletedComponent), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * Allows to delete a component. + * + * @param componentId id of the component to delete + * @return Response with deleted component as a JSON object. + */ + @DELETE + @Path("/{componentId}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method deletes a specific component.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the deleted component"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response deleteComponent(@PathParam("componentId") int componentId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + Component componentToDelete = dalFacade.getComponentById(componentId); + Project project = dalFacade.getProjectById(componentToDelete.getProjectId()); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_COMPONENT, String.valueOf(project.getId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.modify")); + } + if (project.getDefaultComponentId() != null && project.getDefaultComponentId() == componentId) { + ExceptionHandler.getInstance().convertAndThrowException( + new Exception(), + ExceptionLocation.BAZAARSERVICE, + ErrorCode.CANNOTDELETE, + MessageFormat.format(Localization.getInstance().getResourceBundle().getString("error.authorization.component.delete"), componentId) + ); + } + Gson gson = new Gson(); + Component deletedComponent = dalFacade.deleteComponentById(componentId, internalUserId); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, deletedComponent.getLastupdated_time(), Activity.ActivityAction.DELETE, deletedComponent.getId(), + Activity.DataType.COMPONENT, deletedComponent.getProjectId(), Activity.DataType.PROJECT, internalUserId); + return Response.ok(gson.toJson(deletedComponent)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method add the current user to the followers list of a given component. - * - * @param componentId id of the component - * @return Response with component as a JSON object. - */ - @POST - @Path("/{componentId}/followers") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method add the current user to the followers list of a given component.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the component"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse addUserToFollowers(@PathParam("componentId") int componentId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.create")); - } - dalFacade.followComponent(internalUserId, componentId); - Component component = dalFacade.getComponentById(componentId); - Gson gson = new Gson(); - bazaarService.getNotificationDispatcher().dispatchNotification(this, new Date(), Activity.ActivityAction.FOLLOW, component.getId(), - Activity.DataType.COMPONENT, component.getProjectId(), Activity.DataType.PROJECT, internalUserId); - return new HttpResponse(gson.toJson(component), HttpURLConnection.HTTP_CREATED); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method add the current user to the followers list of a given component. + * + * @param componentId id of the component + * @return Response with component as a JSON object. + */ + @POST + @Path("/{componentId}/followers") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method add the current user to the followers list of a given component.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the component"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response addUserToFollowers(@PathParam("componentId") int componentId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.create")); + } + dalFacade.followComponent(internalUserId, componentId); + Component component = dalFacade.getComponentById(componentId); + Gson gson = new Gson(); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, new Date(), Activity.ActivityAction.FOLLOW, component.getId(), + Activity.DataType.COMPONENT, component.getProjectId(), Activity.DataType.PROJECT, internalUserId); + return Response.status(Response.Status.CREATED).entity(gson.toJson(component)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method removes the current user from a followers list of a given component. - * - * @param componentId id of the component - * @return Response with component as a JSON object. - */ - @DELETE - @Path("/{componentId}/followers") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method removes the current user from a followers list of a given component.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the component"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse removeUserFromFollowers(@PathParam("componentId") int componentId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.delete")); - } - dalFacade.unFollowComponent(internalUserId, componentId); - Component component = dalFacade.getComponentById(componentId); - Gson gson = new Gson(); - bazaarService.getNotificationDispatcher().dispatchNotification(this, new Date(), Activity.ActivityAction.UNFOLLOW, component.getId(), - Activity.DataType.COMPONENT, component.getProjectId(), Activity.DataType.PROJECT, internalUserId); - return new HttpResponse(gson.toJson(component), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method removes the current user from a followers list of a given component. + * + * @param componentId id of the component + * @return Response with component as a JSON object. + */ + @DELETE + @Path("/{componentId}/followers") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method removes the current user from a followers list of a given component.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the component"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response removeUserFromFollowers(@PathParam("componentId") int componentId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.delete")); + } + dalFacade.unFollowComponent(internalUserId, componentId); + Component component = dalFacade.getComponentById(componentId); + Gson gson = new Gson(); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, new Date(), Activity.ActivityAction.UNFOLLOW, component.getId(), + Activity.DataType.COMPONENT, component.getProjectId(), Activity.DataType.PROJECT, internalUserId); + return Response.ok(gson.toJson(component)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method returns the list of requirements for a specific component. - * - * @param componentId id of the component under a given project - * @param page page number - * @param perPage number of projects by page - * @return Response with requirements as a JSON array. - */ - @GET - @Path("/{componentId}/requirements") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method returns the list of requirements for a specific component.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of requirements for a given project"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse getRequirementsByComponent(@PathParam("componentId") int componentId, - @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, - @ApiParam(value = "Elements of requirements by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage, - @ApiParam(value = "State filter", required = false, allowableValues = "all,open,realized") @DefaultValue("all") @QueryParam("state") String stateFilter) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - Gson gson = new Gson(); - HashMap filters = new HashMap<>(); - if (stateFilter != "all") { - filters.put("realized", stateFilter); - } - PageInfo pageInfo = new PageInfo(page, perPage, filters); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - if (dalFacade.getComponentById(componentId) == null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "component")); - } - Component component = dalFacade.getComponentById(componentId); - Project project = dalFacade.getProjectById(component.getProjectId()); - if (dalFacade.isComponentPublic(componentId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, String.valueOf(project.getId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + /** + * This method returns the list of requirements for a specific component. + * + * @param componentId id of the component under a given project + * @param page page number + * @param perPage number of projects by page + * @return Response with requirements as a JSON array. + */ + @GET + @Path("/{componentId}/requirements") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method returns the list of requirements for a specific component.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of requirements for a given project"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getRequirementsByComponent(@PathParam("componentId") int componentId, + @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, + @ApiParam(value = "Elements of requirements by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage, + @ApiParam(value = "State filter", required = false, allowableValues = "all,open,realized") @DefaultValue("all") @QueryParam("state") String stateFilter) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); } - } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_REQUIREMENT, String.valueOf(project.getId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.read")); + Gson gson = new Gson(); + HashMap filters = new HashMap<>(); + if (stateFilter != "all") { + filters.put("realized", stateFilter); } - } - PaginationResult requirementsResult = dalFacade.listRequirementsByComponent(componentId, pageInfo, internalUserId); + PageInfo pageInfo = new PageInfo(page, perPage, filters); + Vtor vtor = service.bazaarService.getValidators(); + vtor.validate(pageInfo); + if (vtor.hasViolations()) { + ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + if (dalFacade.getComponentById(componentId) == null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "component")); + } + Component component = dalFacade.getComponentById(componentId); + Project project = dalFacade.getProjectById(component.getProjectId()); + if (dalFacade.isComponentPublic(componentId)) { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, String.valueOf(project.getId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + } else { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_REQUIREMENT, String.valueOf(project.getId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.read")); + } + } + PaginationResult requirementsResult = dalFacade.listRequirementsByComponent(componentId, pageInfo, internalUserId); + + Map parameter = new HashMap<>(); + parameter.put("page", String.valueOf(page)); + parameter.put("per_page", String.valueOf(perPage)); - HttpResponse response = new HttpResponse(gson.toJson(requirementsResult.getElements()), HttpURLConnection.HTTP_OK); - Map parameter = new HashMap<>(); - parameter.put("page", String.valueOf(page)); - parameter.put("per_page", String.valueOf(perPage)); - response = bazaarService.addPaginationToHtppResponse(requirementsResult, "components/" + String.valueOf(componentId) + "/requirements", parameter, response); + Response.ResponseBuilder responseBuilder = Response.ok(); + responseBuilder = responseBuilder.entity(gson.toJson(requirementsResult.getElements())); + responseBuilder = service.bazaarService.paginationLinks(responseBuilder, requirementsResult, "components/" + String.valueOf(componentId) + "/requirements", parameter); + responseBuilder = service.bazaarService.xHeaderFields(responseBuilder, requirementsResult); + Response response = responseBuilder.build(); - return response; - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + return response; + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } + } } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/ProjectsResource.java b/src/main/de/rwth/dbis/acis/bazaar/service/ProjectsResource.java index 00e7cc1f..226579f5 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/ProjectsResource.java +++ b/src/main/de/rwth/dbis/acis/bazaar/service/ProjectsResource.java @@ -11,539 +11,554 @@ import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; -import i5.las2peer.api.Service; -import i5.las2peer.restMapper.HttpResponse; -import i5.las2peer.restMapper.MediaType; -import i5.las2peer.restMapper.RESTMapper; -import i5.las2peer.restMapper.annotations.ContentParam; +import i5.las2peer.api.Context; +import i5.las2peer.restMapper.RESTService; +import i5.las2peer.restMapper.annotations.ServicePath; import i5.las2peer.security.UserAgent; import io.swagger.annotations.*; import jodd.vtor.Vtor; import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import java.net.HttpURLConnection; import java.util.*; -@Path("/bazaar/projects") -@Api(value = "/projects", description = "Projects resource") -public class ProjectsResource extends Service { - private BazaarService bazaarService; +@ServicePath("/bazaar/projects") +public class ProjectsResource extends RESTService { - /** - * This method is needed for every RESTful application in LAS2peer. - * - * @return the mapping to the REST interface. - */ - public String getRESTMapping() { - String result = ""; - try { - result = RESTMapper.getMethodsAsXML(this.getClass()); - } catch (Exception e) { + private BazaarService bazaarService; - e.printStackTrace(); - } - return result; + @Override + protected void initResources() { + getResourceConfig().register(Resource.class); } public ProjectsResource() throws Exception { bazaarService = new BazaarService(); } - /** - * This method returns the list of projects on the server. - * - * @param page page number - * @param perPage number of projects by page - * @return Response with list of all projects - */ - @GET @Path("/") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method returns the list of projects on the server.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "List of projects"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse getProjects( - @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, - @ApiParam(value = "Elements of project by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) { - DALFacade dalFacade = null; - try { - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - UserAgent agent = (UserAgent) getActiveAgent(); - Gson gson = new Gson(); - PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>()); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } - dalFacade = bazaarService.getDBConnection(); - PaginationResult projectsResult; - if (agent.getLoginName().equals("anonymous")) { - // return only public projects - projectsResult = dalFacade.listPublicProjects(pageInfo); - } else { - // return public projects and the ones the user belongs to + public static class Resource { + + private final ProjectsResource service = (ProjectsResource) Context.getCurrent().getService(); + + /** + * This method returns the list of projects on the server. + * + * @param page page number + * @param perPage number of projects by page + * @return Response with list of all projects + */ + @GET + @Path("/") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method returns the list of projects on the server.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "List of projects"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getProjects( + @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, + @ApiParam(value = "Elements of project by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) { + DALFacade dalFacade = null; + try { + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); long userId = agent.getId(); - projectsResult = dalFacade.listPublicAndAuthorizedProjects(pageInfo, userId); - } + Gson gson = new Gson(); + PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>()); + Vtor vtor = service.bazaarService.getValidators(); + vtor.validate(pageInfo); + if (vtor.hasViolations()) { + ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + } + dalFacade = service.bazaarService.getDBConnection(); + PaginationResult projectsResult; + if (agent.getLoginName().equals("anonymous")) { + // return only public projects + projectsResult = dalFacade.listPublicProjects(pageInfo); + } else { + // return public projects and the ones the user belongs to + projectsResult = dalFacade.listPublicAndAuthorizedProjects(pageInfo, userId); + } - HttpResponse response = new HttpResponse(gson.toJson(projectsResult.getElements()), HttpURLConnection.HTTP_OK); - Map parameter = new HashMap<>(); - parameter.put("page", String.valueOf(page)); - parameter.put("per_page", String.valueOf(perPage)); - response = bazaarService.addPaginationToHtppResponse(projectsResult, "projects", parameter, response); + Map parameter = new HashMap<>(); + parameter.put("page", String.valueOf(page)); + parameter.put("per_page", String.valueOf(perPage)); - return response; - } catch (BazaarException bex) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); - } - } + Response.ResponseBuilder responseBuilder = Response.ok(); + responseBuilder = responseBuilder.entity(gson.toJson(projectsResult.getElements())); + responseBuilder = service.bazaarService.paginationLinks(responseBuilder, projectsResult, "projects", parameter); + responseBuilder = service.bazaarService.xHeaderFields(responseBuilder, projectsResult); + Response response = responseBuilder.build(); - /** - * This method allows to retrieve a certain project. - * - * @param projectId id of the project to retrieve - * @return Response with a project as a JSON object. - */ - @GET - @Path("/{projectId}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to retrieve a certain project.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain project"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse getProject(@PathParam("projectId") int projectId) { - DALFacade dalFacade = null; - try { - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + return response; + } catch (BazaarException bex) { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - long userId = ((UserAgent) getActiveAgent()).getId(); - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - if (dalFacade.isProjectPublic(projectId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_PROJECT, String.valueOf(projectId), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + + /** + * This method allows to retrieve a certain project. + * + * @param projectId id of the project to retrieve + * @return Response with a project as a JSON object. + */ + @GET + @Path("/{projectId}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to retrieve a certain project.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain project"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getProject(@PathParam("projectId") int projectId) { + DALFacade dalFacade = null; + try { + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); } - } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PROJECT, String.valueOf(projectId), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.read")); + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + if (dalFacade.isProjectPublic(projectId)) { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_PROJECT, String.valueOf(projectId), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + } else { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PROJECT, String.valueOf(projectId), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.read")); + } } + Project projectToReturn = dalFacade.getProjectById(projectId); + Gson gson = new Gson(); + return Response.ok(gson.toJson(projectToReturn)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - Project projectToReturn = dalFacade.getProjectById(projectId); - Gson gson = new Gson(); - return new HttpResponse(gson.toJson(projectToReturn), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); - } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method allows to create a new project. - * - * @param project project as a JSON object - * @return Response with the created project as a JSON object. - */ - @POST - @Path("/") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to create a new project") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the created project"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse createProject(@ApiParam(value = "Project entity as JSON", required = true) @ContentParam String project) { - DALFacade dalFacade = null; - try { - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - long userId = ((UserAgent) getActiveAgent()).getId(); - Gson gson = new Gson(); - Project projectToCreate = gson.fromJson(project, Project.class); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(projectToCreate); - if (vtor.hasViolations()) ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_PROJECT, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.create")); - } - projectToCreate.setLeaderId(internalUserId); - Project createdProject = dalFacade.createProject(projectToCreate); - bazaarService.getNotificationDispatcher().dispatchNotification(this, createdProject.getCreation_time(), Activity.ActivityAction.CREATE, createdProject.getId(), - Activity.DataType.PROJECT, 0, null, internalUserId); - return new HttpResponse(gson.toJson(createdProject), HttpURLConnection.HTTP_CREATED); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method allows to create a new project. + * + * @param project project as a JSON object + * @return Response with the created project as a JSON object. + */ + @POST + @Path("/") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to create a new project") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the created project"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response createProject(@ApiParam(value = "Project entity as JSON", required = true) String project) { + DALFacade dalFacade = null; + try { + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + Gson gson = new Gson(); + Project projectToCreate = gson.fromJson(project, Project.class); + Vtor vtor = service.bazaarService.getValidators(); + vtor.validate(projectToCreate); + if (vtor.hasViolations()) ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_PROJECT, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.create")); + } + projectToCreate.setLeaderId(internalUserId); + Project createdProject = dalFacade.createProject(projectToCreate); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, createdProject.getCreation_time(), Activity.ActivityAction.CREATE, createdProject.getId(), + Activity.DataType.PROJECT, 0, null, internalUserId); + return Response.status(Response.Status.CREATED).entity(gson.toJson(createdProject)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * Allows to update a certain project. - * - * @param projectId id of the project to update - * @param project updated project as a JSON object - * @return Response with the updated project as a JSON object. - */ - @PUT - @Path("/{projectId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to update a certain project.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the updated project"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse updateProject(@PathParam("projectId") int projectId, - @ApiParam(value = "Project entity as JSON", required = true) @ContentParam String project) { - DALFacade dalFacade = null; - try { - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - long userId = ((UserAgent) getActiveAgent()).getId(); - Gson gson = new Gson(); - Project projectToUpdate = gson.fromJson(project, Project.class); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(projectToUpdate); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_PROJECT, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.modify")); - } - if (projectToUpdate.getId() != 0 && projectId != projectToUpdate.getId()) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, "Id does not match"); - } - Project updatedProject = dalFacade.modifyProject(projectToUpdate); - bazaarService.getNotificationDispatcher().dispatchNotification(this, updatedProject.getLastupdated_time(), Activity.ActivityAction.UPDATE, updatedProject.getId(), - Activity.DataType.PROJECT, 0, null, internalUserId); - return new HttpResponse(gson.toJson(updatedProject), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * Allows to update a certain project. + * + * @param projectId id of the project to update + * @param project updated project as a JSON object + * @return Response with the updated project as a JSON object. + */ + @PUT + @Path("/{projectId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to update a certain project.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the updated project"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response updateProject(@PathParam("projectId") int projectId, + @ApiParam(value = "Project entity as JSON", required = true) String project) { + DALFacade dalFacade = null; + try { + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + Gson gson = new Gson(); + Project projectToUpdate = gson.fromJson(project, Project.class); + Vtor vtor = service.bazaarService.getValidators(); + vtor.validate(projectToUpdate); + if (vtor.hasViolations()) { + ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_PROJECT, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.modify")); + } + if (projectToUpdate.getId() != 0 && projectId != projectToUpdate.getId()) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, "Id does not match"); + } + Project updatedProject = dalFacade.modifyProject(projectToUpdate); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, updatedProject.getLastupdated_time(), Activity.ActivityAction.UPDATE, updatedProject.getId(), + Activity.DataType.PROJECT, 0, null, internalUserId); + return Response.ok(gson.toJson(updatedProject)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method add the current user to the followers list of a given project. - * - * @param projectId id of the project - * @return Response with project as a JSON object. - */ - @POST - @Path("/{projectId}/followers") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method add the current user to the followers list of a given project.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the project"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse addUserToFollowers(@PathParam("projectId") int projectId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.create")); - } - dalFacade.followProject(internalUserId, projectId); - Project project = dalFacade.getProjectById(projectId); - Gson gson = new Gson(); - bazaarService.getNotificationDispatcher().dispatchNotification(this, new Date(), Activity.ActivityAction.FOLLOW, project.getId(), - Activity.DataType.PROJECT, 0, null, internalUserId); - return new HttpResponse(gson.toJson(project), HttpURLConnection.HTTP_CREATED); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method add the current user to the followers list of a given project. + * + * @param projectId id of the project + * @return Response with project as a JSON object. + */ + @POST + @Path("/{projectId}/followers") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method add the current user to the followers list of a given project.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the project"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response addUserToFollowers(@PathParam("projectId") int projectId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.create")); + } + dalFacade.followProject(internalUserId, projectId); + Project project = dalFacade.getProjectById(projectId); + Gson gson = new Gson(); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, new Date(), Activity.ActivityAction.FOLLOW, project.getId(), + Activity.DataType.PROJECT, 0, null, internalUserId); + return Response.status(Response.Status.CREATED).entity(gson.toJson(project)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method removes the current user from a followers list of a given project. - * - * @param projectId id of the project - * @return Response with project as a JSON object. - */ - @DELETE - @Path("/{projectId}/followers") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method removes the current user from a followers list of a given project.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the project"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse removeUserFromFollowers(@PathParam("projectId") int projectId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.delete")); - } - dalFacade.unFollowProject(internalUserId, projectId); - Project project = dalFacade.getProjectById(projectId); - Gson gson = new Gson(); - bazaarService.getNotificationDispatcher().dispatchNotification(this, new Date(), Activity.ActivityAction.UNFOLLOW, project.getId(), - Activity.DataType.PROJECT, 0, null, internalUserId); - return new HttpResponse(gson.toJson(project), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method removes the current user from a followers list of a given project. + * + * @param projectId id of the project + * @return Response with project as a JSON object. + */ + @DELETE + @Path("/{projectId}/followers") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method removes the current user from a followers list of a given project.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the project"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response removeUserFromFollowers(@PathParam("projectId") int projectId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.delete")); + } + dalFacade.unFollowProject(internalUserId, projectId); + Project project = dalFacade.getProjectById(projectId); + Gson gson = new Gson(); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, new Date(), Activity.ActivityAction.UNFOLLOW, project.getId(), + Activity.DataType.PROJECT, 0, null, internalUserId); + return Response.ok(gson.toJson(project)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method returns the list of components under a given project. - * - * @param projectId id of the project - * @param page page number - * @param perPage number of projects by page - * @return Response with components as a JSON array. - */ - @GET - @Path("/{projectId}/components") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method returns the list of components under a given project.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of components for a given project"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse getComponentsByProject( - @PathParam("projectId") int projectId, - @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, - @ApiParam(value = "Elements of components by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - Gson gson = new Gson(); - PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>()); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - if (dalFacade.getProjectById(projectId) == null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "component")); - } - if (dalFacade.isProjectPublic(projectId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMPONENT, String.valueOf(projectId), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + /** + * This method returns the list of components under a given project. + * + * @param projectId id of the project + * @param page page number + * @param perPage number of projects by page + * @return Response with components as a JSON array. + */ + @GET + @Path("/{projectId}/components") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method returns the list of components under a given project.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of components for a given project"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getComponentsByProject( + @PathParam("projectId") int projectId, + @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, + @ApiParam(value = "Elements of components by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); } - } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMPONENT, String.valueOf(projectId), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.read")); + Gson gson = new Gson(); + PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>()); + Vtor vtor = service.bazaarService.getValidators(); + vtor.validate(pageInfo); + if (vtor.hasViolations()) { + ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); } - } - PaginationResult componentsResult = dalFacade.listComponentsByProjectId(projectId, pageInfo); + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + if (dalFacade.getProjectById(projectId) == null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "component")); + } + if (dalFacade.isProjectPublic(projectId)) { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMPONENT, String.valueOf(projectId), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + } else { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMPONENT, String.valueOf(projectId), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.read")); + } + } + PaginationResult componentsResult = dalFacade.listComponentsByProjectId(projectId, pageInfo); + + Map parameter = new HashMap<>(); + parameter.put("page", String.valueOf(page)); + parameter.put("per_page", String.valueOf(perPage)); - HttpResponse response = new HttpResponse(gson.toJson(componentsResult.getElements()), HttpURLConnection.HTTP_OK); - Map parameter = new HashMap<>(); - parameter.put("page", String.valueOf(page)); - parameter.put("per_page", String.valueOf(perPage)); - response = bazaarService.addPaginationToHtppResponse(componentsResult, "projects/" + String.valueOf(projectId) + "/components", parameter, response); + Response.ResponseBuilder responseBuilder = Response.ok(); + responseBuilder = responseBuilder.entity(gson.toJson(componentsResult.getElements())); + responseBuilder = service.bazaarService.paginationLinks(responseBuilder, componentsResult, "projects/" + String.valueOf(projectId) + "/components", parameter); + responseBuilder = service.bazaarService.xHeaderFields(responseBuilder, componentsResult); + Response response = responseBuilder.build(); - return response; - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + return response; + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method returns the list of requirements for a specific project. - * - * @param projectId id of the project to retrieve requirements for - * @param page page number - * @param perPage number of projects by page - * @return Response with requirements as a JSON array. - */ - @GET - @Path("/{projectId}/requirements") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method returns the list of requirements for a specific project.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of requirements for a given project"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse getRequirementsByProject(@PathParam("projectId") int projectId, + /** + * This method returns the list of requirements for a specific project. + * + * @param projectId id of the project to retrieve requirements for + * @param page page number + * @param perPage number of projects by page + * @return Response with requirements as a JSON array. + */ + @GET + @Path("/{projectId}/requirements") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method returns the list of requirements for a specific project.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of requirements for a given project"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getRequirementsByProject(@PathParam("projectId") int projectId, @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, @ApiParam(value = "Elements of requirements by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage, @ApiParam(value = "State filter", required = false, allowableValues = "all,open,realized") @DefaultValue("all") @QueryParam("state") String stateFilter) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - Gson gson = new Gson(); - HashMap filters = new HashMap<>(); - if (stateFilter != "all") { - filters.put("realized", stateFilter); - } - PageInfo pageInfo = new PageInfo(page, perPage, filters); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - if (dalFacade.getProjectById(projectId) == null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "ressource")); - } - if (dalFacade.isProjectPublic(projectId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, String.valueOf(projectId), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); } - } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_REQUIREMENT, String.valueOf(projectId), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.read")); + Gson gson = new Gson(); + HashMap filters = new HashMap<>(); + if (stateFilter != "all") { + filters.put("realized", stateFilter); } - } - PaginationResult requirementsResult = dalFacade.listRequirementsByProject(projectId, pageInfo, internalUserId); + PageInfo pageInfo = new PageInfo(page, perPage, filters); + Vtor vtor = service.bazaarService.getValidators(); + vtor.validate(pageInfo); + if (vtor.hasViolations()) { + ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + if (dalFacade.getProjectById(projectId) == null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "ressource")); + } + if (dalFacade.isProjectPublic(projectId)) { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, String.valueOf(projectId), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + } else { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_REQUIREMENT, String.valueOf(projectId), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.read")); + } + } + PaginationResult requirementsResult = dalFacade.listRequirementsByProject(projectId, pageInfo, internalUserId); + + Map parameter = new HashMap<>(); + parameter.put("page", String.valueOf(page)); + parameter.put("per_page", String.valueOf(perPage)); - HttpResponse response = new HttpResponse(gson.toJson(requirementsResult.getElements()), HttpURLConnection.HTTP_OK); - Map parameter = new HashMap<>(); - parameter.put("page", String.valueOf(page)); - parameter.put("per_page", String.valueOf(perPage)); - response = bazaarService.addPaginationToHtppResponse(requirementsResult, "projects/" + String.valueOf(projectId) + "/requirements", parameter, response); + Response.ResponseBuilder responseBuilder = Response.ok(); + responseBuilder = responseBuilder.entity(gson.toJson(requirementsResult.getElements())); + responseBuilder = service.bazaarService.paginationLinks(responseBuilder, requirementsResult, "projects/" + String.valueOf(projectId) + "/requirements", parameter); + responseBuilder = service.bazaarService.xHeaderFields(responseBuilder, requirementsResult); + Response response = responseBuilder.build(); - return response; - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + return response; + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } + } } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/RequirementsResource.java b/src/main/de/rwth/dbis/acis/bazaar/service/RequirementsResource.java index b9a54e4f..4236b6ff 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/RequirementsResource.java +++ b/src/main/de/rwth/dbis/acis/bazaar/service/RequirementsResource.java @@ -1,6 +1,5 @@ package de.rwth.dbis.acis.bazaar.service; - import com.google.gson.Gson; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.*; @@ -13,785 +12,796 @@ import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; -import i5.las2peer.api.Service; -import i5.las2peer.restMapper.HttpResponse; -import i5.las2peer.restMapper.MediaType; -import i5.las2peer.restMapper.RESTMapper; -import i5.las2peer.restMapper.annotations.ContentParam; +import i5.las2peer.api.Context; +import i5.las2peer.restMapper.RESTService; +import i5.las2peer.restMapper.annotations.ServicePath; import i5.las2peer.security.UserAgent; import io.swagger.annotations.*; import jodd.vtor.Violation; import jodd.vtor.Vtor; import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import java.net.HttpURLConnection; import java.util.*; -@Path("/bazaar/requirements") -@Api(value = "/requirements", description = "Requirements resource") -public class RequirementsResource extends Service { - private BazaarService bazaarService; +@ServicePath("/bazaar/requirements") +public class RequirementsResource extends RESTService { - /** - * This method is needed for every RESTful application in LAS2peer. - * - * @return the mapping to the REST interface. - */ - public String getRESTMapping() { - String result = ""; - try { - result = RESTMapper.getMethodsAsXML(this.getClass()); - } catch (Exception e) { + private BazaarService bazaarService; - e.printStackTrace(); - } - return result; + @Override + protected void initResources() { + getResourceConfig().register(RequirementsResource.Resource.class); } public RequirementsResource() throws Exception { bazaarService = new BazaarService(); } - /** - * This method returns a specific requirement. - * - * @param requirementId id of the requirement to retrieve - * @return Response with requirement as a JSON object. - */ - @GET - @Path("/{requirementId}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method returns a specific requirement.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain requirement"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse getRequirement(@PathParam("requirementId") int requirementId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - RequirementEx requirement = dalFacade.getRequirementById(requirementId, internalUserId); - if (dalFacade.isRequirementPublic(requirementId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, String.valueOf(requirement.getProjectId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + @Path("/") + public static class Resource { + + private final RequirementsResource service = (RequirementsResource) Context.getCurrent().getService(); + + /** + * This method returns a specific requirement. + * + * @param requirementId id of the requirement to retrieve + * @return Response with requirement as a JSON object. + */ + @GET + @Path("/{requirementId}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method returns a specific requirement.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain requirement"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getRequirement(@PathParam("requirementId") int requirementId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); } - } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_REQUIREMENT, String.valueOf(requirement.getProjectId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.read")); + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + RequirementEx requirement = dalFacade.getRequirementById(requirementId, internalUserId); + if (dalFacade.isRequirementPublic(requirementId)) { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, String.valueOf(requirement.getProjectId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + } else { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_REQUIREMENT, String.valueOf(requirement.getProjectId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.component.read")); + } } + Gson gson = new Gson(); + return Response.ok(gson.toJson(requirement)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - Gson gson = new Gson(); - return new HttpResponse(gson.toJson(requirement), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); - } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method allows to create a new requirement. - * - * @param requirement requirement as a JSON object - * @return Response with the created requirement as a JSON object. - */ - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to create a new requirement.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the created requirement"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse createRequirement(@ApiParam(value = "Requirement entity as JSON", required = true) @ContentParam String requirement) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - // TODO: check whether the current user may create a new requirement - dalFacade = bazaarService.getDBConnection(); - Gson gson = new Gson(); - Requirement requirementToCreate = gson.fromJson(requirement, Requirement.class); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - requirementToCreate.setCreatorId(internalUserId); - if (requirementToCreate.getLeadDeveloperId() == 0) { - requirementToCreate.setLeadDeveloperId(1); - } - Vtor vtor = bazaarService.getValidators(); - vtor.useProfiles("create"); - vtor.validate(requirementToCreate); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } - vtor.resetProfiles(); + /** + * This method allows to create a new requirement. + * + * @param requirement requirement as a JSON object + * @return Response with the created requirement as a JSON object. + */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to create a new requirement.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the created requirement"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response createRequirement(@ApiParam(value = "Requirement entity as JSON", required = true) String requirement) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors =service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + // TODO: check whether the current user may create a new requirement + dalFacade = service.bazaarService.getDBConnection(); + Gson gson = new Gson(); + Requirement requirementToCreate = gson.fromJson(requirement, Requirement.class); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + requirementToCreate.setCreatorId(internalUserId); + if (requirementToCreate.getLeadDeveloperId() == 0) { + requirementToCreate.setLeadDeveloperId(1); + } + Vtor vtor = service.bazaarService.getValidators(); + vtor.useProfiles("create"); + vtor.validate(requirementToCreate); + if (vtor.hasViolations()) { + ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + } + vtor.resetProfiles(); - // check if all components are in the same project - for (Component component : requirementToCreate.getComponents()) { - component = dalFacade.getComponentById(component.getId()); - if (requirementToCreate.getProjectId() != component.getProjectId()) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.VALIDATION, "Component does not fit with project"); + // check if all components are in the same project + for (Component component : requirementToCreate.getComponents()) { + component = dalFacade.getComponentById(component.getId()); + if (requirementToCreate.getProjectId() != component.getProjectId()) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.VALIDATION, "Component does not fit with project"); + } } - } - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_REQUIREMENT, String.valueOf(requirementToCreate.getProjectId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.create")); - } - Requirement createdRequirement = dalFacade.createRequirement(requirementToCreate, internalUserId); - dalFacade.followRequirement(internalUserId, createdRequirement.getId()); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_REQUIREMENT, String.valueOf(requirementToCreate.getProjectId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.create")); + } + Requirement createdRequirement = dalFacade.createRequirement(requirementToCreate, internalUserId); + dalFacade.followRequirement(internalUserId, createdRequirement.getId()); - // check if attachments are given - if (requirementToCreate.getAttachments() != null && !requirementToCreate.getAttachments().isEmpty()) { - for (Attachment attachment : requirementToCreate.getAttachments()) { - attachment.setCreatorId(internalUserId); - attachment.setRequirementId(createdRequirement.getId()); - vtor.validate(attachment); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + // check if attachments are given + if (requirementToCreate.getAttachments() != null && !requirementToCreate.getAttachments().isEmpty()) { + for (Attachment attachment : requirementToCreate.getAttachments()) { + attachment.setCreatorId(internalUserId); + attachment.setRequirementId(createdRequirement.getId()); + vtor.validate(attachment); + if (vtor.hasViolations()) { + ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + } + vtor.resetProfiles(); + dalFacade.createAttachment(attachment); } - vtor.resetProfiles(); - dalFacade.createAttachment(attachment); } - } - createdRequirement = dalFacade.getRequirementById(createdRequirement.getId(), internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(this, createdRequirement.getCreation_time(), Activity.ActivityAction.CREATE, createdRequirement.getId(), - Activity.DataType.REQUIREMENT, createdRequirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); - return new HttpResponse(gson.toJson(createdRequirement), HttpURLConnection.HTTP_CREATED); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + createdRequirement = dalFacade.getRequirementById(createdRequirement.getId(), internalUserId); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, createdRequirement.getCreation_time(), Activity.ActivityAction.CREATE, createdRequirement.getId(), + Activity.DataType.REQUIREMENT, createdRequirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); + return Response.status(Response.Status.CREATED).entity(gson.toJson(createdRequirement)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method updates a specific requirement within a project and component. - * - * @param requirementId id of the requirement to update - * @param requirement requirement as a JSON object - * @return Response with updated requirement as a JSON object. - */ - @PUT - @Path("/{requirementId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method updates a specific requirement.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the updated requirement"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse updateRequirement(@PathParam("requirementId") int requirementId, - @ApiParam(value = "Requirement entity as JSON", required = true) @ContentParam String requirement) { - DALFacade dalFacade = null; - try { - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - long userId = ((UserAgent) getActiveAgent()).getId(); - Gson gson = new Gson(); - Requirement requirementToUpdate = gson.fromJson(requirement, Requirement.class); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(requirementToUpdate); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.modify")); - } - if (requirementToUpdate.getId() != 0 && requirementId != requirementToUpdate.getId()) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, "Id does not match"); - } - dalFacade.followRequirement(internalUserId, requirementToUpdate.getId()); - RequirementEx updatedRequirement = dalFacade.modifyRequirement(requirementToUpdate, internalUserId); - if (requirementToUpdate.getRealized() == null) { - bazaarService.getNotificationDispatcher().dispatchNotification(this, updatedRequirement.getLastupdated_time(), Activity.ActivityAction.UPDATE, updatedRequirement.getId(), - Activity.DataType.REQUIREMENT, updatedRequirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); - } else { - bazaarService.getNotificationDispatcher().dispatchNotification(this, updatedRequirement.getLastupdated_time(), Activity.ActivityAction.REALIZE, updatedRequirement.getId(), - Activity.DataType.REQUIREMENT, updatedRequirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); - } - return new HttpResponse(gson.toJson(updatedRequirement), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method updates a specific requirement within a project and component. + * + * @param requirementId id of the requirement to update + * @param requirement requirement as a JSON object + * @return Response with updated requirement as a JSON object. + */ + @PUT + @Path("/{requirementId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method updates a specific requirement.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the updated requirement"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response updateRequirement(@PathParam("requirementId") int requirementId, + @ApiParam(value = "Requirement entity as JSON", required = true) String requirement) { + DALFacade dalFacade = null; + try { + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + Gson gson = new Gson(); + Requirement requirementToUpdate = gson.fromJson(requirement, Requirement.class); + Vtor vtor = service.bazaarService.getValidators(); + vtor.validate(requirementToUpdate); + if (vtor.hasViolations()) { + ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.modify")); + } + if (requirementToUpdate.getId() != 0 && requirementId != requirementToUpdate.getId()) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, "Id does not match"); + } + dalFacade.followRequirement(internalUserId, requirementToUpdate.getId()); + RequirementEx updatedRequirement = dalFacade.modifyRequirement(requirementToUpdate, internalUserId); + if (requirementToUpdate.getRealized() == null) { + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, updatedRequirement.getLastupdated_time(), Activity.ActivityAction.UPDATE, updatedRequirement.getId(), + Activity.DataType.REQUIREMENT, updatedRequirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); + } else { + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, updatedRequirement.getLastupdated_time(), Activity.ActivityAction.REALIZE, updatedRequirement.getId(), + Activity.DataType.REQUIREMENT, updatedRequirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); + } + return Response.ok(gson.toJson(updatedRequirement)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method deletes a specific requirement. - * - * @param requirementId id of the requirement to delete - * @return Response with the deleted requirement as a JSON object. - */ - @DELETE - @Path("/{requirementId}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method deletes a specific requirement.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the deleted requirement"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse deleteRequirement(@PathParam("requirementId") int requirementId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - RequirementEx requirementToDelete = dalFacade.getRequirementById(requirementId, internalUserId); - Project project = dalFacade.getProjectById(requirementToDelete.getProjectId()); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, Arrays.asList(String.valueOf(project.getId()), String.valueOf(requirementId)), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.delete")); - } - Gson gson = new Gson(); - RequirementEx deletedRequirement = dalFacade.deleteRequirementById(requirementId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(this, deletedRequirement.getLastupdated_time(), Activity.ActivityAction.DELETE, deletedRequirement.getId(), - Activity.DataType.REQUIREMENT, deletedRequirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); - return new HttpResponse(gson.toJson(deletedRequirement), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method deletes a specific requirement. + * + * @param requirementId id of the requirement to delete + * @return Response with the deleted requirement as a JSON object. + */ + @DELETE + @Path("/{requirementId}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method deletes a specific requirement.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the deleted requirement"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response deleteRequirement(@PathParam("requirementId") int requirementId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + RequirementEx requirementToDelete = dalFacade.getRequirementById(requirementId, internalUserId); + Project project = dalFacade.getProjectById(requirementToDelete.getProjectId()); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, Arrays.asList(String.valueOf(project.getId()), String.valueOf(requirementId)), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.delete")); + } + Gson gson = new Gson(); + RequirementEx deletedRequirement = dalFacade.deleteRequirementById(requirementId, internalUserId); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, deletedRequirement.getLastupdated_time(), Activity.ActivityAction.DELETE, deletedRequirement.getId(), + Activity.DataType.REQUIREMENT, deletedRequirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); + return Response.ok(gson.toJson(deletedRequirement)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method add the current user to the developers list of a given requirement. - * - * @param requirementId id of the requirement - * @return Response with requirement as a JSON object. - */ - @POST - @Path("/{requirementId}/developers") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method add the current user to the developers list of a given requirement.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the requirement"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse addUserToDevelopers(@PathParam("requirementId") int requirementId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_DEVELOP, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.develop.create")); - } - dalFacade.wantToDevelop(internalUserId, requirementId); - dalFacade.followRequirement(internalUserId, requirementId); - Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(this, new Date(), Activity.ActivityAction.DEVELOP, requirement.getId(), - Activity.DataType.REQUIREMENT, requirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); - Gson gson = new Gson(); - return new HttpResponse(gson.toJson(requirement), HttpURLConnection.HTTP_CREATED); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method add the current user to the developers list of a given requirement. + * + * @param requirementId id of the requirement + * @return Response with requirement as a JSON object. + */ + @POST + @Path("/{requirementId}/developers") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method add the current user to the developers list of a given requirement.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the requirement"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response addUserToDevelopers(@PathParam("requirementId") int requirementId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_DEVELOP, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.develop.create")); + } + dalFacade.wantToDevelop(internalUserId, requirementId); + dalFacade.followRequirement(internalUserId, requirementId); + Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, new Date(), Activity.ActivityAction.DEVELOP, requirement.getId(), + Activity.DataType.REQUIREMENT, requirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); + Gson gson = new Gson(); + return Response.status(Response.Status.CREATED).entity(gson.toJson(requirement)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method remove the current user from a developers list of a given requirement. - * - * @param requirementId id of the requirement - * @return Response with requirement as a JSON object. - */ - @DELETE - @Path("/{requirementId}/developers") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method remove the current user from a developers list of a given requirement.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the requirement"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse removeUserFromDevelopers(@PathParam("requirementId") int requirementId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_DEVELOP, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.develop.delete")); - } - dalFacade.notWantToDevelop(internalUserId, requirementId); - Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - Gson gson = new Gson(); - bazaarService.getNotificationDispatcher().dispatchNotification(this, new Date(), Activity.ActivityAction.UNDEVELOP, requirement.getId(), - Activity.DataType.REQUIREMENT, requirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); - return new HttpResponse(gson.toJson(requirement), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method remove the current user from a developers list of a given requirement. + * + * @param requirementId id of the requirement + * @return Response with requirement as a JSON object. + */ + @DELETE + @Path("/{requirementId}/developers") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method remove the current user from a developers list of a given requirement.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the requirement"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response removeUserFromDevelopers(@PathParam("requirementId") int requirementId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_DEVELOP, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.develop.delete")); + } + dalFacade.notWantToDevelop(internalUserId, requirementId); + Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); + Gson gson = new Gson(); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, new Date(), Activity.ActivityAction.UNDEVELOP, requirement.getId(), + Activity.DataType.REQUIREMENT, requirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); + return Response.ok(gson.toJson(requirement)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method add the current user to the followers list of a given requirement. - * - * @param requirementId id of the requirement - * @return Response with requirement as a JSON object. - */ - @POST - @Path("/{requirementId}/followers") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method add the current user to the followers list of a given requirement.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the requirement"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse addUserToFollowers(@PathParam("requirementId") int requirementId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.create")); - } - dalFacade.followRequirement(internalUserId, requirementId); - Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - Gson gson = new Gson(); - bazaarService.getNotificationDispatcher().dispatchNotification(this, new Date(), Activity.ActivityAction.FOLLOW, requirement.getId(), - Activity.DataType.REQUIREMENT, requirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); - return new HttpResponse(gson.toJson(requirement), HttpURLConnection.HTTP_CREATED); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method add the current user to the followers list of a given requirement. + * + * @param requirementId id of the requirement + * @return Response with requirement as a JSON object. + */ + @POST + @Path("/{requirementId}/followers") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method add the current user to the followers list of a given requirement.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the requirement"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response addUserToFollowers(@PathParam("requirementId") int requirementId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.create")); + } + dalFacade.followRequirement(internalUserId, requirementId); + Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); + Gson gson = new Gson(); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, new Date(), Activity.ActivityAction.FOLLOW, requirement.getId(), + Activity.DataType.REQUIREMENT, requirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); + return Response.status(Response.Status.CREATED).entity(gson.toJson(requirement)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method removes the current user from a followers list of a given requirement. - * - * @param requirementId id of the requirement - * @return Response with requirement as a JSON object. - */ - @DELETE - @Path("/{requirementId}/followers") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method removes the current user from a followers list of a given requirement.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the requirement"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse removeUserFromFollowers(@PathParam("requirementId") int requirementId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.delete")); - } - dalFacade.unFollowRequirement(internalUserId, requirementId); - Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - Gson gson = new Gson(); - bazaarService.getNotificationDispatcher().dispatchNotification(this, new Date(), Activity.ActivityAction.UNFOLLOW, requirement.getId(), - Activity.DataType.REQUIREMENT, requirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); - return new HttpResponse(gson.toJson(requirement), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method removes the current user from a followers list of a given requirement. + * + * @param requirementId id of the requirement + * @return Response with requirement as a JSON object. + */ + @DELETE + @Path("/{requirementId}/followers") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method removes the current user from a followers list of a given requirement.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the requirement"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response removeUserFromFollowers(@PathParam("requirementId") int requirementId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.delete")); + } + dalFacade.unFollowRequirement(internalUserId, requirementId); + Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); + Gson gson = new Gson(); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, new Date(), Activity.ActivityAction.UNFOLLOW, requirement.getId(), + Activity.DataType.REQUIREMENT, requirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); + return Response.ok(gson.toJson(requirement)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method creates a vote for the given requirement in the name of the current user. - * - * @param requirementId id of the requirement - * @param direction "up" or "down" vote direction - * @return Response with requirement as a JSON object. - */ - @POST - @Path("/{requirementId}/vote") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method creates a vote for the given requirement in the name of the current user.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the requirement"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse addVote(@PathParam("requirementId") int requirementId, + /** + * This method creates a vote for the given requirement in the name of the current user. + * + * @param requirementId id of the requirement + * @param direction "up" or "down" vote direction + * @return Response with requirement as a JSON object. + */ + @POST + @Path("/{requirementId}/vote") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method creates a vote for the given requirement in the name of the current user.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the requirement"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response addVote(@PathParam("requirementId") int requirementId, @ApiParam(value = "Vote direction", allowableValues = "up, down") @DefaultValue("up") @QueryParam("direction") String direction) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - if (!(direction.equals("up") || direction.equals("down"))) { - Vtor vtor = bazaarService.getValidators(); - vtor.addViolation(new Violation("Direction can only be \"up\" or \"down\"", direction, direction)); - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_VOTE, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.vote.create")); - } - dalFacade.vote(internalUserId, requirementId, direction.equals("up")); - if (direction.equals("up")) { - dalFacade.followRequirement(internalUserId, requirementId); - } - Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(this, new Date(), Activity.ActivityAction.VOTE, requirement.getId(), - Activity.DataType.REQUIREMENT, requirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); - Gson gson = new Gson(); - return new HttpResponse(gson.toJson(requirement), HttpURLConnection.HTTP_CREATED); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + if (!(direction.equals("up") || direction.equals("down"))) { + Vtor vtor = service.bazaarService.getValidators(); + vtor.addViolation(new Violation("Direction can only be \"up\" or \"down\"", direction, direction)); + ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_VOTE, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.vote.create")); + } + dalFacade.vote(internalUserId, requirementId, direction.equals("up")); + if (direction.equals("up")) { + dalFacade.followRequirement(internalUserId, requirementId); + } + Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, new Date(), Activity.ActivityAction.VOTE, requirement.getId(), + Activity.DataType.REQUIREMENT, requirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); + Gson gson = new Gson(); + return Response.status(Response.Status.CREATED).entity(gson.toJson(requirement)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method removes the vote of the given requirement made by the current user. - * - * @param requirementId id of the requirement - * @return Response with requirement as a JSON object. - */ - @DELETE - @Path("/{requirementId}/vote") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method removes the vote of the given requirement made by the current user.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the requirement"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse removeVote(@PathParam("requirementId") int requirementId) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - // TODO: check whether the current user may create a new requirement - // TODO: check whether all required parameters are entered - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_VOTE, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.vote.delete")); - } - dalFacade.unVote(internalUserId, requirementId); - Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - Gson gson = new Gson(); - bazaarService.getNotificationDispatcher().dispatchNotification(this, new Date(), Activity.ActivityAction.UNVOTE, requirement.getId(), - Activity.DataType.REQUIREMENT, requirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); - return new HttpResponse(gson.toJson(requirement), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method removes the vote of the given requirement made by the current user. + * + * @param requirementId id of the requirement + * @return Response with requirement as a JSON object. + */ + @DELETE + @Path("/{requirementId}/vote") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method removes the vote of the given requirement made by the current user.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the requirement"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response removeVote(@PathParam("requirementId") int requirementId) { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + // TODO: check whether the current user may create a new requirement + // TODO: check whether all required parameters are entered + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_VOTE, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.vote.delete")); + } + dalFacade.unVote(internalUserId, requirementId); + Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); + Gson gson = new Gson(); + service.bazaarService.getNotificationDispatcher().dispatchNotification(service, new Date(), Activity.ActivityAction.UNVOTE, requirement.getId(), + Activity.DataType.REQUIREMENT, requirement.getComponents().get(0).getId(), Activity.DataType.COMPONENT, internalUserId); + return Response.ok(gson.toJson(requirement)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method returns the list of comments for a specific requirement. - * - * @param requirementId id of the requirement - * @param page page number - * @param perPage number of projects by page - * @return Response with comments as a JSON array. - */ - @GET - @Path("/{requirementId}/comments") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method returns the list of comments for a specific requirement.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of comments for a given requirement"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse getComments(@PathParam("requirementId") int requirementId, + /** + * This method returns the list of comments for a specific requirement. + * + * @param requirementId id of the requirement + * @param page page number + * @param perPage number of projects by page + * @return Response with comments as a JSON array. + */ + @GET + @Path("/{requirementId}/comments") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method returns the list of comments for a specific requirement.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of comments for a given requirement"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getComments(@PathParam("requirementId") int requirementId, @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, @ApiParam(value = "Elements of comments by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>(), Pageable.SortDirection.ASC); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - dalFacade = bazaarService.getDBConnection(); - //Todo use requirement's projectId for serurity context, not the one sent from client - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - Project project = dalFacade.getProjectById(requirement.getProjectId()); - if (dalFacade.isRequirementPublic(requirementId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, String.valueOf(project.getId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); } - } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMMENT, String.valueOf(project.getId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.read")); + PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>(), Pageable.SortDirection.ASC); + Vtor vtor = service.bazaarService.getValidators(); + vtor.validate(pageInfo); + if (vtor.hasViolations()) ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + dalFacade = service.bazaarService.getDBConnection(); + //Todo use requirement's projectId for serurity context, not the one sent from client + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); + Project project = dalFacade.getProjectById(requirement.getProjectId()); + if (dalFacade.isRequirementPublic(requirementId)) { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, String.valueOf(project.getId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + } else { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMMENT, String.valueOf(project.getId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.read")); + } } - } - PaginationResult commentsResult = dalFacade.listCommentsByRequirementId(requirementId, pageInfo); - Gson gson = new Gson(); + PaginationResult commentsResult = dalFacade.listCommentsByRequirementId(requirementId, pageInfo); + Gson gson = new Gson(); - HttpResponse response = new HttpResponse(gson.toJson(commentsResult.getElements()), HttpURLConnection.HTTP_OK); - Map parameter = new HashMap<>(); - parameter.put("page", String.valueOf(page)); - parameter.put("per_page", String.valueOf(perPage)); - response = bazaarService.addPaginationToHtppResponse(commentsResult, "requirements/" + String.valueOf(requirementId) + "/comments", parameter, response); + Map parameter = new HashMap<>(); + parameter.put("page", String.valueOf(page)); + parameter.put("per_page", String.valueOf(perPage)); - return response; + Response.ResponseBuilder responseBuilder = Response.ok(); + responseBuilder = responseBuilder.entity(gson.toJson(commentsResult.getElements())); + responseBuilder = service.bazaarService.paginationLinks(responseBuilder, commentsResult, "requirements/" + String.valueOf(requirementId) + "/comments", parameter); + responseBuilder = service.bazaarService.xHeaderFields(responseBuilder, commentsResult); + Response response = responseBuilder.build(); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + return response; + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method returns the list of attachments for a specific requirement. - * - * @param requirementId id of the requirement - * @param page page number - * @param perPage number of projects by page - * @return Response with comments as a JSON array. - */ - @GET - @Path("/{requirementId}/attachments") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method returns the list of attachments for a specific requirement.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of attachments for a given requirement"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse getAttachments(@PathParam("requirementId") int requirementId, + /** + * This method returns the list of attachments for a specific requirement. + * + * @param requirementId id of the requirement + * @param page page number + * @param perPage number of projects by page + * @return Response with comments as a JSON array. + */ + @GET + @Path("/{requirementId}/attachments") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method returns the list of attachments for a specific requirement.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of attachments for a given requirement"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getAttachments(@PathParam("requirementId") int requirementId, @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, @ApiParam(value = "Elements of comments by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>(), Pageable.SortDirection.ASC); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - dalFacade = bazaarService.getDBConnection(); - //Todo use requirement's projectId for serurity context, not the one sent from client - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - Project project = dalFacade.getProjectById(requirement.getProjectId()); - if (dalFacade.isRequirementPublic(requirementId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, String.valueOf(project.getId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); } - } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMMENT, String.valueOf(project.getId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.read")); + PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>(), Pageable.SortDirection.ASC); + Vtor vtor = service.bazaarService.getValidators(); + vtor.validate(pageInfo); + if (vtor.hasViolations()) ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + dalFacade = service.bazaarService.getDBConnection(); + //Todo use requirement's projectId for serurity context, not the one sent from client + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); + Project project = dalFacade.getProjectById(requirement.getProjectId()); + if (dalFacade.isRequirementPublic(requirementId)) { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, String.valueOf(project.getId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + } else { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMMENT, String.valueOf(project.getId()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.read")); + } } - } - PaginationResult attachmentsResult = dalFacade.listAttachmentsByRequirementId(requirementId, pageInfo); - Gson gson = new Gson(); + PaginationResult attachmentsResult = dalFacade.listAttachmentsByRequirementId(requirementId, pageInfo); + Gson gson = new Gson(); - HttpResponse response = new HttpResponse(gson.toJson(attachmentsResult.getElements()), HttpURLConnection.HTTP_OK); - Map parameter = new HashMap<>(); - parameter.put("page", String.valueOf(page)); - parameter.put("per_page", String.valueOf(perPage)); - response = bazaarService.addPaginationToHtppResponse(attachmentsResult, "requirements/" + String.valueOf(requirementId) + "/attachments", parameter, response); + Map parameter = new HashMap<>(); + parameter.put("page", String.valueOf(page)); + parameter.put("per_page", String.valueOf(perPage)); - return response; - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + Response.ResponseBuilder responseBuilder = Response.ok(); + responseBuilder = responseBuilder.entity(gson.toJson(attachmentsResult.getElements())); + responseBuilder = service.bazaarService.paginationLinks(responseBuilder, attachmentsResult, "requirements/" + String.valueOf(requirementId) + "/attachments", parameter); + responseBuilder = service.bazaarService.xHeaderFields(responseBuilder, attachmentsResult); + Response response = responseBuilder.build(); + + return response; + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } } - } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/UsersResource.java b/src/main/de/rwth/dbis/acis/bazaar/service/UsersResource.java index 314b7a19..92276df6 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/UsersResource.java +++ b/src/main/de/rwth/dbis/acis/bazaar/service/UsersResource.java @@ -7,189 +7,183 @@ import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; -import i5.las2peer.api.Service; -import i5.las2peer.restMapper.HttpResponse; -import i5.las2peer.restMapper.MediaType; -import i5.las2peer.restMapper.RESTMapper; -import i5.las2peer.restMapper.annotations.ContentParam; +import i5.las2peer.api.Context; +import i5.las2peer.restMapper.RESTService; +import i5.las2peer.restMapper.annotations.ServicePath; import i5.las2peer.security.UserAgent; import io.swagger.annotations.*; import jodd.vtor.Vtor; import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import java.net.HttpURLConnection; import java.util.EnumSet; -@Path("/bazaar/users") -@Api(value = "/users", description = "Users resource") -public class UsersResource extends Service { +@ServicePath("/bazaar/users") +public class UsersResource extends RESTService { private BazaarService bazaarService; - /** - * This method is needed for every RESTful application in LAS2peer. - * - * @return the mapping to the REST interface. - */ - public String getRESTMapping() { - String result = ""; - try { - result = RESTMapper.getMethodsAsXML(this.getClass()); - } catch (Exception e) { - - e.printStackTrace(); - } - return result; + @Override + protected void initResources() { + getResourceConfig().register(UsersResource.Resource.class); } public UsersResource() throws Exception { bazaarService = new BazaarService(); } - /** - * This method allows to retrieve a certain user. - * - * @param userId the id of the user to be returned - * @return Response with user as a JSON object. - */ - @GET - @Path("/{userId}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to retrieve a certain user.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain user"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse getUser(@PathParam("userId") int userId) { - DALFacade dalFacade = null; - try { - // TODO: check whether the current user may request this project - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - User user = dalFacade.getUserById(userId); - Gson gson = new Gson(); - return new HttpResponse(gson.toJson(user), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + @Path("/") + public static class Resource { + + private final UsersResource service = (UsersResource) Context.getCurrent().getService(); + + /** + * This method allows to retrieve a certain user. + * + * @param userId the id of the user to be returned + * @return Response with user as a JSON object. + */ + @GET + @Path("/{userId}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to retrieve a certain user.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain user"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getUser(@PathParam("userId") int userId) { + DALFacade dalFacade = null; + try { + // TODO: check whether the current user may request this project + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + dalFacade = service.bazaarService.getDBConnection(); + User user = dalFacade.getUserById(userId); + Gson gson = new Gson(); + return Response.ok(gson.toJson(user)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * Allows to update a certain user. - * - * @param userId id of the user to update - * @param user updated user as a JSON object - * @return Response with the updated user as a JSON object. - */ - @PUT - @Path("/{userId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to update the user profile.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the updated user"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse updateUser(@PathParam("userId") int userId, - @ApiParam(value = "User entity as JSON", required = true) @ContentParam String user) { - DALFacade dalFacade = null; - try { - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + /** + * Allows to update a certain user. + * + * @param userId id of the user to update + * @param user updated user as a JSON object + * @return Response with the updated user as a JSON object. + */ + @PUT + @Path("/{userId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to update the user profile.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the updated user"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response updateUser(@PathParam("userId") int userId, + @ApiParam(value = "User entity as JSON", required = true) String user) { + DALFacade dalFacade = null; + try { + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + Gson gson = new Gson(); + User userToUpdate = gson.fromJson(user, User.class); + Vtor vtor = service.bazaarService.getValidators(); + vtor.validate(userToUpdate); + if (vtor.hasViolations()) { + ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(agent.getId()); + if (!internalUserId.equals(userId)) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, + "UserId is not identical with user sending this request."); + } + User updatedUser = dalFacade.modifyUser(userToUpdate); + return Response.ok(gson.toJson(updatedUser)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - long useragentId = ((UserAgent) getActiveAgent()).getId(); - Gson gson = new Gson(); - User userToUpdate = gson.fromJson(user, User.class); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(userToUpdate); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(useragentId); - if(!internalUserId.equals(userId)) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, - "UserId is not identical with user sending this request."); - } - User updatedUser = dalFacade.modifyUser(userToUpdate); - return new HttpResponse(gson.toJson(updatedUser), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); - } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } - } - /** - * This method allows to retrieve the active user. - * - * @return Response with active user as a JSON object. - */ - @GET - @Path("/me") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to retrieve the active user.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the active user"), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public HttpResponse getActiveUser() { - DALFacade dalFacade = null; - try { - long userId = ((UserAgent) getActiveAgent()).getId(); - String registratorErrors = bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registratorErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - User user = dalFacade.getUserById(internalUserId); - Gson gson = new Gson(); - return new HttpResponse(gson.toJson(user), HttpURLConnection.HTTP_OK); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_UNAUTHORIZED); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_NOT_FOUND); - } else { - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bex), HttpURLConnection.HTTP_INTERNAL_ERROR); + /** + * This method allows to retrieve the active user. + * + * @return Response with active user as a JSON object. + */ + @GET + @Path("/me") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to retrieve the active user.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the active user"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getActiveUser() { + DALFacade dalFacade = null; + try { + UserAgent agent = (UserAgent) Context.getCurrent().getMainAgent(); + long userId = agent.getId(); + String registratorErrors = service.bazaarService.notifyRegistrators(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registratorErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registratorErrors); + } + dalFacade = service.bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + User user = dalFacade.getUserById(internalUserId); + Gson gson = new Gson(); + return Response.ok(gson.toJson(user)).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + service.bazaarService.closeDBConnection(dalFacade); } - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ""); - return new HttpResponse(ExceptionHandler.getInstance().toJSON(bazaarException), HttpURLConnection.HTTP_INTERNAL_ERROR); - } finally { - bazaarService.closeDBConnection(dalFacade); } } - } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/notification/ActivityDispatcher.java b/src/main/de/rwth/dbis/acis/bazaar/service/notification/ActivityDispatcher.java index d8656252..d623ac66 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/notification/ActivityDispatcher.java +++ b/src/main/de/rwth/dbis/acis/bazaar/service/notification/ActivityDispatcher.java @@ -11,13 +11,15 @@ import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import i5.las2peer.api.Service; -import i5.las2peer.restMapper.HttpResponse; -import i5.las2peer.security.Context; +import org.apache.http.HttpResponse; +import javax.ws.rs.core.Response; import java.io.Serializable; import java.net.HttpURLConnection; import java.util.Date; +import static i5.las2peer.api.Context.getCurrent; + /** * Created by martin on 15.02.2016. */ @@ -89,13 +91,14 @@ public void sendActivityOverRMI(Service service, Date creationTime, Activity.Act } activityBuilder = activityBuilder.userUrl(baseURL + "users" + "/" + String.valueOf(userId)); Activity activity = activityBuilder.build(); - Object result = service.invokeServiceMethod(activityTrackerService, - "createActivity", new Serializable[]{gson.toJson(activity)}); - if (((HttpResponse) result).getStatus() != HttpURLConnection.HTTP_CREATED) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.NETWORK, ErrorCode.RMI_ERROR, ""); + + Object result = service.getContext().invoke(activityTrackerService, "createActivity", new Serializable[]{gson.toJson(activity)}); + if (!(result).equals(new Integer(Response.Status.CREATED.getStatusCode()).toString())) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.NETWORK, ErrorCode.RMI_ERROR, "ActivityTracker RMI call failed"); } } catch (Exception ex) { - Context.logError(this, "Could not send activity with RMI call to ActivityTracker"); + //TODO log + System.out.println(ex.getMessage()); } } } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/notification/EmailDispatcher.java b/src/main/de/rwth/dbis/acis/bazaar/service/notification/EmailDispatcher.java index 0842d827..4f2fa8da 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/notification/EmailDispatcher.java +++ b/src/main/de/rwth/dbis/acis/bazaar/service/notification/EmailDispatcher.java @@ -4,7 +4,6 @@ import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.*; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; -import i5.las2peer.security.Context; import javax.mail.*; import javax.mail.internet.InternetAddress; @@ -144,7 +143,7 @@ public void sendEmailNotification(Date creationTime, Activity.ActivityAction act Transport.send(mailMessage); } } catch (Exception e) { - Context.logError(this, e.getMessage()); + //TODO log } } }