This is an automated email from the git hooks/post-receive script. New commit to branch develop in repository pollen. See https://gitlab.nuiton.org/chorem/pollen.git commit 3e2687fe652717c0283e6c4bca9931bd0d86620c Author: Sylvain Bavencoff <bavencoff@codelutin.com> Date: Thu Jul 13 12:10:37 2017 +0200 migration d'API REST vers Resteasy --- pollen-rest-api/pom.xml | 33 ++- .../org/chorem/pollen/rest/api/JsonHelper.java | 249 --------------------- .../org/chorem/pollen/rest/api/PollenRender.java | 78 ------- .../chorem/pollen/rest/api/PollenRenderError.java | 46 ---- .../pollen/rest/api/PollenRestApiApplication.java | 74 ++++++ .../rest/api/PollenRestApiApplicationListener.java | 48 +--- .../rest/api/PollenRestApiRequestContext.java | 76 ------- .../rest/api/PollenRestApiRequestFilter.java | 203 ++++++++++------- .../rest/api/PollenTopiaTransactionFilter.java | 7 + .../pollen/rest/api/beans/ChangePasswordBean.java | 25 +++ .../pollen/rest/api/beans/PollCreateBean.java | 54 +++++ .../pollen/rest/api/beans/VoterListSaveBean.java | 50 +++++ .../pollen/rest/api/converter/DateConverter.java | 56 ----- .../pollen/rest/api/converter/JacksonConfig.java | 33 +++ .../rest/api/converter/JsonArrayConverter.java | 82 ------- .../pollen/rest/api/converter/JsonConverter.java | 98 -------- .../api/converter/PollenConverterProvider.java | 29 +++ .../api/converter/PollenEntityIdConverter.java | 63 ++++++ .../api/converter/PollenEntityIdDeserializer.java | 52 +++++ .../api/converter/PollenEntityIdSerializer.java | 25 +++ .../api/converter/PollenEntityRefDeserializer.java | 61 +++++ .../api/converter/PollenEntityRefSerializer.java | 29 +++ .../rest/api/converter/PollenEnumConverter.java | 54 ----- .../FavoriteListImportExceptionMapper.java | 20 ++ .../InvalidEntityLinkExceptionMapper.java | 15 ++ .../InvalidFormExceptionMapper.java | 20 ++ .../PollenAbstractExceptionMapper.java | 40 ++++ .../PollenAuthenticationExceptionMapper.java | 15 ++ ...InvalidEmailActivationTokenExceptionMapper.java | 15 ++ .../PollenInvalidPermissionExceptionMapper.java | 15 ++ .../PollenInvalidSessionTokenExceptionMapper.java | 15 ++ .../PollenUnauthorizedExceptionMapper.java | 15 ++ .../TopiaNoResultExceptionMapper.java | 15 ++ .../rest/api/injector/PollenBeanIdInjector.java | 70 ------ .../PollenRestApiRequestContextInjector.java | 53 ----- .../rest/api/injector/PollenServiceInjector.java | 55 ----- .../org/chorem/pollen/rest/api/v1/ApiUtils.java | 78 +++++++ .../org/chorem/pollen/rest/api/v1/AuthApi.java | 134 +++++++---- .../org/chorem/pollen/rest/api/v1/ChoiceApi.java | 62 ++++- .../org/chorem/pollen/rest/api/v1/CommentApi.java | 69 +++++- .../java/org/chorem/pollen/rest/api/v1/DocApi.java | 15 +- .../org/chorem/pollen/rest/api/v1/ErrorAction.java | 94 -------- .../chorem/pollen/rest/api/v1/FavoriteListApi.java | 170 ++++++++++---- .../org/chorem/pollen/rest/api/v1/PollApi.java | 144 ++++++++---- .../pollen/rest/api/v1/PollenResourceApi.java | 84 ++++--- .../chorem/pollen/rest/api/v1/PollenUserApi.java | 98 +++++--- .../org/chorem/pollen/rest/api/v1/VoteApi.java | 48 +++- .../chorem/pollen/rest/api/v1/VoteCountingApi.java | 23 +- .../pollen/rest/api/v1/VoteCountingTypeApi.java | 22 +- .../chorem/pollen/rest/api/v1/VoterListApi.java | 115 ++++++++-- pollen-rest-api/src/main/resources/mapping | 6 +- pollen-rest-api/src/main/webapp/WEB-INF/web.xml | 69 +----- .../pollen/rest/api/AbstractPollenRestApiTest.java | 92 ++++++-- .../org/chorem/pollen/rest/api/AuthApiTest.java | 36 +-- .../org/chorem/pollen/rest/api/PollApiTest.java | 98 ++++---- .../chorem/pollen/rest/api/PollenUserApiTest.java | 38 ++-- .../rest/api/converter/JsonArrayConverterTest.java | 55 ----- .../rest/api/converter/JsonConverterTest.java | 91 -------- pollen-services/pom.xml | 9 + .../services/bean/PaginationParameterBean.java | 6 + .../chorem/pollen/services/bean/PollenBean.java | 14 +- .../pollen/services/bean/PollenEntityId.java | 15 +- .../pollen/services/bean/PollenEntityRef.java | 10 - .../org/chorem/pollen/services/bean/VoteBean.java | 6 +- .../pollen/services/bean/VoteToChoiceBean.java | 6 +- .../chorem/pollen/services/bean/VoterListBean.java | 6 +- .../pollen/services/bean/VoterListMemberBean.java | 6 +- .../services/service/FavoriteListService.java | 2 +- .../services/service/NotificationService.java | 9 +- .../pollen/services/service/PollService.java | 4 +- .../pollen/services/service/PollenUserService.java | 11 +- .../pollen/services/service/VoterListService.java | 4 +- .../pollen/services/service/mail/EmailService.java | 13 +- .../services/test/FakePollenServiceContext.java | 2 + .../services/service/VoteCountingServiceTest.java | 6 +- .../src/main/web/css/custom-code-lutin.css | 59 +++++ pollen-ui-riot-js/src/main/web/js/AuthService.js | 11 +- pollen-ui-riot-js/src/main/web/js/ChoiceService.js | 22 +- .../src/main/web/js/CommentService.js | 30 +-- .../src/main/web/js/FavoriteListService.js | 32 ++- pollen-ui-riot-js/src/main/web/js/FetchService.js | 3 +- pollen-ui-riot-js/src/main/web/js/PollService.js | 26 ++- pollen-ui-riot-js/src/main/web/js/ResultService.js | 2 +- pollen-ui-riot-js/src/main/web/js/Session.js | 1 + pollen-ui-riot-js/src/main/web/js/UIHelper.js | 4 + pollen-ui-riot-js/src/main/web/js/UserService.js | 11 +- pollen-ui-riot-js/src/main/web/js/VoteService.js | 14 +- .../src/main/web/js/VoterListService.js | 14 +- .../src/main/web/tag/UserCard.tag.html | 2 +- .../web/tag/components/date-time-picker.tag.html | 4 +- .../web/tag/favoriteList/FavoriteList.tag.html | 3 +- .../web/tag/favoriteList/FavoriteLists.tag.html | 19 +- pom.xml | 37 +-- 93 files changed, 2083 insertions(+), 1869 deletions(-) diff --git a/pollen-rest-api/pom.xml b/pollen-rest-api/pom.xml index 821451ec..3597979f 100644 --- a/pollen-rest-api/pom.xml +++ b/pollen-rest-api/pom.xml @@ -92,26 +92,22 @@ </dependency> <dependency> - <groupId>org.debux.webmotion</groupId> - <artifactId>webmotion</artifactId> + <groupId>org.jboss.resteasy</groupId> + <artifactId>resteasy-jaxrs</artifactId> </dependency> <dependency> - <groupId>org.debux.webmotion</groupId> - <artifactId>webmotion-unittest</artifactId> - <exclusions> - <exclusion> - <groupId>org.apache.tomcat.embed</groupId> - <artifactId>tomcat-embed-logging-juli</artifactId> - </exclusion> - <exclusion> - <groupId>org.apache.tomcat.embed</groupId> - <artifactId>tomcat-embed-jasper</artifactId> - </exclusion> - <exclusion> - <groupId>org.eclipse.jdt.core.compiler</groupId> - <artifactId>ecj</artifactId> - </exclusion> - </exclusions> + <groupId>org.jboss.resteasy</groupId> + <artifactId>resteasy-servlet-initializer</artifactId> + </dependency> + + <dependency> + <groupId>org.jboss.resteasy</groupId> + <artifactId>resteasy-jackson2-provider</artifactId> + </dependency> + + <dependency> + <groupId>org.jboss.resteasy</groupId> + <artifactId>resteasy-multipart-provider</artifactId> </dependency> <dependency> @@ -250,7 +246,6 @@ <configuration> <path>/${defaultWebContextPath}</path> <systemProperties> - <pollen.data.directory>${defaultDbDir}</pollen.data.directory> <pollen.log.dir>${defaultLogDir}</pollen.log.dir> </systemProperties> <uriEncoding>UTF-8</uriEncoding> diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/JsonHelper.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/JsonHelper.java deleted file mode 100644 index c18d28ed..00000000 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/JsonHelper.java +++ /dev/null @@ -1,249 +0,0 @@ -package org.chorem.pollen.rest.api; - -/* - * #%L - * Pollen :: Rest Api - * %% - * Copyright (C) 2009 - 2017 Code Lutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import com.google.common.collect.Multimap; -import com.google.gson.ExclusionStrategy; -import com.google.gson.FieldAttributes; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializer; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.math.NumberUtils; -import org.chorem.pollen.services.bean.PollenEntityId; -import org.chorem.pollen.services.bean.PollenEntityRef; -import org.chorem.pollen.services.service.FavoriteListImportException; -import org.chorem.pollen.services.service.InvalidFormException; -import org.nuiton.topia.persistence.TopiaIdFactory; - -import java.lang.reflect.Type; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -/** - * Created on 5/24/14. - * - * @author Tony Chemit - dev@tchemit.fr - * @since 2.0 - */ -public class JsonHelper { - - public static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm"); - private final Gson gson; - - public JsonHelper(final TopiaIdFactory idFactory, boolean prettyPrint) { - - GsonBuilder gsonBuilder = new GsonBuilder(); - - gsonBuilder.setExclusionStrategies(new ExclusionStrategy() { - @Override - public boolean shouldSkipField(FieldAttributes f) { - return false; - } - - @Override - public boolean shouldSkipClass(Class<?> clazz) { - return clazz == Class.class; - } - }); - - gsonBuilder.registerTypeAdapter(Date.class, (JsonSerializer<Date>) (src, typeOfSrc, context) -> { - - JsonElement result; - - if (src == null) { - - result = JsonNull.INSTANCE; - - } else { - - result = new JsonPrimitive(src.getTime()); - - } - - return result; - - }); - - gsonBuilder.registerTypeAdapter(PollenEntityId.class, (JsonSerializer<PollenEntityId>) (src, typeOfSrc, context) -> { - - JsonElement result; - - if (src == null || src.getEntityId() == null) { - - result = JsonNull.INSTANCE; - - } else { - - src.encode(idFactory); - result = new JsonPrimitive(src.getReducedId()); - - } - - return result; - - }); - - gsonBuilder.registerTypeAdapter(PollenEntityRef.class, (JsonSerializer<PollenEntityRef>) (src, typeOfSrc, context) -> { - - JsonElement result; - - if (src == null || src.getEntityId() == null) { - - result = JsonNull.INSTANCE; - - } else { - - src.encode(idFactory); - - JsonObject object = new JsonObject(); - if (src.getPermission() != null) { - object.add("permission", new JsonPrimitive(src.getPermission())); - } - object.add("id", new JsonPrimitive(src.getReducedId())); - - result = object; - - } - - return result; - - }); - - gsonBuilder.registerTypeAdapter(InvalidFormException.class, (JsonSerializer<InvalidFormException>) (src, typeOfSrc, context) -> { - - - Multimap<String, String> errors = src.getErrors(); - - Map<String, Object> map = new HashMap<>(); - for (String key : errors.keySet()) { - map.put(key, errors.get(key)); - } - - return context.serialize(map); - - }); - - gsonBuilder.registerTypeAdapter(FavoriteListImportException.class, (JsonSerializer<FavoriteListImportException>) (src, typeOfSrc, context) -> { - - - String error = src.getCauseMessage(); - - Map<String, Object> map = new HashMap<>(); - map.put("error", error); - - return context.serialize(map); - - }); - - gsonBuilder.registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> { - if (NumberUtils.isCreatable(json.getAsString())) { - return new Date(json.getAsLong()); - } - try { - return SIMPLE_DATE_FORMAT.parse(json.getAsString()); - } catch (ParseException e) { - return null; - } - - }); - - gsonBuilder.registerTypeAdapter(PollenEntityId.class, (JsonDeserializer<PollenEntityId>) (json, typeOfT, context) -> { - - PollenEntityId id = PollenEntityId.newId(typeOfT); - - String asString = json.getAsString(); - - if (asString != null) { - - id.setReducedId(asString); - id.decode(idFactory); - - } - - return id; - - }); - - gsonBuilder.registerTypeAdapter(PollenEntityRef.class, (JsonDeserializer<PollenEntityRef>) (json, typeOfT, context) -> { - - String id = ((JsonObject) json).get("id").getAsString(); - String permission = ((JsonObject) json).get("permission").getAsString(); - - PollenEntityRef<?> ref = PollenEntityRef.newRef(typeOfT); - - ref.setReducedId(id); - ref.setPermission(permission); - ref.decode(idFactory); - - - return ref; - - }); - - gsonBuilder.registerTypeAdapter(Double.class, (JsonDeserializer<Double>) (json, typeOfT, context) -> { - Double result; - if (StringUtils.isEmpty(json.getAsString())) { - result = null; - } else { - result = json.getAsDouble(); - } - return result; - }); - - if (prettyPrint) { - - gsonBuilder.setPrettyPrinting(); - - } - - this.gson = gsonBuilder.create(); - - } - - public String toJson(Object model) { - - return gson.toJson(model); - - } - - public <O> O fromJson(String json, Class<O> type) { - - return gson.fromJson(json, type); - - } - - public <O> O fromJson(String json, Type type) { - - return gson.fromJson(json, type); - - } - -} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRender.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRender.java deleted file mode 100644 index aab07062..00000000 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRender.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.chorem.pollen.rest.api; - -/* - * #%L - * Pollen :: Rest Api - * %% - * Copyright (C) 2009 - 2017 Code Lutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import org.chorem.pollen.services.service.FavoriteListImportException; -import org.chorem.pollen.services.service.InvalidFormException; -import org.debux.webmotion.server.call.Call; -import org.debux.webmotion.server.call.HttpContext; -import org.debux.webmotion.server.mapping.Mapping; -import org.debux.webmotion.server.render.Render; -import org.nuiton.topia.persistence.TopiaIdFactory; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.PrintWriter; - -/** - * To render any entities. - * - * @author Tony Chemit - dev@tchemit.fr - * @since 2.0 - */ -public class PollenRender<T> extends Render { - - protected final T model; - - public PollenRender(T model) { - this.model = model; - } - - @Override - public void create(Mapping mapping, Call call) throws IOException, ServletException { - - HttpContext context = call.getContext(); - HttpServletResponse response = context.getResponse(); - response.setContentType("application/json"); - - PollenRestApiApplicationContext applicationContext = - PollenRestApiApplicationContext.getApplicationContext(context.getServletContext()); - - if (model instanceof InvalidFormException || model instanceof FavoriteListImportException) { - - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - - } - - TopiaIdFactory topiaIdFactory = applicationContext.getTopiaApplicationContext().getTopiaIdFactory(); - boolean devMode = applicationContext.getApplicationConfig().isDevMode(); - - JsonHelper gson = new JsonHelper(topiaIdFactory, devMode); - String json = gson.toJson(model); - - PrintWriter out = context.getOut(); - out.print(json); - - } - -} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRenderError.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRenderError.java deleted file mode 100644 index e64f5cf5..00000000 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRenderError.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.chorem.pollen.rest.api; - -import org.chorem.pollen.rest.api.v1.AuthApi; -import org.debux.webmotion.server.call.Call; -import org.debux.webmotion.server.call.HttpContext; -import org.debux.webmotion.server.mapping.Mapping; -import org.debux.webmotion.server.render.RenderError; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -/** - * @author Sylvain Bavencoff - bavencoff@codelutin.com - */ -public class PollenRenderError extends RenderError { - - protected boolean removeConnexionCookie; - - public PollenRenderError(int code, String message, boolean removeConnexionCookie) { - super(code, message); - this.removeConnexionCookie = removeConnexionCookie; - } - - public PollenRenderError(int code, String message) { - this(code, message, false); - } - - @Override - public void create(Mapping mapping, Call call) throws IOException, ServletException { - HttpContext context = call.getContext(); - HttpServletResponse response = context.getResponse(); - - String origin = context.getHeader("Origin"); - if (origin != null) { - response.setHeader(HttpContext.HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, origin); - response.setHeader(HttpContext.HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); - response.setHeader(HttpContext.HEADER_ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, DELETE, PUT, OPTIONS"); - } - if (removeConnexionCookie) { - AuthApi.removeAuthCookie(response); - } - - super.create(mapping,call); - } -} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRestApiApplication.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRestApiApplication.java new file mode 100644 index 00000000..f4372e95 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRestApiApplication.java @@ -0,0 +1,74 @@ +package org.chorem.pollen.rest.api; + +import com.google.common.collect.Sets; +import org.chorem.pollen.rest.api.converter.JacksonConfig; +import org.chorem.pollen.rest.api.converter.PollenConverterProvider; +import org.chorem.pollen.rest.api.exceptionMappers.FavoriteListImportExceptionMapper; +import org.chorem.pollen.rest.api.exceptionMappers.InvalidEntityLinkExceptionMapper; +import org.chorem.pollen.rest.api.exceptionMappers.InvalidFormExceptionMapper; +import org.chorem.pollen.rest.api.exceptionMappers.PollenAuthenticationExceptionMapper; +import org.chorem.pollen.rest.api.exceptionMappers.PollenInvalidEmailActivationTokenExceptionMapper; +import org.chorem.pollen.rest.api.exceptionMappers.PollenInvalidPermissionExceptionMapper; +import org.chorem.pollen.rest.api.exceptionMappers.PollenInvalidSessionTokenExceptionMapper; +import org.chorem.pollen.rest.api.exceptionMappers.PollenUnauthorizedExceptionMapper; +import org.chorem.pollen.rest.api.exceptionMappers.TopiaNoResultExceptionMapper; +import org.chorem.pollen.rest.api.v1.AuthApi; +import org.chorem.pollen.rest.api.v1.ChoiceApi; +import org.chorem.pollen.rest.api.v1.CommentApi; +import org.chorem.pollen.rest.api.v1.DocApi; +import org.chorem.pollen.rest.api.v1.FavoriteListApi; +import org.chorem.pollen.rest.api.v1.PollApi; +import org.chorem.pollen.rest.api.v1.PollenResourceApi; +import org.chorem.pollen.rest.api.v1.PollenUserApi; +import org.chorem.pollen.rest.api.v1.VoteApi; +import org.chorem.pollen.rest.api.v1.VoteCountingApi; +import org.chorem.pollen.rest.api.v1.VoteCountingTypeApi; +import org.chorem.pollen.rest.api.v1.VoterListApi; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; +import java.util.Set; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +@ApplicationPath("/v1") +public class PollenRestApiApplication extends Application { + + Set<Object> singletons; + + public PollenRestApiApplication() { + singletons = Sets.newHashSet( + new AuthApi(), + new ChoiceApi(), + new CommentApi(), + new DocApi(), + new FavoriteListApi(), + new PollApi(), + new PollenResourceApi(), + new PollenUserApi(), + new VoteApi(), + new VoteCountingApi(), + new VoteCountingTypeApi(), + new VoterListApi(), + new PollenAuthenticationExceptionMapper(), + new PollenInvalidSessionTokenExceptionMapper(), + new PollenUnauthorizedExceptionMapper(), + new PollenInvalidPermissionExceptionMapper(), + new PollenInvalidEmailActivationTokenExceptionMapper(), + new InvalidFormExceptionMapper(), + new FavoriteListImportExceptionMapper(), + new TopiaNoResultExceptionMapper(), + new InvalidEntityLinkExceptionMapper(), + new PollenRestApiRequestFilter(), + new PollenConverterProvider(), + new JacksonConfig() + ); + } + + @Override + public Set<Object> getSingletons() { + return singletons; + } + +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRestApiApplicationListener.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRestApiApplicationListener.java index 98bdc852..7d654ae4 100644 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRestApiApplicationListener.java +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRestApiApplicationListener.java @@ -24,14 +24,6 @@ package org.chorem.pollen.rest.api; import com.google.common.collect.Sets; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.chorem.pollen.persistence.entity.ChoiceType; -import org.chorem.pollen.rest.api.converter.DateConverter; -import org.chorem.pollen.rest.api.converter.JsonArrayConverter; -import org.chorem.pollen.rest.api.converter.JsonConverter; -import org.chorem.pollen.rest.api.converter.PollenEnumConverter; -import org.chorem.pollen.rest.api.injector.PollenBeanIdInjector; -import org.chorem.pollen.rest.api.injector.PollenRestApiRequestContextInjector; -import org.chorem.pollen.rest.api.injector.PollenServiceInjector; import org.chorem.pollen.services.PollenUIContext; import org.chorem.pollen.services.bean.ChildFavoriteListBean; import org.chorem.pollen.services.bean.ChoiceBean; @@ -50,10 +42,6 @@ import org.chorem.pollen.services.config.PollenServicesConfig; import org.chorem.pollen.services.job.AbstractPollenJob; import org.chorem.pollen.services.job.SendEmailInErrorsJob; import org.chorem.pollen.services.job.SendPollEndReminderJob; -import org.debux.webmotion.server.WebMotionServerListener; -import org.debux.webmotion.server.call.ServerContext; -import org.debux.webmotion.server.mapping.Mapping; -import org.nuiton.topia.persistence.TopiaIdFactory; import org.quartz.CronScheduleBuilder; import org.quartz.JobBuilder; import org.quartz.JobDataMap; @@ -64,7 +52,8 @@ import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; -import java.util.Date; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; import java.util.Set; /** @@ -73,7 +62,7 @@ import java.util.Set; * @author Tony Chemit - dev@tchemit.fr * @since 2.0 */ -public class PollenRestApiApplicationListener implements WebMotionServerListener { +public class PollenRestApiApplicationListener implements ServletContextListener { /** Logger. */ private static final Log log = LogFactory.getLog(PollenRestApiApplicationListener.class); @@ -99,37 +88,14 @@ public class PollenRestApiApplicationListener implements WebMotionServerListener private Scheduler scheduler; @Override - public void onStart(Mapping mapping, ServerContext serverContext) { - + public void contextInitialized(ServletContextEvent sce) { // --- init application context --- // PollenRestApiApplicationContext applicationContext = PollenRestApiApplicationContext.getApplicationContext(); PollenRestApiApplicationContext.setApplicationContext( - serverContext.getServletContext(), applicationContext); - - TopiaIdFactory topiaIdFactory = applicationContext.getTopiaApplicationContext().getTopiaIdFactory(); - - // --- init converters --- // - - serverContext.addConverter(new DateConverter(), Date.class); - serverContext.addConverter(new PollenEnumConverter<>(ChoiceType.class), ChoiceType.class); - - for (Class<?> beanType : BEAN_TYPES) { - - serverContext.addConverter(JsonConverter.newConverter(topiaIdFactory, beanType), beanType); - - JsonArrayConverter<?> converter = JsonArrayConverter.newConverter(topiaIdFactory, beanType); - serverContext.addConverter(converter, converter.getDefaultType()); - - } - - // --- init injectors --- // - - serverContext.addInjector(new PollenRestApiRequestContextInjector()); - serverContext.addInjector(new PollenServiceInjector()); - serverContext.addInjector(new PollenBeanIdInjector(topiaIdFactory)); + sce.getServletContext(), applicationContext); // --- init crons --- // @@ -185,7 +151,7 @@ public class PollenRestApiApplicationListener implements WebMotionServerListener } @Override - public void onStop(ServerContext serverContext) { + public void contextDestroyed(ServletContextEvent sce) { //-- close scheduler ---// if (scheduler != null) { @@ -206,7 +172,7 @@ public class PollenRestApiApplicationListener implements WebMotionServerListener // Get application context PollenRestApiApplicationContext applicationContext = PollenRestApiApplicationContext.getApplicationContext( - serverContext.getServletContext()); + sce.getServletContext()); // close it (and all underlined resources) if (applicationContext != null) { diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRestApiRequestContext.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRestApiRequestContext.java deleted file mode 100644 index 65b9ce08..00000000 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRestApiRequestContext.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.chorem.pollen.rest.api; - -/* - * #%L - * Pollen :: Rest Api - * %% - * Copyright (C) 2009 - 2017 Code Lutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import org.chorem.pollen.services.PollenServiceContext; -import org.chorem.pollen.services.PollenUIContext; -import org.chorem.pollen.services.service.security.PollenSecurityContext; -import org.chorem.pollen.services.service.security.SecurityService; -import org.debux.webmotion.server.call.HttpContext; - -/** - * Created on 4/25/14. - * - * @author Tony Chemit - dev@tchemit.fr - * @since 2.0 - */ -public class PollenRestApiRequestContext { - - protected static final String REQUEST_POLLEN_REQUEST_CONTEXT = "pollen_PollenRequestContext"; - - public static PollenRestApiRequestContext getRequestContext(HttpContext httpContext) { - - return (PollenRestApiRequestContext) - httpContext.getRequest().getAttribute(REQUEST_POLLEN_REQUEST_CONTEXT); - } - - public static void setRequestContext(HttpContext httpContext, - PollenRestApiRequestContext serviceContext) { - httpContext.getRequest().setAttribute(REQUEST_POLLEN_REQUEST_CONTEXT, serviceContext); - } - - protected PollenServiceContext serviceContext; - - public void setServiceContext(PollenServiceContext serviceContext) { - this.serviceContext = serviceContext; - } - - public PollenServiceContext getServiceContext() { - return serviceContext; - } - - public void setSecurityContext(PollenSecurityContext securityContext) { - serviceContext.setSecurityContext(securityContext); - } - - public PollenSecurityContext getSecurityContext() { - return serviceContext.getSecurityContext(); - } - - public SecurityService getSecurityService() { - return serviceContext.newService(SecurityService.class); - } - - public void setUIContext(PollenUIContext uiContext) { - serviceContext.setUIContext(uiContext); - } -} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRestApiRequestFilter.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRestApiRequestFilter.java index 83ce6fd0..ed99e59d 100644 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRestApiRequestFilter.java +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenRestApiRequestFilter.java @@ -21,145 +21,190 @@ package org.chorem.pollen.rest.api; * #L% */ -import org.apache.commons.beanutils.Converter; +import com.google.gson.Gson; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.chorem.pollen.persistence.PollenPersistenceContext; import org.chorem.pollen.persistence.entity.PollenPrincipal; import org.chorem.pollen.persistence.entity.SessionToken; +import org.chorem.pollen.rest.api.v1.AuthApi; import org.chorem.pollen.services.PollenServiceContext; import org.chorem.pollen.services.PollenUIContext; +import org.chorem.pollen.services.service.ChoiceService; +import org.chorem.pollen.services.service.CommentService; +import org.chorem.pollen.services.service.FavoriteListService; +import org.chorem.pollen.services.service.FeedService; +import org.chorem.pollen.services.service.NotificationService; +import org.chorem.pollen.services.service.PollService; +import org.chorem.pollen.services.service.PollenResourceService; +import org.chorem.pollen.services.service.PollenUIUrlRenderService; +import org.chorem.pollen.services.service.PollenUserService; +import org.chorem.pollen.services.service.ReportService; +import org.chorem.pollen.services.service.VoteCountingService; +import org.chorem.pollen.services.service.VoteCountingTypeService; +import org.chorem.pollen.services.service.VoteService; +import org.chorem.pollen.services.service.VoterListService; +import org.chorem.pollen.services.service.mail.EmailService; import org.chorem.pollen.services.service.security.PollenCypherTechnicalException; import org.chorem.pollen.services.service.security.PollenInvalidSessionTokenException; import org.chorem.pollen.services.service.security.PollenSecurityContext; import org.chorem.pollen.services.service.security.SecurityService; -import org.debux.webmotion.server.WebMotionFilter; -import org.debux.webmotion.server.call.Call; -import org.debux.webmotion.server.call.CookieManager; -import org.debux.webmotion.server.call.HttpContext; -import org.debux.webmotion.server.render.Render; -import org.debux.webmotion.server.render.RenderStatus; - -import javax.servlet.http.HttpServletResponse; +import org.jboss.resteasy.spi.ResteasyProviderFactory; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.container.PreMatching; +import javax.ws.rs.core.Cookie; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.util.List; import java.util.Locale; -import java.util.Map; import static org.chorem.pollen.rest.api.v1.AuthApi.COOKIE_POLLEN_AUTH; /** - * Inject {@link PollenRestApiRequestContext} in services. + * Inject {@link } in services. * * @author Tony Chemit - dev@tchemit.fr * @since 2.0 */ -public class PollenRestApiRequestFilter extends WebMotionFilter { +@Provider +@PreMatching +public class PollenRestApiRequestFilter implements ContainerRequestFilter, ContainerResponseFilter { private static final String HEADER_ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers"; private static final String HEADER_ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers"; + private static final String HEADER_ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin"; + private static final String HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials"; + private static final String HEADER_ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods"; + public static final String REQUEST_PERMISSION_PARAMETER = "permission"; public static final String REQUEST_HEADER_SESSION_TOKEN = "X-Pollen-Session-Token"; public static final String REQUEST_HEADER_UI_CONTEXT = "X-Pollen-UI-context"; + + /** Logger. */ private static final Log log = LogFactory.getLog(PollenRestApiRequestFilter.class); - @SuppressWarnings("unused") - public void inject(Call call, HttpContext context) throws PollenInvalidSessionTokenException, PollenCypherTechnicalException { + @Override + public void filter(ContainerRequestContext containerRequestContext) throws IOException { + try { + pushRequestContext(containerRequestContext); + } catch (PollenInvalidSessionTokenException | PollenCypherTechnicalException e) { + Response.ResponseBuilder builder = Response.status(Response.Status.UNAUTHORIZED) + .entity(e.getMessage()); + builder = AuthApi.removeAuthCookie(builder); + containerRequestContext.abortWith(builder.build()); + } + } - PollenRestApiRequestContext pollenRestApiRequestContext = prepareRequestContext(context); + @Override + public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException { - if (HttpContext.METHOD_OPTIONS.equals(context.getMethod())) { + MultivaluedMap<String, Object> headers = containerResponseContext.getHeaders(); - Render render = call.getRender(); + if (HttpMethod.OPTIONS.equals(containerRequestContext.getMethod())) { - if (render instanceof RenderStatus && HttpServletResponse.SC_OK == ((RenderStatus) render).getCode()) { + if (Response.Status.OK == containerResponseContext.getStatusInfo()) { // add CORS response headers - HttpServletResponse response = context.getResponse(); - - String requestHeaders = context.getHeader(HEADER_ACCESS_CONTROL_REQUEST_HEADERS); + String requestHeaders = containerResponseContext.getHeaderString(HEADER_ACCESS_CONTROL_REQUEST_HEADERS); if (StringUtils.isNotBlank(requestHeaders)) { - response.setHeader(HEADER_ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders); + headers.add(HEADER_ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders); } else { - response.setHeader(HEADER_ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); + headers.add(HEADER_ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, " + REQUEST_HEADER_UI_CONTEXT); } } } - HttpServletResponse response = context.getResponse(); - - String origin = context.getHeader("Origin"); + String origin = containerRequestContext.getHeaderString("Origin"); if (origin != null) { - response.setHeader(HttpContext.HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, origin); - response.setHeader(HttpContext.HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); - response.setHeader(HttpContext.HEADER_ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, DELETE, PUT, OPTIONS"); + headers.add(HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, origin); + headers.add(HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); + headers.add(HEADER_ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, DELETE, PUT, OPTIONS"); } - - doProcess(); - } - private PollenRestApiRequestContext prepareRequestContext(HttpContext context) throws PollenInvalidSessionTokenException, PollenCypherTechnicalException { + private void pushRequestContext(ContainerRequestContext context) throws PollenInvalidSessionTokenException, PollenCypherTechnicalException { Locale locale = getUserLocale(context); - PollenRestApiApplicationContext applicationContext = - PollenRestApiApplicationContext.getApplicationContext(context.getServletContext()); + PollenRestApiApplicationContext applicationContext = PollenRestApiApplicationContext.getApplicationContext(); PollenPersistenceContext persistenceContext = - PollenTopiaTransactionFilter.getPersistenceContext(context.getRequest()); + PollenTopiaTransactionFilter.getPersistenceContext(context); PollenServiceContext serviceContext = applicationContext.newServiceContext(persistenceContext, locale); - PollenRestApiRequestContext requestContext = new PollenRestApiRequestContext(); - requestContext.setServiceContext(serviceContext); - - PollenSecurityContext securityContext = createSecurityContext(context, applicationContext, requestContext); - requestContext.setSecurityContext(securityContext); - - PollenUIContext uiContext = extractUIContext(context); - requestContext.setUIContext(uiContext); - - PollenRestApiRequestContext.setRequestContext(context, requestContext); - - return requestContext; - + ResteasyProviderFactory.pushContext(PollenServiceContext.class, serviceContext); + + + PollenSecurityContext securityContext = createSecurityContext(context, applicationContext, serviceContext); + serviceContext.setSecurityContext(securityContext); + ResteasyProviderFactory.pushContext(PollenSecurityContext.class, securityContext); + + serviceContext.setUIContext(extractUIContext(context)); + + ResteasyProviderFactory.pushContext(ChoiceService.class, serviceContext.newService(ChoiceService.class)); + ResteasyProviderFactory.pushContext(CommentService.class, serviceContext.newService(CommentService.class)); + ResteasyProviderFactory.pushContext(FavoriteListService.class, serviceContext.newService(FavoriteListService.class)); + ResteasyProviderFactory.pushContext(EmailService.class, serviceContext.newService(EmailService.class)); + ResteasyProviderFactory.pushContext(NotificationService.class, serviceContext.newService(NotificationService.class)); + ResteasyProviderFactory.pushContext(FeedService.class, serviceContext.newService(FeedService.class)); + ResteasyProviderFactory.pushContext(PollService.class, serviceContext.newService(PollService.class)); + ResteasyProviderFactory.pushContext(SecurityService.class, serviceContext.newService(SecurityService.class)); + ResteasyProviderFactory.pushContext(ReportService.class, serviceContext.newService(ReportService.class)); + ResteasyProviderFactory.pushContext(PollenResourceService.class, serviceContext.newService(PollenResourceService.class)); + ResteasyProviderFactory.pushContext(PollenUIUrlRenderService.class, serviceContext.newService(PollenUIUrlRenderService.class)); + ResteasyProviderFactory.pushContext(PollenUserService.class, serviceContext.newService(PollenUserService.class)); + ResteasyProviderFactory.pushContext(VoteCountingService.class, serviceContext.newService(VoteCountingService.class)); + ResteasyProviderFactory.pushContext(VoterListService.class, serviceContext.newService(VoterListService.class)); + ResteasyProviderFactory.pushContext(VoteCountingTypeService.class, serviceContext.newService(VoteCountingTypeService.class)); + ResteasyProviderFactory.pushContext(VoteService.class, serviceContext.newService(VoteService.class)); + ResteasyProviderFactory.pushContext(PollenUserService.class, serviceContext.newService(PollenUserService.class)); } - private PollenUIContext extractUIContext(HttpContext context) { - String uiContextJson = context.getHeader(REQUEST_HEADER_UI_CONTEXT); + private PollenUIContext extractUIContext(ContainerRequestContext context) { + String uiContextJson = context.getHeaderString(REQUEST_HEADER_UI_CONTEXT); PollenUIContext uiContext = null; if (uiContextJson != null) { - Converter converter = context.getServerContext().getConverter().lookup(PollenUIContext.class); - uiContext = converter.convert(PollenUIContext.class, uiContextJson); + Gson gson = new Gson(); + uiContext = gson.fromJson(uiContextJson, PollenUIContext.class); } return uiContext; } - private PollenSecurityContext createSecurityContext(HttpContext context, + private PollenSecurityContext createSecurityContext(ContainerRequestContext context, PollenRestApiApplicationContext applicationContext, - PollenRestApiRequestContext requestContext) throws PollenInvalidSessionTokenException, PollenCypherTechnicalException { + PollenServiceContext serviceContext) throws PollenInvalidSessionTokenException, PollenCypherTechnicalException { - SecurityService securityService = requestContext.getSecurityService(); + SecurityService securityService = serviceContext.newService(SecurityService.class); // --- get session token (from request parameters) --- // - String sessionTokenHeader = context.getHeader(REQUEST_HEADER_SESSION_TOKEN); + String sessionTokenHeader = context.getHeaderString(REQUEST_HEADER_SESSION_TOKEN); if (StringUtils.isEmpty(sessionTokenHeader)) { // --- get session token (from request cookies) --- // - CookieManager.CookieEntity cookieEntity = context.getCookieManager().get(COOKIE_POLLEN_AUTH); - if (cookieEntity != null) { + Cookie cookie = context.getCookies().get(COOKIE_POLLEN_AUTH); + if (cookie != null) { if (log.isDebugEnabled()) { - log.debug("Found pollen-auth cookie:: " + cookieEntity.getValue()); + log.debug("Found pollen-auth cookie:: " + cookie.getValue()); } - sessionTokenHeader = securityService.decrypt(cookieEntity.getValue()); + sessionTokenHeader = securityService.decrypt(cookie.getValue()); } } @@ -167,10 +212,12 @@ public class PollenRestApiRequestFilter extends WebMotionFilter { SessionToken sessionToken = securityService.getSessionTokenByToken(sessionTokenHeader); // --- get mainPrincipal (from request parameters) --- // - Map<String, String[]> parameters = context.getParameters(); - String[] strings = parameters.get(REQUEST_PERMISSION_PARAMETER); - String credentialParam = strings == null || strings.length < 1 ? null : strings[0]; - PollenPrincipal mainPrincipal = securityService.getPollenPrincipalByPermissionToken(credentialParam); + String permission = null; + List<String> permissions = context.getUriInfo().getQueryParameters().get(REQUEST_PERMISSION_PARAMETER); + if (CollectionUtils.isNotEmpty(permissions)) { + permission = permissions.get(0); + } + PollenPrincipal mainPrincipal = securityService.getPollenPrincipalByPermissionToken(permission); // --- create security context --- // @@ -178,30 +225,18 @@ public class PollenRestApiRequestFilter extends WebMotionFilter { } - private Locale getUserLocale(HttpContext context) { - String language = context.getHeader(HttpContext.HEADER_LANGUAGE); + private Locale getUserLocale(ContainerRequestContext context) { + Locale language = context.getLanguage(); if (log.isDebugEnabled()) { log.debug("Found Accept-Language: " + language); } - // search best locale accepted by the server 'fr' or 'en' - if (language != null) { - String[] allLanguage = language.split(","); - int i = 0; - do { - language = allLanguage[i].substring(0, 2); - if (!language.equals("fr") && !language.equals("en")) { - // language not accepted - language = null; - } - i++; - } while (language == null && i < allLanguage.length); - } - - if (language == null) { + if (language == null + || (!Locale.FRENCH.getLanguage().equals(language.getLanguage()) + && !Locale.ENGLISH.getLanguage().equals(language.getLanguage()))) { - language = Locale.FRENCH.getLanguage(); + language = Locale.FRANCE; if (log.isInfoEnabled()) { log.info("Use default language: " + language); @@ -209,7 +244,7 @@ public class PollenRestApiRequestFilter extends WebMotionFilter { } - return new Locale(language); + return language; } diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenTopiaTransactionFilter.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenTopiaTransactionFilter.java index 5d3dafc9..8c2a4a4e 100644 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenTopiaTransactionFilter.java +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/PollenTopiaTransactionFilter.java @@ -30,6 +30,7 @@ import org.nuiton.web.filter.TypedTopiaTransactionFilter; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; +import javax.ws.rs.container.ContainerRequestContext; public class PollenTopiaTransactionFilter extends TypedTopiaTransactionFilter<PollenPersistenceContext> { @@ -59,4 +60,10 @@ public class PollenTopiaTransactionFilter extends TypedTopiaTransactionFilter<Po } } + public static PollenPersistenceContext getPersistenceContext(ContainerRequestContext context) { + PollenPersistenceContext topiaContext = (PollenPersistenceContext) + context.getProperty(TOPIA_TRANSACTION_REQUEST_ATTRIBUTE); + return topiaContext; + } } + \ No newline at end of file diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/beans/ChangePasswordBean.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/beans/ChangePasswordBean.java new file mode 100644 index 00000000..57f304af --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/beans/ChangePasswordBean.java @@ -0,0 +1,25 @@ +package org.chorem.pollen.rest.api.beans; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class ChangePasswordBean { + protected String oldPassword; + protected String newPassword; + + public String getOldPassword() { + return oldPassword; + } + + public void setOldPassword(String oldPassword) { + this.oldPassword = oldPassword; + } + + public String getNewPassword() { + return newPassword; + } + + public void setNewPassword(String newPassword) { + this.newPassword = newPassword; + } +} \ No newline at end of file diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/beans/PollCreateBean.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/beans/PollCreateBean.java new file mode 100644 index 00000000..68956468 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/beans/PollCreateBean.java @@ -0,0 +1,54 @@ +package org.chorem.pollen.rest.api.beans; + +import org.chorem.pollen.services.bean.ChoiceBean; +import org.chorem.pollen.services.bean.PollBean; +import org.chorem.pollen.services.bean.VoterListBean; +import org.chorem.pollen.services.bean.VoterListMemberBean; + +import java.util.List; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class PollCreateBean { + + protected PollBean poll; + + protected List<ChoiceBean> choices; + + protected List<VoterListBean> voterLists; + + protected List<VoterListMemberBean> voterListMembers; + + public PollBean getPoll() { + return poll; + } + + public void setPoll(PollBean poll) { + this.poll = poll; + } + + public List<ChoiceBean> getChoices() { + return choices; + } + + public void setChoices(List<ChoiceBean> choices) { + this.choices = choices; + } + + public List<VoterListBean> getVoterLists() { + return voterLists; + } + + public void setVoterLists(List<VoterListBean> voterLists) { + this.voterLists = voterLists; + } + + public List<VoterListMemberBean> getVoterListMembers() { + return voterListMembers; + } + + public void setVoterListMembers(List<VoterListMemberBean> voterListMembers) { + this.voterListMembers = voterListMembers; + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/beans/VoterListSaveBean.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/beans/VoterListSaveBean.java new file mode 100644 index 00000000..d04f7a88 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/beans/VoterListSaveBean.java @@ -0,0 +1,50 @@ +package org.chorem.pollen.rest.api.beans; + +import org.chorem.pollen.services.bean.VoterListBean; +import org.chorem.pollen.services.bean.VoterListMemberBean; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class VoterListSaveBean { + + protected VoterListBean[] listsToSave; + + protected VoterListMemberBean[] membersToSave; + + protected VoterListBean[] listsToDelete; + + protected VoterListMemberBean[] membersToDelete; + + public VoterListBean[] getListsToSave() { + return listsToSave; + } + + public void setListsToSave(VoterListBean[] listsToSave) { + this.listsToSave = listsToSave; + } + + public VoterListMemberBean[] getMembersToSave() { + return membersToSave; + } + + public void setMembersToSave(VoterListMemberBean[] membersToSave) { + this.membersToSave = membersToSave; + } + + public VoterListBean[] getListsToDelete() { + return listsToDelete; + } + + public void setListsToDelete(VoterListBean[] listsToDelete) { + this.listsToDelete = listsToDelete; + } + + public VoterListMemberBean[] getMembersToDelete() { + return membersToDelete; + } + + public void setMembersToDelete(VoterListMemberBean[] membersToDelete) { + this.membersToDelete = membersToDelete; + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/DateConverter.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/DateConverter.java deleted file mode 100644 index 67129ed5..00000000 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/DateConverter.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.chorem.pollen.rest.api.converter; - -/* - * #%L - * Pollen :: Rest Api - * %% - * Copyright (C) 2009 - 2017 Code Lutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import org.apache.commons.beanutils.converters.AbstractConverter; - -import java.util.Date; - -/** - * Created on 5/19/14. - * - * @author Tony Chemit - dev@tchemit.fr - * @since 2.0 - */ -public class DateConverter extends AbstractConverter { - - @Override - protected <T> T convertToType(Class<T> type, Object value) throws Throwable { - Date result = null; - if (value != null) { - if (value.getClass().isAssignableFrom(Date.class)) { - result = (Date) value; - } else { - Object o = ((Object[]) value)[0]; - String sTime = o.toString(); - Long time = Long.parseLong(sTime); - result = new Date(time); - } - } - return (T) result; - } - - @Override - protected Class<?> getDefaultType() { - return Date.class; - } -} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/JacksonConfig.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/JacksonConfig.java new file mode 100644 index 00000000..f4b46ec2 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/JacksonConfig.java @@ -0,0 +1,33 @@ +package org.chorem.pollen.rest.api.converter; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import org.chorem.pollen.services.bean.PollenEntityId; +import org.chorem.pollen.services.bean.PollenEntityRef; + +import javax.ws.rs.ext.ContextResolver; +import javax.ws.rs.ext.Provider; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +@Provider +public class JacksonConfig implements ContextResolver<ObjectMapper> { + + private ObjectMapper objectMapper; + + public JacksonConfig() { + objectMapper = new ObjectMapper(); + SimpleModule module = new SimpleModule(); + module.addSerializer(PollenEntityId.class, new PollenEntityIdSerializer()); + module.addSerializer(PollenEntityRef.class, new PollenEntityRefSerializer()); + module.addDeserializer(PollenEntityId.class, new PollenEntityIdDeserializer()); + module.addDeserializer(PollenEntityRef.class, new PollenEntityRefDeserializer()); + objectMapper.registerModule(module); + } + + public ObjectMapper getContext(Class<?> objectType) { + return objectMapper; + } + +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/JsonArrayConverter.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/JsonArrayConverter.java deleted file mode 100644 index 65bd81c3..00000000 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/JsonArrayConverter.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.chorem.pollen.rest.api.converter; - -/* - * #%L - * Pollen :: Rest Api - * %% - * Copyright (C) 2009 - 2017 Code Lutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import com.google.common.reflect.TypeParameter; -import com.google.common.reflect.TypeToken; -import org.apache.commons.beanutils.converters.AbstractConverter; -import org.chorem.pollen.rest.api.JsonHelper; -import org.nuiton.topia.persistence.TopiaIdFactory; - -/** - * Created on 5/16/14. - * - * @author Tony Chemit - dev@tchemit.fr - * @since 2.0 - */ -public class JsonArrayConverter<O> extends AbstractConverter { - - protected final Class<O[]> arrayType; - - protected final JsonHelper jsonHelper; - - public static <O> JsonArrayConverter<O> newConverter(TopiaIdFactory topiaIdFactory, Class<O> objectType) { - return new JsonArrayConverter<>(topiaIdFactory, objectType); - } - - public JsonArrayConverter(TopiaIdFactory topiaIdFactory, Class<O> entityType) { - - this.arrayType = (Class<O[]>) new TypeToken<O[]>() { - } - .where(new TypeParameter<O>() { - }, entityType) - .getType(); - this.jsonHelper = new JsonHelper(topiaIdFactory, false); - } - - @Override - protected <T> T convertToType(Class<T> type, Object value) throws Throwable { - - String stringValue; - - if (value instanceof String) { - - stringValue = (String) value; - - } else { - - stringValue = ((String[]) value)[0]; - - } - - O[] values = jsonHelper.fromJson(stringValue, this.arrayType); - - return (T) values; - - } - - @Override - public Class<?> getDefaultType() { - return arrayType; - } -} - diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/JsonConverter.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/JsonConverter.java deleted file mode 100644 index eb847eb0..00000000 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/JsonConverter.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.chorem.pollen.rest.api.converter; - -/* - * #%L - * Pollen :: Rest Api - * %% - * Copyright (C) 2009 - 2017 Code Lutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import org.apache.commons.beanutils.converters.AbstractConverter; -import org.chorem.pollen.persistence.PollenEntityEnum; -import org.chorem.pollen.rest.api.JsonHelper; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaIdFactory; - -/** - * Created on 5/6/14. - * - * @author Tony Chemit - dev@tchemit.fr - * @since 2.0 - */ -public class JsonConverter<O> extends AbstractConverter { - - protected final Class<O> objectType; - - protected final Class<O> implementationClass; - - protected final JsonHelper jsonHelper; - - public static <O> JsonConverter<O> newConverter(TopiaIdFactory topiaIdFactory, Class<O> objectType) { - return newConverter(topiaIdFactory, objectType, objectType); - } - - public static <E extends TopiaEntity> JsonConverter<E> newEntityConverter(TopiaIdFactory topiaIdFactory, Class<E> objectType) { - Class<E> implementationClass = PollenEntityEnum.getImplementationClass(objectType); - return newConverter(topiaIdFactory, objectType, implementationClass); - } - - public static <O> JsonConverter<O> newConverter(TopiaIdFactory topiaIdFactory, Class<O> objectType, Class<O> implementationClass) { - return new JsonConverter<>(topiaIdFactory, objectType, implementationClass); - } - - public JsonConverter(TopiaIdFactory topiaIdFactory, Class<O> objectType, Class<O> implementationClass) { - - this.objectType = objectType; - this.jsonHelper = new JsonHelper(topiaIdFactory, false); - this.implementationClass = implementationClass; - } - - @Override - protected String convertToString(Object value) throws Throwable { - - return jsonHelper.toJson(value); - - } - - @Override - protected <T> T convertToType(Class<T> type, Object value) throws Throwable { - - String stringValue; - - if (value instanceof String) { - - stringValue = (String) value; - - } else { - - stringValue = ((String[]) value)[0]; - - } - - return (T) jsonHelper.fromJson(stringValue, implementationClass); - - } - - @Override - protected Class<O> getDefaultType() { - - return objectType; - - } - - -} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenConverterProvider.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenConverterProvider.java new file mode 100644 index 00000000..de8a5dfc --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenConverterProvider.java @@ -0,0 +1,29 @@ +package org.chorem.pollen.rest.api.converter; + +import org.chorem.pollen.services.bean.PollenEntityId; + +import javax.ws.rs.ext.ParamConverter; +import javax.ws.rs.ext.ParamConverterProvider; +import javax.ws.rs.ext.Provider; +import java.lang.annotation.Annotation; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +@Provider +public class PollenConverterProvider implements ParamConverterProvider { + + @Override + public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) { + ParamConverter<T> converter = null; + + if (PollenEntityId.class.isAssignableFrom(rawType)) { + Class entityClass = (Class)((ParameterizedType) genericType).getActualTypeArguments()[0]; + converter = new PollenEntityIdConverter(entityClass); + } + + return converter; + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEntityIdConverter.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEntityIdConverter.java new file mode 100644 index 00000000..467ffbbe --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEntityIdConverter.java @@ -0,0 +1,63 @@ +package org.chorem.pollen.rest.api.converter; + +/* + * #%L + * Pollen :: Rest Api + * %% + * Copyright (C) 2009 - 2017 Code Lutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * #L% + */ + +import org.chorem.pollen.rest.api.PollenRestApiApplicationContext; +import org.chorem.pollen.services.bean.PollenEntityId; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaIdFactory; + +import javax.ws.rs.ext.ParamConverter; + +/** + * Created on 5/23/14. + * + * @author Tony Chemit - dev@tchemit.fr + * @since 2.0 + */ +public class PollenEntityIdConverter<E extends TopiaEntity> implements ParamConverter<PollenEntityId<E>> { + + protected final Class<E> type; + + public PollenEntityIdConverter(Class<E> type) { + this.type = type; + } + + @Override + public String toString(PollenEntityId<E> object) { + return object.getReducedId(); + } + + @Override + public PollenEntityId<E> fromString(String string) { + PollenEntityId<E> result = PollenEntityId.newId(type); + result.setReducedId(string); + + PollenRestApiApplicationContext applicationContext = + PollenRestApiApplicationContext.getApplicationContext(); + + TopiaIdFactory topiaIdFactory = applicationContext.getTopiaApplicationContext().getTopiaIdFactory(); + result.decode(topiaIdFactory); + + return result; + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEntityIdDeserializer.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEntityIdDeserializer.java new file mode 100644 index 00000000..363e0780 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEntityIdDeserializer.java @@ -0,0 +1,52 @@ +package org.chorem.pollen.rest.api.converter; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.BeanProperty; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.deser.ContextualDeserializer; +import com.fasterxml.jackson.databind.type.SimpleType; +import org.chorem.pollen.rest.api.PollenRestApiApplicationContext; +import org.chorem.pollen.services.bean.PollenEntityId; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaIdFactory; + +import java.io.IOException; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class PollenEntityIdDeserializer extends JsonDeserializer<PollenEntityId> implements ContextualDeserializer { + + private JavaType valueType; + + @Override + public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { + SimpleType type = (SimpleType) ctxt.getContextualType(); + JavaType valueType = type.containedType(0); + PollenEntityIdDeserializer deserializer = new PollenEntityIdDeserializer(); + deserializer.valueType = valueType; + return deserializer; + } + + @Override + public PollenEntityId deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + + String id = p.getText(); + + PollenEntityId pollenEntityId = PollenEntityId.newId((Class<? extends TopiaEntity>) valueType.getRawClass()); + + pollenEntityId.setReducedId(id); + + PollenRestApiApplicationContext applicationContext = + PollenRestApiApplicationContext.getApplicationContext(); + + TopiaIdFactory topiaIdFactory = applicationContext.getTopiaApplicationContext().getTopiaIdFactory(); + pollenEntityId.decode(topiaIdFactory); + + return pollenEntityId; + + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEntityIdSerializer.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEntityIdSerializer.java new file mode 100644 index 00000000..cf3569a9 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEntityIdSerializer.java @@ -0,0 +1,25 @@ +package org.chorem.pollen.rest.api.converter; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import org.chorem.pollen.rest.api.PollenRestApiApplicationContext; +import org.chorem.pollen.services.bean.PollenEntityId; +import org.nuiton.topia.persistence.TopiaIdFactory; + +import java.io.IOException; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class PollenEntityIdSerializer extends JsonSerializer<PollenEntityId> { + @Override + public void serialize(PollenEntityId value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + PollenRestApiApplicationContext applicationContext = + PollenRestApiApplicationContext.getApplicationContext(); + + TopiaIdFactory topiaIdFactory = applicationContext.getTopiaApplicationContext().getTopiaIdFactory(); + value.encode(topiaIdFactory); + gen.writeString(value.getReducedId()); + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEntityRefDeserializer.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEntityRefDeserializer.java new file mode 100644 index 00000000..211599f9 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEntityRefDeserializer.java @@ -0,0 +1,61 @@ +package org.chorem.pollen.rest.api.converter; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.BeanProperty; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.deser.ContextualDeserializer; +import com.fasterxml.jackson.databind.type.SimpleType; +import org.chorem.pollen.rest.api.PollenRestApiApplicationContext; +import org.chorem.pollen.services.bean.PollenEntityRef; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaIdFactory; + +import java.io.IOException; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class PollenEntityRefDeserializer extends JsonDeserializer<PollenEntityRef> implements ContextualDeserializer { + + private JavaType valueType; + + @Override + public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { + SimpleType type = (SimpleType) ctxt.getContextualType(); + JavaType valueType = type.containedType(0); + PollenEntityRefDeserializer deserializer = new PollenEntityRefDeserializer(); + deserializer.valueType = valueType; + return deserializer; + } + + + @Override + public PollenEntityRef deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + ObjectCodec oc = p.getCodec(); + + JsonNode node = oc.readTree(p); + + String permission = node.get("permission").asText(); + + String id = node.get("id").asText(); + + PollenEntityRef<?> ref = PollenEntityRef.newRef((Class<? extends TopiaEntity>) valueType.getRawClass()); + + ref.setReducedId(id); + ref.setPermission(permission); + + PollenRestApiApplicationContext applicationContext = + PollenRestApiApplicationContext.getApplicationContext(); + + TopiaIdFactory topiaIdFactory = applicationContext.getTopiaApplicationContext().getTopiaIdFactory(); + + ref.decode(topiaIdFactory); + + return ref; + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEntityRefSerializer.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEntityRefSerializer.java new file mode 100644 index 00000000..1f6865b8 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEntityRefSerializer.java @@ -0,0 +1,29 @@ +package org.chorem.pollen.rest.api.converter; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import org.chorem.pollen.rest.api.PollenRestApiApplicationContext; +import org.chorem.pollen.services.bean.PollenEntityRef; +import org.nuiton.topia.persistence.TopiaIdFactory; + +import java.io.IOException; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class PollenEntityRefSerializer extends JsonSerializer<PollenEntityRef> { + @Override + public void serialize(PollenEntityRef value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + PollenRestApiApplicationContext applicationContext = + PollenRestApiApplicationContext.getApplicationContext(); + + TopiaIdFactory topiaIdFactory = applicationContext.getTopiaApplicationContext().getTopiaIdFactory(); + value.encode(topiaIdFactory); + + gen.writeStartObject(); + gen.writeStringField("permission", value.getPermission()); + gen.writeStringField("id", value.getReducedId()); + gen.writeEndObject(); + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEnumConverter.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEnumConverter.java deleted file mode 100644 index 8307709c..00000000 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/converter/PollenEnumConverter.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.chorem.pollen.rest.api.converter; - -import org.apache.commons.beanutils.ConversionException; -import org.nuiton.converter.EnumConverter; - -/** - * Created on 31/01/17. - * - * @author Tony Chemit - dev@tchemit.fr - * @since 2.0 - */ -public class PollenEnumConverter<E extends Enum> extends EnumConverter<E> { - - public PollenEnumConverter(Class<E> enumType, Object defaultValue) { - super(enumType, defaultValue); - } - - public PollenEnumConverter(Class<E> enumType) { - super(enumType); - } - - @Override - public <T> T convert(Class<T> aClass, Object value) { - if (value == null) { - return super.convert(aClass, value); - } - if (isEnabled(aClass, enumType)) { - Object result; - if (isEnabled(value.getClass(), enumType)) { - result = value; - return aClass.cast(result); - } - if (value.getClass().isArray()) { { - value = ((Object[])value)[0]; - }} - if (value instanceof String) { - try { - result = valueOf(aClass, value); - } catch (IllegalArgumentException e) { - // try an ordinal conversion - result = convertFromOrdinal(aClass, value); - } - return aClass.cast(result); - } - if (value instanceof Integer) { - // try a ordinal conversion - result = convertFromOrdinal(aClass, value); - return aClass.cast(result); - } - } - throw new ConversionException( - String.format("no convertor found for type %2$s and objet '%1$s'", aClass.getName(), value)); - } -} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/FavoriteListImportExceptionMapper.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/FavoriteListImportExceptionMapper.java new file mode 100644 index 00000000..e34cdc6a --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/FavoriteListImportExceptionMapper.java @@ -0,0 +1,20 @@ +package org.chorem.pollen.rest.api.exceptionMappers; + +import org.chorem.pollen.services.service.FavoriteListImportException; + +import javax.ws.rs.core.Response; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class FavoriteListImportExceptionMapper extends PollenAbstractExceptionMapper<FavoriteListImportException> { + + public FavoriteListImportExceptionMapper() { + super(Response.Status.BAD_REQUEST); + } + + @Override + protected Object getEntity(FavoriteListImportException exception) { + return exception; + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/InvalidEntityLinkExceptionMapper.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/InvalidEntityLinkExceptionMapper.java new file mode 100644 index 00000000..0db3e2e9 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/InvalidEntityLinkExceptionMapper.java @@ -0,0 +1,15 @@ +package org.chorem.pollen.rest.api.exceptionMappers; + +import org.chorem.pollen.services.service.InvalidEntityLinkException; + +import javax.ws.rs.core.Response; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class InvalidEntityLinkExceptionMapper extends PollenAbstractExceptionMapper<InvalidEntityLinkException>{ + + public InvalidEntityLinkExceptionMapper() { + super(Response.Status.NOT_FOUND); + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/InvalidFormExceptionMapper.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/InvalidFormExceptionMapper.java new file mode 100644 index 00000000..f074ff48 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/InvalidFormExceptionMapper.java @@ -0,0 +1,20 @@ +package org.chorem.pollen.rest.api.exceptionMappers; + +import org.chorem.pollen.services.service.InvalidFormException; + +import javax.ws.rs.core.Response; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class InvalidFormExceptionMapper extends PollenAbstractExceptionMapper<InvalidFormException> { + + public InvalidFormExceptionMapper() { + super(Response.Status.BAD_REQUEST); + } + + @Override + protected Object getEntity(InvalidFormException exception) { + return exception; + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenAbstractExceptionMapper.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenAbstractExceptionMapper.java new file mode 100644 index 00000000..e987ec81 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenAbstractExceptionMapper.java @@ -0,0 +1,40 @@ +package org.chorem.pollen.rest.api.exceptionMappers; + +import org.chorem.pollen.rest.api.v1.AuthApi; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class PollenAbstractExceptionMapper<E extends Exception> implements ExceptionMapper<E> { + + protected final Response.Status status; + + protected final boolean removeConnexionCookie; + + public PollenAbstractExceptionMapper(Response.Status status) { + this(status, false); + } + + public PollenAbstractExceptionMapper(Response.Status status, boolean removeConnexionCookie) { + this.status = status; + this.removeConnexionCookie = removeConnexionCookie; + } + + protected Object getEntity(E exception) { + return exception.getMessage(); + } + + + @Override + public Response toResponse(E exception) { + Response.ResponseBuilder builder = Response.status(status) + .entity(getEntity(exception)); + if (removeConnexionCookie) { + builder = AuthApi.removeAuthCookie(builder); + } + return builder.build(); + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenAuthenticationExceptionMapper.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenAuthenticationExceptionMapper.java new file mode 100644 index 00000000..2db84d94 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenAuthenticationExceptionMapper.java @@ -0,0 +1,15 @@ +package org.chorem.pollen.rest.api.exceptionMappers; + +import org.chorem.pollen.services.service.security.PollenAuthenticationException; + +import javax.ws.rs.core.Response; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class PollenAuthenticationExceptionMapper extends PollenAbstractExceptionMapper<PollenAuthenticationException> { + + public PollenAuthenticationExceptionMapper() { + super(Response.Status.UNAUTHORIZED, true); + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenInvalidEmailActivationTokenExceptionMapper.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenInvalidEmailActivationTokenExceptionMapper.java new file mode 100644 index 00000000..e3c66669 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenInvalidEmailActivationTokenExceptionMapper.java @@ -0,0 +1,15 @@ +package org.chorem.pollen.rest.api.exceptionMappers; + +import org.chorem.pollen.services.service.security.PollenInvalidEmailActivationTokenException; + +import javax.ws.rs.core.Response; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class PollenInvalidEmailActivationTokenExceptionMapper extends PollenAbstractExceptionMapper<PollenInvalidEmailActivationTokenException> { + + public PollenInvalidEmailActivationTokenExceptionMapper() { + super(Response.Status.FORBIDDEN); + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenInvalidPermissionExceptionMapper.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenInvalidPermissionExceptionMapper.java new file mode 100644 index 00000000..ee8ce049 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenInvalidPermissionExceptionMapper.java @@ -0,0 +1,15 @@ +package org.chorem.pollen.rest.api.exceptionMappers; + +import org.chorem.pollen.services.service.security.PollenInvalidPermissionException; + +import javax.ws.rs.core.Response; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class PollenInvalidPermissionExceptionMapper extends PollenAbstractExceptionMapper<PollenInvalidPermissionException> { + + public PollenInvalidPermissionExceptionMapper() { + super(Response.Status.FORBIDDEN); + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenInvalidSessionTokenExceptionMapper.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenInvalidSessionTokenExceptionMapper.java new file mode 100644 index 00000000..5bfdb101 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenInvalidSessionTokenExceptionMapper.java @@ -0,0 +1,15 @@ +package org.chorem.pollen.rest.api.exceptionMappers; + +import org.chorem.pollen.services.service.security.PollenInvalidSessionTokenException; + +import javax.ws.rs.core.Response; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class PollenInvalidSessionTokenExceptionMapper extends PollenAbstractExceptionMapper<PollenInvalidSessionTokenException> { + + public PollenInvalidSessionTokenExceptionMapper() { + super(Response.Status.UNAUTHORIZED, true); + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenUnauthorizedExceptionMapper.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenUnauthorizedExceptionMapper.java new file mode 100644 index 00000000..b4f9dcea --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/PollenUnauthorizedExceptionMapper.java @@ -0,0 +1,15 @@ +package org.chorem.pollen.rest.api.exceptionMappers; + +import org.chorem.pollen.services.service.security.PollenUnauthorizedException; + +import javax.ws.rs.core.Response; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class PollenUnauthorizedExceptionMapper extends PollenAbstractExceptionMapper<PollenUnauthorizedException> { + + public PollenUnauthorizedExceptionMapper() { + super(Response.Status.FORBIDDEN); + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/TopiaNoResultExceptionMapper.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/TopiaNoResultExceptionMapper.java new file mode 100644 index 00000000..ac088c61 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/exceptionMappers/TopiaNoResultExceptionMapper.java @@ -0,0 +1,15 @@ +package org.chorem.pollen.rest.api.exceptionMappers; + +import org.nuiton.topia.persistence.TopiaNoResultException; + +import javax.ws.rs.core.Response; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class TopiaNoResultExceptionMapper extends PollenAbstractExceptionMapper<TopiaNoResultException> { + + public TopiaNoResultExceptionMapper() { + super(Response.Status.NOT_FOUND); + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/injector/PollenBeanIdInjector.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/injector/PollenBeanIdInjector.java deleted file mode 100644 index ed120d62..00000000 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/injector/PollenBeanIdInjector.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.chorem.pollen.rest.api.injector; - -/* - * #%L - * Pollen :: Rest Api - * %% - * Copyright (C) 2009 - 2017 Code Lutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import org.chorem.pollen.services.bean.PollenEntityId; -import org.debux.webmotion.server.call.Call; -import org.debux.webmotion.server.handler.ExecutorParametersInjectorHandler; -import org.debux.webmotion.server.mapping.Mapping; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaIdFactory; - -import java.lang.reflect.Type; - -/** - * Created on 5/23/14. - * - * @author Tony Chemit - dev@tchemit.fr - * @since 2.0 - */ -public class PollenBeanIdInjector implements ExecutorParametersInjectorHandler.Injector { - - protected final TopiaIdFactory topiaIdFactory; - - public PollenBeanIdInjector(TopiaIdFactory topiaIdFactory) { - this.topiaIdFactory = topiaIdFactory; - } - - @Override - public PollenEntityId<TopiaEntity> getValue(Mapping m, Call call, String name, Class type, Type generic) { - - PollenEntityId<TopiaEntity> result = null; - - if (PollenEntityId.class.isAssignableFrom(type)) { - - result = PollenEntityId.newId(generic); - Call.ParameterTree parameterTree = call.getParameterTree().getObject().get(name); - - if (parameterTree != null && parameterTree.getValue() != null) { - - String encodedId = ((String[]) parameterTree.getValue())[0]; - result.setReducedId(encodedId); - result.decode(topiaIdFactory); - - } - } - - return result; - - } - -} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/injector/PollenRestApiRequestContextInjector.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/injector/PollenRestApiRequestContextInjector.java deleted file mode 100644 index 389cd4d2..00000000 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/injector/PollenRestApiRequestContextInjector.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.chorem.pollen.rest.api.injector; - -/* - * #%L - * Pollen :: Rest Api - * %% - * Copyright (C) 2009 - 2017 Code Lutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import org.chorem.pollen.rest.api.PollenRestApiRequestContext; -import org.debux.webmotion.server.call.Call; -import org.debux.webmotion.server.call.HttpContext; -import org.debux.webmotion.server.handler.ExecutorParametersInjectorHandler; -import org.debux.webmotion.server.mapping.Mapping; - -import java.lang.reflect.Type; - -/** - * Created on 5/23/14. - * - * @author Tony Chemit - dev@tchemit.fr - * @since 2.0 - */ -public class PollenRestApiRequestContextInjector implements ExecutorParametersInjectorHandler.Injector { - - @Override - public PollenRestApiRequestContext getValue(Mapping m, Call call, String name, Class<?> type, Type generic) { - - PollenRestApiRequestContext result = null; - if (PollenRestApiRequestContext.class.isAssignableFrom(type)) { - HttpContext httpContext = call.getContext(); - - result = PollenRestApiRequestContext.getRequestContext(httpContext); - } - - return result; - - } -} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/injector/PollenServiceInjector.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/injector/PollenServiceInjector.java deleted file mode 100644 index 33f88338..00000000 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/injector/PollenServiceInjector.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.chorem.pollen.rest.api.injector; - -/* - * #%L - * Pollen :: Rest Api - * %% - * Copyright (C) 2009 - 2017 Code Lutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import org.chorem.pollen.rest.api.PollenRestApiRequestContext; -import org.chorem.pollen.services.PollenService; -import org.debux.webmotion.server.call.Call; -import org.debux.webmotion.server.call.HttpContext; -import org.debux.webmotion.server.handler.ExecutorParametersInjectorHandler; -import org.debux.webmotion.server.mapping.Mapping; - -import java.lang.reflect.Type; - -/** - * Created on 5/23/14. - * - * @author Tony Chemit - dev@tchemit.fr - * @since 2.0 - */ -public class PollenServiceInjector implements ExecutorParametersInjectorHandler.Injector { - @Override - public PollenService getValue(Mapping m, Call call, String name, Class type, Type generic) { - - PollenService result = null; - if (PollenService.class.isAssignableFrom(type)) { - HttpContext httpContext = call.getContext(); - - PollenRestApiRequestContext requestContext = - PollenRestApiRequestContext.getRequestContext(httpContext); - result = requestContext.getServiceContext().newService(type); - } - - return result; - - } -} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/ApiUtils.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/ApiUtils.java new file mode 100644 index 00000000..cf3405e3 --- /dev/null +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/ApiUtils.java @@ -0,0 +1,78 @@ +package org.chorem.pollen.rest.api.v1; + +import com.google.common.base.Charsets; +import com.rometools.rome.feed.atom.Feed; +import com.rometools.rome.feed.synd.SyndFeed; +import org.apache.commons.io.IOUtils; +import org.chorem.pollen.services.PollenTechnicalException; +import org.chorem.pollen.services.bean.ResourceFileBean; +import org.chorem.pollen.services.bean.export.ExportBean; +import org.jboss.resteasy.plugins.providers.multipart.InputPart; +import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput; + +import javax.ws.rs.core.Response; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class ApiUtils { + + public static Response exportBeanToResponse(ExportBean exportBean) { + InputStream inputStream = IOUtils.toInputStream(exportBean.getContent(), Charsets.UTF_8); + + return ResponseDownload(inputStream, exportBean.getName(), exportBean.getContentType()); + } + + public static Response ResponseDownload(InputStream inputStream, String name, String contentType) { + return Response.ok(inputStream, contentType) + .header("content-disposition", "attachment; filename=\"" + name + "\"") + .build(); + } + + public static ResourceFileBean multipartToResourceBean(MultipartFormDataInput multipartFormDataInput, String inputName) { + try { + InputStream in = multipartFormDataInput.getFormDataPart(inputName, InputStream.class, null); + java.nio.file.Path tempPath = Files.createTempDirectory("pollen"); + InputPart inputPart = multipartFormDataInput + .getFormDataMap() + .get(inputName) + .get(0); + String contentDisposition = inputPart + .getHeaders() + .get("Content-Disposition") + .get(0); + Pattern FilenamePattern = Pattern.compile("filename=\"(.*)\""); + Matcher matcher = FilenamePattern.matcher(contentDisposition); + String fileName = inputName; + if (matcher.find()) { + fileName = matcher.group(1); + } + File uploadFile = new File(tempPath.toFile(), fileName); + Files.copy(in, uploadFile.toPath()); + + ResourceFileBean resourceBean = new ResourceFileBean(); + resourceBean.setFile(uploadFile); + resourceBean.setName(fileName); + + String contentType = inputPart.getMediaType().toString(); + + resourceBean.setContentType(contentType); + resourceBean.setSize(uploadFile.length()); + + return resourceBean; + } catch (IOException e) { + throw new PollenTechnicalException(e); + } + } + + public static Feed syndFeedToFeed(SyndFeed feedForPoll) { + // TODO + return null; + } +} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/AuthApi.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/AuthApi.java index 0f3d6bcd..b6eb9330 100644 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/AuthApi.java +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/AuthApi.java @@ -27,8 +27,7 @@ import org.apache.commons.logging.LogFactory; import org.apache.shiro.codec.Base64; import org.chorem.pollen.persistence.entity.PollenUser; import org.chorem.pollen.persistence.entity.SessionToken; -import org.chorem.pollen.rest.api.PollenRestApiRequestContext; -import org.chorem.pollen.services.PollenUIContext; +import org.chorem.pollen.services.PollenServiceContext; import org.chorem.pollen.services.bean.PollenEntityRef; import org.chorem.pollen.services.service.PollenUserService; import org.chorem.pollen.services.service.security.MissingAuthenticationException; @@ -36,12 +35,22 @@ import org.chorem.pollen.services.service.security.PollenAuthenticationException import org.chorem.pollen.services.service.security.PollenCypherTechnicalException; import org.chorem.pollen.services.service.security.PollenEmailNotValidatedException; import org.chorem.pollen.services.service.security.PollenInvalidSessionTokenException; +import org.chorem.pollen.services.service.security.PollenSecurityContext; import org.chorem.pollen.services.service.security.SecurityService; -import org.debux.webmotion.server.WebMotionController; -import org.debux.webmotion.server.call.HttpContext; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.NewCookie; +import javax.ws.rs.core.Response; /** * TODO @@ -49,7 +58,10 @@ import javax.servlet.http.HttpServletResponse; * @author Tony Chemit - dev@tchemit.fr * @since 2.0 */ -public class AuthApi extends WebMotionController { +@Path("") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class AuthApi { /** Logger */ private static final Log log = LogFactory.getLog(AuthApi.class); @@ -58,28 +70,41 @@ public class AuthApi extends WebMotionController { private static final String COOKIE_POLLEN_CONNECTED = "pollen-connected"; private final static int COOKIE_MAX_AGE = 60 * 60 * 24 * 365; // 1 year - public static void removeAuthCookie(HttpServletResponse response) { - Cookie authCookie = new Cookie(COOKIE_POLLEN_AUTH, ""); - authCookie.setPath("/"); - authCookie.setMaxAge(0); - response.addCookie(authCookie); - - Cookie connectedCookie = new Cookie(COOKIE_POLLEN_CONNECTED, ""); - connectedCookie.setPath("/"); - connectedCookie.setMaxAge(0); - response.addCookie(connectedCookie); - + public static Response.ResponseBuilder removeAuthCookie(Response.ResponseBuilder reponseBuilder) { + + NewCookie authCookie = new NewCookie( + COOKIE_POLLEN_AUTH, + "", + "/", + null, + null, + 0, + false); + + NewCookie connectedCookie = new NewCookie( + COOKIE_POLLEN_CONNECTED, + "", + "/", + null, + null, + 0, + false); + + return reponseBuilder.cookie(authCookie, connectedCookie); } - public PollenEntityRef<PollenUser> login(HttpContext requestContext, SecurityService securityService) + @Path("/login") + @POST @PUT + public Response login(@HeaderParam("Authorization") String authHeader, + @Context PollenServiceContext serviceContext, + @Context SecurityService securityService, + @Context PollenSecurityContext securityContext) throws PollenAuthenticationException, MissingAuthenticationException, PollenInvalidSessionTokenException, PollenCypherTechnicalException, PollenEmailNotValidatedException { - String authHeader = requestContext.getHeader("Authorization"); - if (StringUtils.startsWith(authHeader, "Basic ")) { String s = new String(Base64.decode(StringUtils.substringAfter(authHeader, "Basic "))); String[] lp = s.split(":"); @@ -91,74 +116,91 @@ public class AuthApi extends WebMotionController { } PollenEntityRef<PollenUser> userPollenEntityRef = securityService.login(login, password, false); + userPollenEntityRef.encode(serviceContext.getTopiaApplicationContext().getTopiaIdFactory()); // Inject the session token in security context - PollenRestApiRequestContext pollenRestApiRequestContext = PollenRestApiRequestContext.getRequestContext(requestContext); - SessionToken sessionToken = securityService.getSessionTokenByToken(userPollenEntityRef.getPermission()); - pollenRestApiRequestContext.getSecurityContext().setSessionToken(sessionToken); + securityContext.setSessionToken(sessionToken); // add auth cookies - String value = pollenRestApiRequestContext.getSecurityService().encrypt( + String value = securityService.encrypt( sessionToken.getPollenUser().getTopiaId(), sessionToken.getPollenToken().getToken() ); - HttpServletResponse response = requestContext.getResponse(); - Cookie authCookie = new Cookie(COOKIE_POLLEN_AUTH, value); - authCookie.setPath("/"); - authCookie.setMaxAge(COOKIE_MAX_AGE); - response.addCookie(authCookie); - - Cookie connectedCookie = new Cookie(COOKIE_POLLEN_CONNECTED, "true"); - connectedCookie.setPath("/"); - connectedCookie.setMaxAge(COOKIE_MAX_AGE); - response.addCookie(connectedCookie); + NewCookie authCookie = new NewCookie( + COOKIE_POLLEN_AUTH, + value, + "/", + null, + null, + COOKIE_MAX_AGE, + false); + + NewCookie connectedCookie = new NewCookie( + COOKIE_POLLEN_CONNECTED, + "true", + "/", + null, + null, + COOKIE_MAX_AGE, + false); if (log.isDebugEnabled()) { log.debug("Add auth cookie:: " + authCookie.getValue()); } - return userPollenEntityRef; + return Response.ok(userPollenEntityRef).cookie(authCookie, connectedCookie).build(); } throw new MissingAuthenticationException(); } - public PollenEntityRef<PollenUser> login2(SecurityService securityService, String login, String password, Boolean rememberMe) + @Path("/login2") + @POST @PUT + public PollenEntityRef<PollenUser> login2(@Context SecurityService securityService, + @QueryParam("login") String login, + @QueryParam("password") String password, + @QueryParam("rememberMe") Boolean rememberMe) throws PollenAuthenticationException, PollenEmailNotValidatedException { return securityService.login(login, password, rememberMe); } - - public void logout(HttpContext requestContext, SecurityService securityService) { + @Path("/logout") + @GET + public boolean logout(@Context SecurityService securityService, + @Context PollenSecurityContext securityContext) { securityService.logout(); // Remove the session token from security context - PollenRestApiRequestContext.getRequestContext(requestContext).getSecurityContext().setSessionToken(null); - - HttpServletResponse response = requestContext.getResponse(); + securityContext.setSessionToken(null); - removeAuthCookie(response); + return true; } - public void lostPassword(SecurityService securityService, String login) throws PollenEmailNotValidatedException { + @Path("/lostpassword/{login} ") + @GET + public void lostPassword(@Context SecurityService securityService, + @PathParam("login") String login) throws PollenEmailNotValidatedException { securityService.lostPassword(login); } - public void resendValidation(PollenUserService pollenUserService, String login, PollenUIContext pollenUIContext) { + @Path("/resendValidation") + @POST @PUT + public void resendValidation(@Context PollenUserService pollenUserService, + String login) { - pollenUserService.resendValidation(login, pollenUIContext); + pollenUserService.resendValidation(login); } diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/ChoiceApi.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/ChoiceApi.java index ba5d78b3..b42c1c34 100644 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/ChoiceApi.java +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/ChoiceApi.java @@ -30,8 +30,17 @@ import org.chorem.pollen.services.bean.ReportBean; import org.chorem.pollen.services.service.ChoiceService; import org.chorem.pollen.services.service.InvalidFormException; import org.chorem.pollen.services.service.ReportService; -import org.debux.webmotion.server.WebMotionController; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; import java.util.List; /** @@ -40,50 +49,83 @@ import java.util.List; * @author Tony Chemit - dev@tchemit.fr * @since 2.0 */ -public class ChoiceApi extends WebMotionController { +@Path("/choices/{pollId}") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class ChoiceApi { - public List<ChoiceBean> getChoices(ChoiceService choiceService, PollenEntityId<Poll> pollId) { + @GET + public List<ChoiceBean> getChoices(@Context ChoiceService choiceService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { return choiceService.getChoices(pollId.getEntityId()); } - public ChoiceBean getChoice(ChoiceService choiceService, PollenEntityId<Poll> pollId, PollenEntityId<Choice> choiceId) { + @Path("/{choiceId}") + @GET + public ChoiceBean getChoice(@Context ChoiceService choiceService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("choiceId") PollenEntityId<Choice> choiceId) { return choiceService.getChoice(pollId.getEntityId(), choiceId.getEntityId()); } - public PollenEntityRef<Choice> addChoice(ChoiceService choiceService, PollenEntityId<Poll> pollId, ChoiceBean choice) throws InvalidFormException { + @POST + public PollenEntityRef<Choice> addChoice(@Context ChoiceService choiceService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + ChoiceBean choice) throws InvalidFormException { return choiceService.addChoice(pollId.getEntityId(), choice); } - public ChoiceBean editChoice(ChoiceService choiceService, PollenEntityId<Poll> pollId, ChoiceBean choice) throws InvalidFormException { + @Path("/{choiceId}") + @POST @PUT + public ChoiceBean editChoice(@Context ChoiceService choiceService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + ChoiceBean choice) throws InvalidFormException { return choiceService.editChoice(pollId.getEntityId(), choice); } - public void deleteChoice(ChoiceService choiceService, PollenEntityId<Poll> pollId, PollenEntityId<Choice> choiceId) throws InvalidFormException { + @Path("/{choiceId}") + @DELETE + public void deleteChoice(@Context ChoiceService choiceService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("choiceId")PollenEntityId<Choice> choiceId) throws InvalidFormException { choiceService.deleteChoice(pollId.getEntityId(), choiceId.getEntityId()); } - public void addReport(ReportService reportService, PollenEntityId<Poll> pollId, PollenEntityId<Choice> choiceId, ReportBean report) throws InvalidFormException { + @Path("/{choiceId}/reports") + @POST + public void addReport(@Context ReportService reportService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("choiceId")PollenEntityId<Choice> choiceId, + ReportBean report) throws InvalidFormException { reportService.addChoiceReport(pollId.getEntityId(), choiceId.getEntityId(), report); } - public List<ReportBean> getReports(ReportService reportService, PollenEntityId<Poll> pollId, PollenEntityId<Choice> choiceId) { + @Path("/{choiceId}/reports") + @GET + public List<ReportBean> getReports(@Context ReportService reportService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("choiceId")PollenEntityId<Choice> choiceId) { return reportService.getChoiceReports(pollId.getEntityId(), choiceId.getEntityId()); } - public void saveReport(ReportService reportService, PollenEntityId<Poll> pollId, PollenEntityId<Choice> choiceId, ReportBean report) { + @Path("/{choiceId}/reports/{reportId}") + @POST + public void saveReport(@Context ReportService reportService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("choiceId")PollenEntityId<Choice> choiceId, ReportBean report) { reportService.saveChoiceReport(pollId.getEntityId(), choiceId.getEntityId(), report); diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/CommentApi.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/CommentApi.java index f1b8ef18..3e9cb71c 100644 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/CommentApi.java +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/CommentApi.java @@ -32,8 +32,17 @@ import org.chorem.pollen.services.bean.ReportBean; import org.chorem.pollen.services.service.CommentService; import org.chorem.pollen.services.service.InvalidFormException; import org.chorem.pollen.services.service.ReportService; -import org.debux.webmotion.server.WebMotionController; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; import java.util.List; @@ -43,56 +52,94 @@ import java.util.List; * @author Tony Chemit - dev@tchemit.fr * @since 2.0 */ -public class CommentApi extends WebMotionController { +@Path("/comments/{pollId}") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class CommentApi { - public PaginationResultBean<CommentBean> getComments(CommentService commentService, PollenEntityId<Poll> pollId, PaginationParameterBean paginationParameter) { + @GET + public PaginationResultBean<CommentBean> getComments(@Context CommentService commentService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + PaginationParameterBean paginationParameter) { return commentService.getComments(pollId.getEntityId(), paginationParameter); } - public CommentBean getComment(CommentService commentService, PollenEntityId<Poll> pollId, PollenEntityId<Comment> commentId) { + @Path("/{commentId}") + @GET + public CommentBean getComment(@Context CommentService commentService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("commentId") PollenEntityId<Comment> commentId) { return commentService.getComment(pollId.getEntityId(), commentId.getReducedId()); } - public CommentBean getNewComment(CommentService commentService, PollenEntityId<Poll> pollId) { + @Path("/new") + @GET + public CommentBean getNewComment(@Context CommentService commentService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { return commentService.getNewComment(pollId.getEntityId()); } - public PollenEntityRef<Comment> addComment(CommentService commentService, PollenEntityId<Poll> pollId, CommentBean comment) throws InvalidFormException { + @POST + public PollenEntityRef<Comment> addComment(@Context CommentService commentService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + CommentBean comment) throws InvalidFormException { return commentService.addComment(pollId.getEntityId(), comment); } - public CommentBean editComment(CommentService commentService, PollenEntityId<Poll> pollId, CommentBean comment) throws InvalidFormException { + @Path("/{commentId}") + @PUT @POST + public CommentBean editComment(@Context CommentService commentService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + CommentBean comment) throws InvalidFormException { return commentService.editComment(pollId.getEntityId(), comment); } - public void deleteComment(CommentService commentService, PollenEntityId<Poll> pollId, PollenEntityId<Comment> commentId) { + @Path("/{commentId}") + @DELETE + public void deleteComment(@Context CommentService commentService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("commentId") PollenEntityId<Comment> commentId) { commentService.deleteComment(pollId.getEntityId(), commentId.getEntityId()); } - public void addReport(ReportService reportService, PollenEntityId<Poll> pollId, PollenEntityId<Comment> commentId, ReportBean report) throws InvalidFormException { + @Path("/{commentId}/reports") + @POST + public void addReport(@Context ReportService reportService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("commentId") PollenEntityId<Comment> commentId, + ReportBean report) throws InvalidFormException { reportService.addCommentReport(pollId.getEntityId(), commentId.getEntityId(), report); } - public List<ReportBean> getReports(ReportService reportService, PollenEntityId<Poll> pollId, PollenEntityId<Comment> commentId) { + @Path("/{commentId}/reports") + @GET + public List<ReportBean> getReports(@Context ReportService reportService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("commentId") PollenEntityId<Comment> commentId) { return reportService.getCommentReports(pollId.getEntityId(), commentId.getEntityId()); } - public void saveReport(ReportService reportService, PollenEntityId<Poll> pollId, PollenEntityId<Comment> commentId, ReportBean report) { + @Path("/{commentId}/reports/{reportId}") + @POST + public void saveReport(@Context ReportService reportService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("commentId") PollenEntityId<Comment> commentId, + ReportBean report) { reportService.saveCommentReport(pollId.getEntityId(), commentId.getEntityId(), report); diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/DocApi.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/DocApi.java index 550d4db8..de442fed 100644 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/DocApi.java +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/DocApi.java @@ -23,9 +23,11 @@ package org.chorem.pollen.rest.api.v1; import org.apache.commons.io.IOUtils; import org.chorem.pollen.services.PollenTechnicalException; -import org.debux.webmotion.server.WebMotionController; -import org.debux.webmotion.server.render.Render; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; @@ -36,16 +38,19 @@ import java.nio.charset.StandardCharsets; * @author Tony Chemit - dev@tchemit.fr * @since 2.0 */ -public class DocApi extends WebMotionController { +@Path("/doc") +public class DocApi { - public Render showMapping() { + @GET + @Produces(MediaType.TEXT_PLAIN) + public String showMapping() { InputStream mappingUrl = getClass().getResourceAsStream("/mapping"); try { String content = IOUtils.toString(mappingUrl, StandardCharsets.UTF_8); - return renderContent(content, "text/plain"); + return content; } catch (IOException e) { diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/ErrorAction.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/ErrorAction.java deleted file mode 100644 index 5592d84b..00000000 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/ErrorAction.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.chorem.pollen.rest.api.v1; - -/* - * #%L - * Pollen :: Rest Api - * %% - * Copyright (C) 2009 - 2017 Code Lutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.chorem.pollen.rest.api.PollenRenderError; -import org.chorem.pollen.services.service.FavoriteListImportException; -import org.chorem.pollen.services.service.InvalidFormException; -import org.debux.webmotion.server.WebMotionController; -import org.debux.webmotion.server.call.HttpContext; -import org.debux.webmotion.server.render.Render; - -import javax.servlet.http.HttpServletResponse; - -/** - * TODO - * - * @author Tony Chemit - dev@tchemit.fr - * @since 2.0 - */ -public class ErrorAction extends WebMotionController { - - private static final Log log = LogFactory.getLog(ErrorAction.class); - - public InvalidFormException on400Form(HttpContext context, InvalidFormException e) { - - // just return the exception, - return e; - - } - - public FavoriteListImportException on400Import(HttpContext context, FavoriteListImportException e) { - if (log.isErrorEnabled()) { - log.error(e.getMessage(), e); - } - - // just return the exception, - return e; - - } - - public Render on404(HttpContext context, Exception e) { - - return pollenRenderError(HttpServletResponse.SC_NOT_FOUND, e.getMessage()); - - } - - public Render on401(HttpContext context, Exception e) { - - return pollenRenderError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage(), true); - - } - - public Render on403(HttpContext context, Exception e) { - - return pollenRenderError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); - - } - - public Render on500(HttpContext context, Exception e) { - - return pollenRenderError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - - } - - public Render pollenRenderError(int scNotFound, String message) { - return new PollenRenderError(scNotFound, message); - } - - public Render pollenRenderError(int scNotFound, String message, boolean removeConnexionCookie) { - return new PollenRenderError(scNotFound, message, removeConnexionCookie); - } - -} diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/FavoriteListApi.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/FavoriteListApi.java index 93233ddd..c202234b 100644 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/FavoriteListApi.java +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/FavoriteListApi.java @@ -21,8 +21,6 @@ package org.chorem.pollen.rest.api.v1; * #L% */ -import com.google.common.base.Charsets; -import org.apache.commons.io.IOUtils; import org.chorem.pollen.persistence.entity.ChildFavoriteList; import org.chorem.pollen.persistence.entity.FavoriteList; import org.chorem.pollen.persistence.entity.FavoriteListMember; @@ -35,15 +33,26 @@ import org.chorem.pollen.services.bean.PaginationResultBean; import org.chorem.pollen.services.bean.PollenBean; import org.chorem.pollen.services.bean.PollenEntityId; import org.chorem.pollen.services.bean.PollenEntityRef; +import org.chorem.pollen.services.bean.ResourceFileBean; import org.chorem.pollen.services.bean.export.ExportBean; import org.chorem.pollen.services.service.FavoriteListImportException; import org.chorem.pollen.services.service.FavoriteListService; import org.chorem.pollen.services.service.InvalidFormException; -import org.debux.webmotion.server.WebMotionController; -import org.debux.webmotion.server.call.UploadFile; -import org.debux.webmotion.server.render.Render; - -import java.io.InputStream; +import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput; + +import javax.ws.rs.BeanParam; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; /** * TODO @@ -51,130 +60,215 @@ import java.io.InputStream; * @author Tony Chemit - dev@tchemit.fr * @since 2.0 */ -public class FavoriteListApi extends WebMotionController { +@Path("/favoriteLists") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class FavoriteListApi { - public PaginationResultBean<FavoriteListBean> getFavoriteLists(FavoriteListService favoriteListService, PaginationParameterBean paginationParameter, String search) { + @GET + public PaginationResultBean<FavoriteListBean> getFavoriteLists(@Context FavoriteListService favoriteListService, + @BeanParam PaginationParameterBean paginationParameter, + @QueryParam("search") String search) { return favoriteListService.getFavoriteLists(paginationParameter, search); } - public FavoriteListBean getFavoriteList(FavoriteListService favoriteListService, PollenEntityId<FavoriteList> favoriteListId) { - - return favoriteListService.getFavoriteList(favoriteListId.getEntityId()); - - } + @Path("/imports") + @POST + @Consumes("multipart/form-data") + public int importFavoriteLists(@Context FavoriteListService favoriteListService, + MultipartFormDataInput input) throws InvalidFormException { - public int importFavoriteLists(FavoriteListService favoriteListService, UploadFile importFile) throws InvalidFormException { - return favoriteListService.importFavoriteLists(importFile.getFile()); + ResourceFileBean resourceFileBean = ApiUtils.multipartToResourceBean(input, "importFile"); + return favoriteListService.importFavoriteLists(resourceFileBean.getFile()); } - public Render exportFavoriteLists(FavoriteListService favoriteListService) { + @Path("/exports") + @GET + @Produces(MediaType.APPLICATION_OCTET_STREAM) + public Response exportFavoriteLists(@Context FavoriteListService favoriteListService) { ExportBean exportBean = favoriteListService.exportFavoriteLists(); - InputStream inputStream = IOUtils.toInputStream(exportBean.getContent(), Charsets.UTF_8); + return ApiUtils.exportBeanToResponse(exportBean); + } + + @Path("/{favoriteListId}") + @GET + public FavoriteListBean getFavoriteList(@Context FavoriteListService favoriteListService, + @PathParam("favoriteListId") PollenEntityId<FavoriteList> favoriteListId) { + + return favoriteListService.getFavoriteList(favoriteListId.getEntityId()); - return renderDownload(inputStream, exportBean.getName(), exportBean.getContentType()); } - public PollenEntityRef<FavoriteList> createFavoriteList(FavoriteListService favoriteListService, FavoriteListBean favoriteList) throws InvalidFormException { + + + @POST + public PollenEntityRef<FavoriteList> createFavoriteList(@Context FavoriteListService favoriteListService, + FavoriteListBean favoriteList) throws InvalidFormException { return favoriteListService.createFavoriteList(favoriteList); } - public FavoriteListBean editFavoriteList(FavoriteListService favoriteListService, FavoriteListBean favoriteList) throws InvalidFormException { + @Path("/{favoriteListId}") + @PUT @POST + public FavoriteListBean editFavoriteList(@Context FavoriteListService favoriteListService, + FavoriteListBean favoriteList) throws InvalidFormException { return favoriteListService.editFavoriteList(favoriteList); } - public void deleteFavoriteList(FavoriteListService favoriteListService, PollenEntityId<FavoriteList> favoriteListId) { + @Path("/{favoriteListId}") + @DELETE + public void deleteFavoriteList(@Context FavoriteListService favoriteListService, + @PathParam("favoriteListId") PollenEntityId<FavoriteList> favoriteListId) { favoriteListService.deleteFavoriteList(favoriteListId.getEntityId()); } - public void importFavoriteListMembersFromCsv(FavoriteListService favoriteListService, PollenEntityId<FavoriteList> favoriteListId, UploadFile csvFile) throws FavoriteListImportException { - - favoriteListService.importFavoriteListMembersFromCsv(favoriteListId.getEntityId(), csvFile.getFile()); + @Path("/{favoriteListId}/importCsv") + @POST + @Consumes("multipart/form-data") + public void importFavoriteListMembersFromCsv(@Context FavoriteListService favoriteListService, + @PathParam("favoriteListId") PollenEntityId<FavoriteList> favoriteListId, + MultipartFormDataInput input) throws FavoriteListImportException { + ResourceFileBean resourceFileBean = ApiUtils.multipartToResourceBean(input, "csvFile"); + favoriteListService.importFavoriteListMembersFromCsv(favoriteListId.getEntityId(), resourceFileBean.getFile()); } - public void importFavoriteListMembersFromLdap(FavoriteListService favoriteListService, PollenEntityId<FavoriteList> favoriteListId, String ldap) throws FavoriteListImportException { + @Path("/{favoriteListId}/importLdap") + @POST + public void importFavoriteListMembersFromLdap(@Context FavoriteListService favoriteListService, + @PathParam("favoriteListId") PollenEntityId<FavoriteList> favoriteListId, + String ldap) throws FavoriteListImportException { favoriteListService.importFavoriteListMembersFromLdap(favoriteListId.getEntityId(), ldap); } - public FavoriteListBean importFavoriteListMembersFromVoterList(FavoriteListService favoriteListService, PollenEntityId<VoterList> voterListId) throws FavoriteListImportException, InvalidFormException { + @Path("/importVoterList") + @POST + public FavoriteListBean importFavoriteListMembersFromVoterList(@Context FavoriteListService favoriteListService, + @QueryParam("voterListId") PollenEntityId<VoterList> voterListId) throws FavoriteListImportException, InvalidFormException { return favoriteListService.importFavoriteListMembersFromVoterList(voterListId.getEntityId()); } - public PaginationResultBean<FavoriteListMemberBean> getMembers(FavoriteListService favoriteListService, PollenEntityId<FavoriteList> favoriteListId, String search, PaginationParameterBean paginationParameter) { + @Path("/{favoriteListId}/members") + @GET + public PaginationResultBean<FavoriteListMemberBean> getMembers(@Context FavoriteListService favoriteListService, + @PathParam("favoriteListId") PollenEntityId<FavoriteList> favoriteListId, + @QueryParam("search") String search, + @BeanParam PaginationParameterBean paginationParameter) { return favoriteListService.getFavoriteListMembers(favoriteListId.getEntityId(), search, paginationParameter); } - public FavoriteListMemberBean getMember(FavoriteListService favoriteListService, PollenEntityId<FavoriteList> favoriteListId, PollenEntityId<FavoriteListMember> memberId) { + @Path("/{favoriteListId}/members/{memberId}") + @GET + public FavoriteListMemberBean getMember(@Context FavoriteListService favoriteListService, + @PathParam("favoriteListId") PollenEntityId<FavoriteList> favoriteListId, + @PathParam("memberId") PollenEntityId<FavoriteListMember> memberId) { return favoriteListService.getFavoriteListMember(favoriteListId.getEntityId(), memberId.getEntityId()); } - public PollenEntityRef<FavoriteListMember> addMember(FavoriteListService favoriteListService, PollenEntityId<FavoriteList> favoriteListId, FavoriteListMemberBean member) throws InvalidFormException { + @Path("/{favoriteListId}/members") + @POST + public PollenEntityRef<FavoriteListMember> addMember(@Context FavoriteListService favoriteListService, + @PathParam("favoriteListId") PollenEntityId<FavoriteList> favoriteListId, + FavoriteListMemberBean member) throws InvalidFormException { return favoriteListService.addFavoriteListMember(favoriteListId.getEntityId(), member); } - public FavoriteListMemberBean editMember(FavoriteListService favoriteListService, PollenEntityId<FavoriteList> favoriteListId, FavoriteListMemberBean member) throws InvalidFormException { + @Path("/{favoriteListId}/members/{memberId}") + @PUT @POST + public FavoriteListMemberBean editMember(@Context FavoriteListService favoriteListService, + @PathParam("favoriteListId") PollenEntityId<FavoriteList> favoriteListId, + FavoriteListMemberBean member) throws InvalidFormException { return favoriteListService.editFavoriteListMember(favoriteListId.getEntityId(), member); } - public void removeMember(FavoriteListService favoriteListService, PollenEntityId<FavoriteList> favoriteListId, PollenEntityId<FavoriteListMember> memberId) { + @Path("/{favoriteListId}/members/{memberId}") + @DELETE + public void removeMember(@Context FavoriteListService favoriteListService, + @PathParam("favoriteListId") PollenEntityId<FavoriteList> favoriteListId, + @PathParam("memberId") PollenEntityId<FavoriteListMember> memberId) { favoriteListService.deleteFavoriteListMember(favoriteListId.getEntityId(), memberId.getEntityId()); } - public PaginationResultBean<ChildFavoriteListBean> getChildrenLists(FavoriteListService favoriteListService, PollenEntityId<FavoriteList> favoriteListId, String search, PaginationParameterBean paginationParameter) { + @Path("/{favoriteListId}/lists") + @GET + public PaginationResultBean<ChildFavoriteListBean> getChildrenLists(@Context FavoriteListService favoriteListService, + @PathParam("favoriteListId") PollenEntityId<FavoriteList> favoriteListId, + @QueryParam("search") String search, + @BeanParam PaginationParameterBean paginationParameter) { return favoriteListService.getChildrenLists(favoriteListId.getEntityId(), search, paginationParameter); } - public ChildFavoriteListBean getChildList(FavoriteListService favoriteListService, PollenEntityId<FavoriteList> favoriteListId, PollenEntityId<ChildFavoriteList> childListId) { + @Path("/{favoriteListId}/lists/{childListId}") + @GET + public ChildFavoriteListBean getChildList(@Context FavoriteListService favoriteListService, + @PathParam("favoriteListId") PollenEntityId<FavoriteList> favoriteListId, + @PathParam("childListId") PollenEntityId<ChildFavoriteList> childListId) { return favoriteListService.getChildList(favoriteListId.getEntityId(), childListId.getEntityId()); } - public PollenEntityRef<ChildFavoriteList> addChildList(FavoriteListService favoriteListService, PollenEntityId<FavoriteList> favoriteListId, ChildFavoriteListBean childList) throws InvalidFormException { + @Path("/{favoriteListId}/lists") + @POST + public PollenEntityRef<ChildFavoriteList> addChildList(@Context FavoriteListService favoriteListService, + @PathParam("favoriteListId") PollenEntityId<FavoriteList> favoriteListId, + ChildFavoriteListBean childList) throws InvalidFormException { return favoriteListService.addChildList(favoriteListId.getEntityId(), childList); } - public ChildFavoriteListBean editChildList(FavoriteListService favoriteListService, PollenEntityId<FavoriteList> favoriteListId, ChildFavoriteListBean childList) throws InvalidFormException { + @Path("/{favoriteListId}/lists/{childListId}") + @POST @PUT + public ChildFavoriteListBean editChildList(@Context FavoriteListService favoriteListService, + @PathParam("favoriteListId") PollenEntityId<FavoriteList> favoriteListId, + ChildFavoriteListBean childList) throws InvalidFormException { return favoriteListService.editChildList(favoriteListId.getEntityId(), childList); } - public void removeChildList(FavoriteListService favoriteListService, PollenEntityId<FavoriteList> favoriteListId, PollenEntityId<ChildFavoriteList> childListId) { + @Path("/{favoriteListId}/lists/{childListId}") + @DELETE + public void removeChildList(@Context FavoriteListService favoriteListService, + @PathParam("favoriteListId") PollenEntityId<FavoriteList> favoriteListId, + @PathParam("childListId") PollenEntityId<ChildFavoriteList> childListId) { favoriteListService.removeChildList(favoriteListId.getEntityId(), childListId.getEntityId()); } - public PaginationResultBean<PollenBean> getAllChildren(FavoriteListService favoriteListService, PollenEntityId<FavoriteList> favoriteListId, String search, PaginationParameterBean paginationParameter) { + @Path("/{favoriteListId}/all") + @GET + public PaginationResultBean<PollenBean> getAllChildren(@Context FavoriteListService favoriteListService, + @PathParam("favoriteListId") PollenEntityId<FavoriteList> favoriteListId, + @QueryParam("search") String search, + @BeanParam PaginationParameterBean paginationParameter) { return favoriteListService.getAllChildren(favoriteListId.getEntityId(), search, paginationParameter); diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/PollApi.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/PollApi.java index 64be44f9..7656fcb5 100644 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/PollApi.java +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/PollApi.java @@ -21,26 +21,35 @@ package org.chorem.pollen.rest.api.v1; * #L% */ -import com.google.common.collect.Lists; +import com.rometools.rome.feed.atom.Feed; +import com.rometools.rome.feed.synd.SyndFeed; import org.chorem.pollen.persistence.entity.ChoiceType; import org.chorem.pollen.persistence.entity.Poll; -import org.chorem.pollen.services.bean.ChoiceBean; +import org.chorem.pollen.rest.api.beans.PollCreateBean; import org.chorem.pollen.services.bean.PaginationParameterBean; import org.chorem.pollen.services.bean.PaginationResultBean; import org.chorem.pollen.services.bean.PollBean; import org.chorem.pollen.services.bean.PollenEntityId; import org.chorem.pollen.services.bean.PollenEntityRef; import org.chorem.pollen.services.bean.ReportBean; -import org.chorem.pollen.services.bean.VoterListBean; -import org.chorem.pollen.services.bean.VoterListMemberBean; +import org.chorem.pollen.services.bean.export.ExportBean; import org.chorem.pollen.services.service.FeedService; import org.chorem.pollen.services.service.InvalidFormException; import org.chorem.pollen.services.service.PollService; import org.chorem.pollen.services.service.ReportService; -import org.debux.webmotion.server.WebMotionController; -import org.debux.webmotion.server.render.Render; -import java.io.File; +import javax.ws.rs.BeanParam; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import java.util.List; /** @@ -49,113 +58,170 @@ import java.util.List; * @author Tony Chemit - dev@tchemit.fr * @since 2.0 */ -public class PollApi extends WebMotionController { +@Path("/polls") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class PollApi { - public PollBean getNewPoll(PollService pollService, ChoiceType choiceType) { - return pollService.getNewPoll(choiceType); + @GET + @Path("/new") + public PollBean getNewPoll(@Context PollService pollService) { + + return pollService.getNewPoll(ChoiceType.TEXT); } - public PaginationResultBean<PollBean> getPolls(PollService pollService, PaginationParameterBean paginationParameter) { + @GET + public PaginationResultBean<PollBean> getPolls(@Context PollService pollService, + @BeanParam PaginationParameterBean paginationParameter) { return pollService.getPolls(paginationParameter); } - public PaginationResultBean<PollBean> getCreatedPolls(PollService pollService, PaginationParameterBean paginationParameter) { + @GET + @Path("/created") + public PaginationResultBean<PollBean> getCreatedPolls(@Context PollService pollService, + @BeanParam PaginationParameterBean paginationParameter) { return pollService.getCreatedPolls(paginationParameter); } - public PaginationResultBean<PollBean> getInvitedPolls(PollService pollService, PaginationParameterBean paginationParameter) { + @GET + @Path("/invited") + public PaginationResultBean<PollBean> getInvitedPolls(@Context PollService pollService, + @BeanParam PaginationParameterBean paginationParameter) { return pollService.getInvitedPolls(paginationParameter); } - public PaginationResultBean<PollBean> getParticipatedPolls(PollService pollService, PaginationParameterBean paginationParameter) { + @GET + @Path("/participated") + public PaginationResultBean<PollBean> getParticipatedPolls(@Context PollService pollService, + @BeanParam PaginationParameterBean paginationParameter) { return pollService.getParticipatedPolls(paginationParameter); } - public PollBean getPoll(PollService pollService, PollenEntityId<Poll> pollId) { + @POST + public PollenEntityRef<Poll> createPoll(@Context PollService pollService, + PollCreateBean pollCreateBean) throws InvalidFormException { - return pollService.getPoll(pollId.getEntityId()); + return pollService.createPoll(pollCreateBean.getPoll(), + pollCreateBean.getChoices(), + pollCreateBean.getVoterLists(), + pollCreateBean.getVoterListMembers()); } - public PollenEntityRef<Poll> createPoll(PollService pollService, - PollBean poll, - ChoiceBean[] choices, - VoterListBean[] voterLists, - VoterListMemberBean[] voterListMembers) throws InvalidFormException { - - List<ChoiceBean> choiceList = Lists.newArrayList(choices); - List<VoterListBean> voterListList = Lists.newArrayList(voterLists); - List<VoterListMemberBean> voterListMemberList = Lists.newArrayList(voterListMembers); + @Path("/{pollId}") + @GET + public PollBean getPoll(@Context PollService pollService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { - return pollService.createPoll(poll, choiceList, voterListList, voterListMemberList); + return pollService.getPoll(pollId.getEntityId()); } - public PollBean editPoll(PollService pollService, PollBean poll) throws InvalidFormException { + @Path("/{pollId}") + @PUT + @POST + public PollBean editPoll(@Context PollService pollService, + PollBean poll) throws InvalidFormException { return pollService.editPoll(poll); } - public void deletePoll(PollService pollService, PollenEntityId<Poll> pollId) { + @Path("/{pollId}") + @DELETE + public void deletePoll(@Context PollService pollService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { pollService.deletePoll(pollId.getEntityId()); } - public PollenEntityRef<Poll> clonePoll(PollService pollService, PollenEntityId<Poll> pollId) { + @Path("/{pollId}/clone") + @POST + public PollenEntityRef<Poll> clonePoll(@Context PollService pollService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { return pollService.clonePoll(pollId.getEntityId()); } - public void closePoll(PollService pollService, PollenEntityId<Poll> pollId) { + @Path("/{pollId}/close") + @PUT + public void closePoll(@Context PollService pollService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { pollService.closePoll(pollId.getEntityId()); } - public void reopenPoll(PollService pollService, PollenEntityId<Poll> pollId) { + + @Path("/{pollId}/reopen") + @POST + public void reopenPoll(@Context PollService pollService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { pollService.reopenPoll(pollId.getEntityId()); } - public File exportPoll(PollService pollService, PollenEntityId<Poll> pollId) { + @Path("/{pollId}/export") + @GET + @Produces(MediaType.APPLICATION_OCTET_STREAM) + public Response exportPoll(@Context PollService pollService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { - return pollService.exportPoll(pollId.getEntityId()); + ExportBean exportBean = pollService.exportPoll(pollId.getEntityId()); + return ApiUtils.exportBeanToResponse(exportBean); } - public PollBean assignPoll(PollService pollService, PollenEntityId<Poll> pollId) { + @Path("/{pollId}/assign") + @PUT + public PollBean assignPoll(@Context PollService pollService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { return pollService.assignPollToConnectedUser(pollId.getEntityId()); } - public Render getFeedForPoll(FeedService feedService, PollenEntityId<Poll> pollId) { - return renderAtom(feedService.getFeedForPoll(pollId.getEntityId())); + @Path("/{pollId}/feed") + @Produces(MediaType.APPLICATION_ATOM_XML) + public Feed getFeedForPoll(@Context FeedService feedService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { + SyndFeed feedForPoll = feedService.getFeedForPoll(pollId.getEntityId()); + return ApiUtils.syndFeedToFeed(feedForPoll); } - public void addReport(ReportService reportService, PollenEntityId<Poll> pollId, ReportBean report) throws InvalidFormException { + @Path("/{pollId}/reports") + @POST + public void addReport(@Context ReportService reportService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + ReportBean report) throws InvalidFormException { reportService.addPollReport(pollId.getEntityId(), report); } - public List<ReportBean> getReports(ReportService reportService, PollenEntityId<Poll> pollId) { + @Path("/{pollId}/reports") + @GET + public List<ReportBean> getReports(@Context ReportService reportService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { return reportService.getPollReports(pollId.getEntityId()); } - public void saveReport(ReportService reportService, PollenEntityId<Poll> pollId, ReportBean report) { + @Path("/{pollId}/reports/{reportId}") + @POST + public void saveReport(@Context ReportService reportService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + ReportBean report) { reportService.savePollReport(pollId.getEntityId(), report); diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/PollenResourceApi.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/PollenResourceApi.java index 49124c34..2556c82d 100644 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/PollenResourceApi.java +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/PollenResourceApi.java @@ -29,11 +29,19 @@ import org.chorem.pollen.services.bean.ResourceMetaBean; import org.chorem.pollen.services.bean.ResourceStreamBean; import org.chorem.pollen.services.service.InvalidFormException; import org.chorem.pollen.services.service.PollenResourceService; -import org.debux.webmotion.server.WebMotionController; -import org.debux.webmotion.server.call.UploadFile; -import org.debux.webmotion.server.render.Render; +import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput; import javax.imageio.ImageIO; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; @@ -46,23 +54,36 @@ import java.io.IOException; * @author dralagen * @since 2.0 */ -public class PollenResourceApi extends WebMotionController { +@Path("/resources") +public class PollenResourceApi { - public Render getResource(PollenResourceService pollenResourceService, PollenEntityId<PollenResource> resourceId) { + @Path("/{resourceId}") + @GET + @Produces(MediaType.APPLICATION_OCTET_STREAM) + public Response getResource(@Context PollenResourceService pollenResourceService, + @PathParam("resourceId") PollenEntityId<PollenResource> resourceId) { ResourceStreamBean resource = pollenResourceService.getResource(resourceId.getEntityId()); - return renderStream(resource.getResourceContent(), resource.getContentType()); + return Response.ok(resource.getResourceContent(), resource.getContentType()).build(); } - public Render getDownloadResource(PollenResourceService pollenResourceService, PollenEntityId<PollenResource> resourceId) { + @Path("/{resourceId}/download") + @GET + @Produces(MediaType.APPLICATION_OCTET_STREAM) + public Response getDownloadResource(@Context PollenResourceService pollenResourceService, + @PathParam("resourceId") PollenEntityId<PollenResource> resourceId) { ResourceStreamBean resource = pollenResourceService.getResource(resourceId.getEntityId()); - return renderDownload(resource.getResourceContent(), resource.getName(), resource.getContentType()); + return ApiUtils.ResponseDownload(resource.getResourceContent(), resource.getName(), resource.getContentType()); } - public Render getPreviewResource(PollenResourceService pollenResourceService, PollenEntityId<PollenResource> resourceId) throws IOException { + @Path("/{resourceId}/preview") + @GET + @Produces(MediaType.APPLICATION_OCTET_STREAM) + public Response getPreviewResource(@Context PollenResourceService pollenResourceService, + @PathParam("resourceId") PollenEntityId<PollenResource> resourceId) throws IOException { ResourceStreamBean resource = pollenResourceService.getResource(resourceId.getEntityId()); String contentType; @@ -99,48 +120,51 @@ public class PollenResourceApi extends WebMotionController { ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageIO.write(destination, contentType.split("/")[1], output); - return renderStream(new ByteArrayInputStream(output.toByteArray()), contentType); + return Response.ok(new ByteArrayInputStream(output.toByteArray()), contentType).build(); } - public ResourceMetaBean getMetaResource(PollenResourceService pollenResourceService, PollenEntityId<PollenResource> resourceId) { + @Path("/{resourceId}/meta") + @GET + @Produces(MediaType.APPLICATION_JSON) + public ResourceMetaBean getMetaResource(@Context PollenResourceService pollenResourceService, + @PathParam("resourceId") PollenEntityId<PollenResource> resourceId) { return pollenResourceService.getMetaResource(resourceId.getEntityId()); } - public PollenEntityRef<PollenResource> createResource(PollenResourceService pollenResourceService, UploadFile resource) throws InvalidFormException { + @POST + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + public PollenEntityRef<PollenResource> createResource(@Context PollenResourceService pollenResourceService, + MultipartFormDataInput input) throws InvalidFormException { - ResourceFileBean resourceBean = new ResourceFileBean(); - - resourceBean.setFile(resource.getFile()); - resourceBean.setName(resource.getName()); - resourceBean.setContentType(resource.getContentType()); - resourceBean.setSize(resource.getSize()); + ResourceFileBean resourceBean = ApiUtils.multipartToResourceBean(input, "resource"); PollenEntityRef<PollenResource> createRef = pollenResourceService.createResource(resourceBean); - resource.getFile().delete(); - return createRef; } - public PollenEntityRef<PollenResource> editResource(PollenResourceService pollenResourceService, PollenEntityId<PollenResource> resourceId, UploadFile resource) throws InvalidFormException { - - ResourceFileBean resourceBean = new ResourceFileBean(); - - resourceBean.setFile(resource.getFile()); - resourceBean.setName(resource.getName()); - resourceBean.setContentType(resource.getContentType()); - resourceBean.setSize(resource.getSize()); + @Path("/{resourceId}") + @POST + @Consumes(MediaType.MULTIPART_FORM_DATA) + public PollenEntityRef<PollenResource> editResource(@Context PollenResourceService pollenResourceService, + @PathParam("resourceId") PollenEntityId<PollenResource> resourceId, + MultipartFormDataInput input) throws InvalidFormException { + ResourceFileBean resourceBean = ApiUtils.multipartToResourceBean(input, "resource"); PollenEntityRef<PollenResource> createRef = pollenResourceService.editResource(resourceId.getEntityId(), resourceBean); - resource.getFile().delete(); + resourceBean.getFile().delete(); return createRef; } - public void deleteResource(PollenResourceService pollenResourceService, PollenEntityId<PollenResource> resourceId) { + @Path("/{resourceId}") + @DELETE + public void deleteResource(@Context PollenResourceService pollenResourceService, + @PathParam("resourceId") PollenEntityId<PollenResource> resourceId) { pollenResourceService.deleteResource(resourceId.getEntityId()); } diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/PollenUserApi.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/PollenUserApi.java index 52036c42..9c335d75 100644 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/PollenUserApi.java +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/PollenUserApi.java @@ -22,8 +22,7 @@ package org.chorem.pollen.rest.api.v1; */ import org.chorem.pollen.persistence.entity.PollenUser; -import org.chorem.pollen.rest.api.PollenRestApiRequestContext; -import org.chorem.pollen.services.PollenUIContext; +import org.chorem.pollen.rest.api.beans.ChangePasswordBean; import org.chorem.pollen.services.bean.PaginationParameterBean; import org.chorem.pollen.services.bean.PaginationResultBean; import org.chorem.pollen.services.bean.PollenEntityId; @@ -32,9 +31,20 @@ import org.chorem.pollen.services.bean.PollenUserBean; import org.chorem.pollen.services.service.InvalidFormException; import org.chorem.pollen.services.service.PollenUserService; import org.chorem.pollen.services.service.security.PollenInvalidEmailActivationTokenException; -import org.debux.webmotion.server.WebMotionController; -import org.debux.webmotion.server.call.HttpContext; - +import org.chorem.pollen.services.service.security.PollenSecurityContext; + +import javax.ws.rs.BeanParam; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; import java.util.Objects; /** @@ -43,83 +53,113 @@ import java.util.Objects; * @author Tony Chemit - dev@tchemit.fr * @since 2.0 */ -public class PollenUserApi extends WebMotionController { +@Path("/users") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class PollenUserApi { - public PaginationResultBean<PollenUserBean> getUsers(PollenUserService pollenUserService, PaginationParameterBean paginationParameter) { + @GET + public PaginationResultBean<PollenUserBean> getUsers(@Context PollenUserService pollenUserService, + @BeanParam PaginationParameterBean paginationParameter) { return pollenUserService.getUsers(paginationParameter); } - public PollenUserBean getConnectedUser(HttpContext context, PollenUserService pollenUserService) { - PollenRestApiRequestContext pollenRestApiRequestContext = PollenRestApiRequestContext.getRequestContext(context); - PollenUser pollenUser = pollenRestApiRequestContext.getSecurityContext().getPollenUser(); + @Path("/connected") + @GET + public PollenUserBean getConnectedUser(@Context PollenSecurityContext securityContext, @Context PollenUserService pollenUserService) { + PollenUser pollenUser = securityContext.getPollenUser(); Objects.requireNonNull(pollenUser,"Could not find connected user"); return pollenUserService.getUser(pollenUser.getTopiaId()); } - public PollenUserBean getUser(PollenUserService pollenUserService, PollenEntityId<PollenUser> userId) { + @Path("/{userId}") + @GET + public PollenUserBean getUser(@Context PollenUserService pollenUserService, + @PathParam("userId") PollenEntityId<PollenUser> userId) { return pollenUserService.getUser(userId.getEntityId()); } - public PollenEntityRef<PollenUser> createUser(PollenUserService pollenUserService, - PollenUserBean user, - PollenUIContext pollenUIContext) throws InvalidFormException { + @POST + public PollenEntityRef<PollenUser> createUser(@Context PollenUserService pollenUserService, + PollenUserBean user) throws InvalidFormException { - return pollenUserService.createUser(user, pollenUIContext); + return pollenUserService.createUser(user); } - public PollenUserBean editUser(PollenUserService pollenUserService, + @Path("/{userId}") + @POST + public PollenUserBean editUser(@Context PollenUserService pollenUserService, PollenUserBean user) throws InvalidFormException { return pollenUserService.editUser(user); } - public PollenUserBean adminUser(PollenUserService pollenUserService, + @Path("/{userId}/admin") + @POST + public PollenUserBean adminUser(@Context PollenUserService pollenUserService, PollenUserBean user) { return pollenUserService.adminUser(user); } - public void deleteUser(PollenUserService pollenUserService, PollenEntityId<PollenUser> userId, boolean anonymize) { + @Path("/{userId}") + @DELETE + public void deleteUser(@Context PollenUserService pollenUserService, + @PathParam("userId") PollenEntityId<PollenUser> userId, + @QueryParam("anonymize") boolean anonymize) { pollenUserService.deleteUser(userId.getEntityId(), anonymize); } - public void banUser(PollenUserService pollenUserService, PollenEntityId<PollenUser> userId, boolean anonymize) { + @Path("/{userId}/ban") + @DELETE + public void banUser(@Context PollenUserService pollenUserService, + @PathParam("userId") PollenEntityId<PollenUser> userId, + @QueryParam("anonymize") boolean anonymize) { pollenUserService.banUser(userId.getEntityId(), anonymize); } - public void makeAdmin(PollenUserService pollenUserService, PollenEntityId<PollenUser> userId) { + @Path("/{userId}/makeAdmin") + @POST + public void makeAdmin(@Context PollenUserService pollenUserService, + @PathParam("userId") PollenEntityId<PollenUser> userId) { pollenUserService.makeAdmin(userId.getEntityId()); } - public void unmakeAdmin(PollenUserService pollenUserService, PollenEntityId<PollenUser> userId) { + @Path("/{userId}/unmakeAdmin") + @POST + public void unmakeAdmin(@Context PollenUserService pollenUserService, + @PathParam("userId") PollenEntityId<PollenUser> userId) { pollenUserService.unmakeAdmin(userId.getEntityId()); } - public void validateUserEmail(PollenUserService pollenUserService, - PollenEntityId<PollenUser> userId, - String token) throws PollenInvalidEmailActivationTokenException { + @Path("/{userId}") + @PUT + public void validateUserEmail(@Context PollenUserService pollenUserService, + @PathParam("userId") PollenEntityId<PollenUser> userId, + @QueryParam("token") String token) throws PollenInvalidEmailActivationTokenException { pollenUserService.validateUserEmail(userId.getEntityId(), token); } - public void changePassword(PollenUserService pollenUserService, - PollenEntityId<PollenUser> userId, - String oldPassword, - String newPassword) throws InvalidFormException { + @Path("/{userId}/password") + @PUT @POST + public void changePassword(@Context PollenUserService pollenUserService, + @PathParam("userId") PollenEntityId<PollenUser> userId, + ChangePasswordBean bean) throws InvalidFormException { - pollenUserService.changePassword(userId.getEntityId(), oldPassword, newPassword); + pollenUserService.changePassword(userId.getEntityId(), bean.getOldPassword(), bean.getNewPassword()); } } diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoteApi.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoteApi.java index f3fc6465..8fb2478c 100644 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoteApi.java +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoteApi.java @@ -28,8 +28,17 @@ import org.chorem.pollen.services.bean.PollenEntityRef; import org.chorem.pollen.services.bean.VoteBean; import org.chorem.pollen.services.service.InvalidFormException; import org.chorem.pollen.services.service.VoteService; -import org.debux.webmotion.server.WebMotionController; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; import java.util.List; /** @@ -38,39 +47,62 @@ import java.util.List; * @author Tony Chemit - dev@tchemit.fr * @since 2.0 */ -public class VoteApi extends WebMotionController { +@Path("/votes/{pollId}") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class VoteApi { - public VoteBean getNewVote(VoteService voteService, PollenEntityId<Poll> pollId) { + @Path("/new") + @GET + public VoteBean getNewVote(@Context VoteService voteService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { return voteService.getNewVote(pollId.getEntityId()); } - public List<VoteBean> getVotes(VoteService voteService, PollenEntityId<Poll> pollId) { + @GET + public List<VoteBean> getVotes(@Context VoteService voteService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { return voteService.getVotes(pollId.getEntityId()); } - public VoteBean getVote(VoteService voteService, PollenEntityId<Poll> pollId, PollenEntityId<Vote> voteId) { + @Path("/{voteId}") + @GET + public VoteBean getVote(@Context VoteService voteService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("voteId") PollenEntityId<Vote> voteId) { return voteService.getVote(pollId.getEntityId(), voteId.getEntityId()); } - public PollenEntityRef<Vote> addVote(VoteService voteService, PollenEntityId<Poll> pollId, VoteBean vote) throws InvalidFormException { + @POST + public PollenEntityRef<Vote> addVote(@Context VoteService voteService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + VoteBean vote) throws InvalidFormException { return voteService.addVote(pollId.getEntityId(), vote); } - public VoteBean editVote(VoteService voteService, PollenEntityId<Poll> pollId, VoteBean vote) throws InvalidFormException { + @Path("/{voteId}") + @POST @PUT + public VoteBean editVote(@Context VoteService voteService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + VoteBean vote) throws InvalidFormException { return voteService.editVote(pollId.getEntityId(), vote); } - public void deleteVote(VoteService voteService, PollenEntityId<Poll> pollId, PollenEntityId<Vote> voteId) { + @Path("/{voteId}") + @DELETE + public void deleteVote(@Context VoteService voteService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("voteId") PollenEntityId<Vote> voteId) { voteService.deleteVote(pollId.getEntityId(), voteId.getEntityId()); diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoteCountingApi.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoteCountingApi.java index 87ec05e9..44caa4e5 100644 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoteCountingApi.java +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoteCountingApi.java @@ -26,7 +26,14 @@ import org.chorem.pollen.services.bean.ListVoteCountingResultBean; import org.chorem.pollen.services.bean.PollenEntityId; import org.chorem.pollen.services.bean.VoteCountingResultBean; import org.chorem.pollen.services.service.VoteCountingService; -import org.debux.webmotion.server.WebMotionController; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; /** * TODO @@ -34,15 +41,23 @@ import org.debux.webmotion.server.WebMotionController; * @author Tony Chemit - dev@tchemit.fr * @since 2.0 */ -public class VoteCountingApi extends WebMotionController { +@Path("/results/{pollId}") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class VoteCountingApi { - public VoteCountingResultBean getMainResult(VoteCountingService voteCountingService, PollenEntityId<Poll> pollId) { + @GET + public VoteCountingResultBean getMainResult(@Context VoteCountingService voteCountingService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { return voteCountingService.getMainResult(pollId.getEntityId()); } - public ListVoteCountingResultBean getGroupResult(VoteCountingService voteCountingService, PollenEntityId<Poll> pollId) { + @Path("/group") + @GET + public ListVoteCountingResultBean getGroupResult(@Context VoteCountingService voteCountingService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { return voteCountingService.getGroupResult(pollId.getEntityId()); diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoteCountingTypeApi.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoteCountingTypeApi.java index e4a38302..54f771b7 100644 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoteCountingTypeApi.java +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoteCountingTypeApi.java @@ -23,8 +23,14 @@ package org.chorem.pollen.rest.api.v1; import org.chorem.pollen.services.bean.VoteCountingTypeBean; import org.chorem.pollen.services.service.VoteCountingTypeService; -import org.debux.webmotion.server.WebMotionController; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; import java.util.List; /** @@ -33,12 +39,20 @@ import java.util.List; * @author garandel * @since 2.0 */ -public class VoteCountingTypeApi extends WebMotionController { - public List<VoteCountingTypeBean> getVoteCountingTypes(VoteCountingTypeService voteCountingTypeService) { +@Path("/voteCountingTypes") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class VoteCountingTypeApi { + + @GET + public List<VoteCountingTypeBean> getVoteCountingTypes(@Context VoteCountingTypeService voteCountingTypeService) { return voteCountingTypeService.getVoteCountingTypes(); } - public VoteCountingTypeBean getVoteCountingType(VoteCountingTypeService voteCountingTypeService, int id) { + @Path("/{id}") + @GET + public VoteCountingTypeBean getVoteCountingType(@Context VoteCountingTypeService voteCountingTypeService, + @PathParam("id") int id) { return voteCountingTypeService.getVoteCountingType(id); } } diff --git a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoterListApi.java b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoterListApi.java index 59a49d69..652a4df6 100644 --- a/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoterListApi.java +++ b/pollen-rest-api/src/main/java/org/chorem/pollen/rest/api/v1/VoterListApi.java @@ -25,14 +25,24 @@ import com.google.common.collect.Lists; import org.chorem.pollen.persistence.entity.Poll; import org.chorem.pollen.persistence.entity.VoterList; import org.chorem.pollen.persistence.entity.VoterListMember; +import org.chorem.pollen.rest.api.beans.VoterListSaveBean; import org.chorem.pollen.services.bean.PollenEntityId; import org.chorem.pollen.services.bean.PollenEntityRef; import org.chorem.pollen.services.bean.VoterListBean; import org.chorem.pollen.services.bean.VoterListMemberBean; import org.chorem.pollen.services.service.InvalidFormException; import org.chorem.pollen.services.service.VoterListService; -import org.debux.webmotion.server.WebMotionController; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; import java.util.List; import java.util.Set; @@ -42,7 +52,10 @@ import java.util.Set; * @author Tony Chemit - dev@tchemit.fr * @since 2.0 */ -public class VoterListApi extends WebMotionController { +@Path("/voterLists/{pollId}") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class VoterListApi { // public PollenEntityRef<VoterList> importFavoriteListNewGroup(VoterListService voterListService, PollenEntityId<Poll> pollId, PollenEntityId<FavoriteList> favoriteListId) { // @@ -56,25 +69,40 @@ public class VoterListApi extends WebMotionController { // // } - public VoterListBean getMainVoterList(VoterListService voterListService, PollenEntityId<Poll> pollId) { + @Path("/main") + @GET + public VoterListBean getMainVoterList(@Context VoterListService voterListService, + @PathParam("pollId") PollenEntityId<Poll> pollId) { return voterListService.getMainVoterList(pollId.getEntityId()); } - public List<VoterListBean> getVoterLists(VoterListService voterListService, PollenEntityId<Poll> pollId, PollenEntityId<VoterList> voterListId) { + @Path("/{voterListId}") + @GET + public List<VoterListBean> getVoterLists(@Context VoterListService voterListService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("voterListId") PollenEntityId<VoterList> voterListId) { return voterListService.getVoterLists(pollId.getEntityId(), voterListId.getEntityId()); } - public VoterListBean getVoterList(VoterListService voterListService, PollenEntityId<Poll> pollId, PollenEntityId<VoterList> voterListId) { + @Path("/{voterListId}") + @GET + public VoterListBean getVoterList(@Context VoterListService voterListService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("voterListId") PollenEntityId<VoterList> voterListId) { return voterListService.getVoterList(pollId.getEntityId(), voterListId.getEntityId()); } - public PollenEntityRef<VoterList> createVoterList(VoterListService voterListService, PollenEntityId<Poll> pollId, VoterListBean voterList, VoterListMemberBean... members) throws InvalidFormException { + @POST + public PollenEntityRef<VoterList> createVoterList(@Context VoterListService voterListService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + VoterListBean voterList, + VoterListMemberBean... members) throws InvalidFormException { List<VoterListMemberBean> memberList = Lists.newArrayList(members); @@ -82,75 +110,114 @@ public class VoterListApi extends WebMotionController { } - public VoterListBean editVoterList(VoterListService voterListService, PollenEntityId<Poll> pollId, VoterListBean voterList) throws InvalidFormException { + @Path("/{voterListId}") + @POST @PUT + public VoterListBean editVoterList(@Context VoterListService voterListService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + VoterListBean voterList) throws InvalidFormException { return voterListService.editVoterList(pollId.getEntityId(), voterList); } - public void deleteVoterList(VoterListService voterListService, PollenEntityId<Poll> pollId, PollenEntityId<VoterList> voterListId) { + @Path("/{voterListId}") + @DELETE + public void deleteVoterList(@Context VoterListService voterListService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("voterListId") PollenEntityId<VoterList> voterListId) { voterListService.deleteVoterList(pollId.getEntityId(), voterListId.getEntityId()); } - public Set<VoterListMemberBean> getMembers(VoterListService voterListService, PollenEntityId<Poll> pollId, PollenEntityId<VoterList> voterListId) { + @Path("/{voterListId}/members") + @GET + public Set<VoterListMemberBean> getMembers(@Context VoterListService voterListService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("voterListId") PollenEntityId<VoterList> voterListId) { return voterListService.getVoterListMembers(pollId.getEntityId(), voterListId.getEntityId()); } - public VoterListMemberBean getMember(VoterListService voterListService, PollenEntityId<Poll> pollId, PollenEntityId<VoterList> voterListId, PollenEntityId<VoterListMember> memberId) { + @Path("/{voterListId}/members/{memberId}") + @GET + public VoterListMemberBean getMember(@Context VoterListService voterListService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("voterListId") PollenEntityId<VoterList> voterListId, + @PathParam("memberId") PollenEntityId<VoterListMember> memberId) { return voterListService.getVoterListMember(pollId.getEntityId(), voterListId.getEntityId(), memberId.getEntityId()); } - public VoterListMemberBean addMember(VoterListService voterListService, PollenEntityId<Poll> pollId, VoterListMemberBean member) throws InvalidFormException { + @Path("/{voterListId}/members") + @POST + public VoterListMemberBean addMember(@Context VoterListService voterListService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + VoterListMemberBean member) throws InvalidFormException { return voterListService.addVoterListMember(pollId.getEntityId(), member); } - public VoterListMemberBean editMember(VoterListService voterListService, PollenEntityId<Poll> pollId, VoterListMemberBean member) throws InvalidFormException { + @Path("/{voterListId}/members/{memberId}") + @POST @PUT + public VoterListMemberBean editMember(@Context VoterListService voterListService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + VoterListMemberBean member) throws InvalidFormException { return voterListService.editVoterListMember(pollId.getEntityId(), member); } - public void deleteMember(VoterListService voterListService, PollenEntityId<Poll> pollId, PollenEntityId<VoterList> voterListId, PollenEntityId<VoterListMember> memberId) throws InvalidFormException { + @Path("/{voterListId}/members/{memberId}") + @DELETE + public void deleteMember(@Context VoterListService voterListService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("voterListId") PollenEntityId<VoterList> voterListId, + @PathParam("memberId") PollenEntityId<VoterListMember> memberId) throws InvalidFormException { voterListService.deleteVoterListMember(pollId.getEntityId(), voterListId.getEntityId(), memberId.getEntityId()); } - public void saveVoters(VoterListService voterListService, PollenEntityId<Poll> pollId, - VoterListBean[] listsToSave, - VoterListMemberBean[] membersToSave, - VoterListBean[] listsToDelete, - VoterListMemberBean[] membersToDelete) throws InvalidFormException { + @Path("/save") + @POST + public void saveVoters(@Context VoterListService voterListService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + VoterListSaveBean voterListSaveBean) throws InvalidFormException { List<String> listIds = Lists.newLinkedList(); - for (VoterListBean list : listsToDelete) { + for (VoterListBean list : voterListSaveBean.getListsToDelete()) { listIds.add(list.getEntityId()); } List<String> memberIds = Lists.newLinkedList(); - for (VoterListMemberBean member : membersToDelete) { + for (VoterListMemberBean member : voterListSaveBean.getMembersToDelete()) { memberIds.add(member.getEntityId()); } voterListService.saveVoters(pollId.getEntityId(), - Lists.newArrayList(listsToSave), - Lists.newArrayList(membersToSave), + Lists.newArrayList(voterListSaveBean.getListsToSave()), + Lists.newArrayList(voterListSaveBean.getMembersToSave()), listIds, memberIds); } - public int resendInvitationVoterList(VoterListService voterListService, PollenEntityId<Poll> pollId, PollenEntityId<VoterList> voterListId) { + @Path("/{voterListId}/resend") + @GET + public int resendInvitationVoterList(@Context VoterListService voterListService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("voterListId") PollenEntityId<VoterList> voterListId) { return voterListService.resendInvitationVoterList(pollId.getEntityId(), voterListId.getEntityId()); } - public boolean resendInvitationMember(VoterListService voterListService, PollenEntityId<Poll> pollId, PollenEntityId<VoterList> voterListId, PollenEntityId<VoterListMember> memberId) { + @Path("/{voterListId}/members/{memberId}/resend") + @GET + public boolean resendInvitationMember(@Context VoterListService voterListService, + @PathParam("pollId") PollenEntityId<Poll> pollId, + @PathParam("voterListId") PollenEntityId<VoterList> voterListId, + @PathParam("memberId") PollenEntityId<VoterListMember> memberId) { return voterListService.resendInvitationMember(pollId.getEntityId(), voterListId.getEntityId(), memberId.getEntityId()); } diff --git a/pollen-rest-api/src/main/resources/mapping b/pollen-rest-api/src/main/resources/mapping index d6076def..de064f7a 100644 --- a/pollen-rest-api/src/main/resources/mapping +++ b/pollen-rest-api/src/main/resources/mapping @@ -118,12 +118,8 @@ GET /v1/polls/created PollApi.getCreatedPoll GET /v1/polls/invited PollApi.getInvitedPolls GET /v1/polls/participated PollApi.getParticipatedPolls POST /v1/polls PollApi.createPoll -POST,GET /v1/polls/create PollApi.createPoll -GET /v1/polls/edit PollApi.editPoll - #fix me POST,PUT /v1/polls/{pollId} PollApi.editPoll -POST /v1/polls/{pollId}/edit PollApi.editPoll GET /v1/polls/{pollId} PollApi.getPoll DELETE /v1/polls/{pollId} PollApi.deletePoll @@ -205,7 +201,7 @@ DELETE /v1/polls/{pollId}/voterLists/{voterListId}/members/{memberId} GET /v1/polls/{pollId}/votes VoteApi.getVotes GET /v1/polls/{pollId}/votes/new VoteApi.getNewVote -GET /v1/polls/{pollId}/votes/{voteId}/edit VoteApi.editVote +GET /v1/polls/{pollId}/votes/{voteId} VoteApi.editVote POST /v1/polls/{pollId}/votes VoteApi.addVote GET /v1/polls/{pollId}/votes/{voteId} VoteApi.getVote PUT,POST /v1/polls/{pollId}/votes/{voteId} VoteApi.editVote diff --git a/pollen-rest-api/src/main/webapp/WEB-INF/web.xml b/pollen-rest-api/src/main/webapp/WEB-INF/web.xml index 45e02fa2..d8a94176 100644 --- a/pollen-rest-api/src/main/webapp/WEB-INF/web.xml +++ b/pollen-rest-api/src/main/webapp/WEB-INF/web.xml @@ -27,12 +27,7 @@ http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>Pollen REST Api</display-name> - - <context-param> - <param-name>wm.skip.conventionScan</param-name> - <param-value>true</param-value> - </context-param> - + <filter> <filter-name>topiaTransaction</filter-name> <filter-class> @@ -40,32 +35,14 @@ </filter-class> </filter> - <filter> - <filter-name>WebMotionServer</filter-name> - <filter-class>org.debux.webmotion.server.WebMotionServer</filter-class> - <async-supported>true</async-supported> - </filter> - <filter-mapping> <filter-name>topiaTransaction</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> - <filter-mapping> - <filter-name>WebMotionServer</filter-name> - <url-pattern>/*</url-pattern> - <dispatcher>REQUEST</dispatcher> - <dispatcher>INCLUDE</dispatcher> - <dispatcher>FORWARD</dispatcher> - <dispatcher>ERROR</dispatcher> - </filter-mapping> <listener> - <listener-class>org.apache.commons.fileupload.servlet.FileCleanerCleanup</listener-class> - </listener> - - <listener> - <listener-class>org.debux.webmotion.server.WebMotionServletContextListener</listener-class> + <listener-class>org.chorem.pollen.rest.api.PollenRestApiApplicationListener</listener-class> </listener> <!-- Force jsessionid into cookie --> @@ -74,46 +51,4 @@ </session-config> - <!-- Exception --> - <error-page> - <exception-type>java.lang.Exception</exception-type> - <location>/error</location> - </error-page> - - <!-- Bad Request --> - <error-page> - <error-code>400</error-code> - <location>/error</location> - </error-page> - - <!-- Unauthorized --> - <error-page> - <error-code>401</error-code> - <location>/error</location> - </error-page> - - <!-- Forbidden --> - <error-page> - <error-code>403</error-code> - <location>/error</location> - </error-page> - - <!-- Not Found --> - <error-page> - <error-code>404</error-code> - <location>/error</location> - </error-page> - - <!-- Request Time-out --> - <error-page> - <error-code>408</error-code> - <location>/error</location> - </error-page> - - <!-- Internal Server Error --> - <error-page> - <error-code>500</error-code> - <location>/error</location> - </error-page> - </web-app> diff --git a/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/AbstractPollenRestApiTest.java b/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/AbstractPollenRestApiTest.java index 1f8b29b7..0f17c8b8 100644 --- a/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/AbstractPollenRestApiTest.java +++ b/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/AbstractPollenRestApiTest.java @@ -21,19 +21,26 @@ package org.chorem.pollen.rest.api; * #L% */ +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.catalina.Globals; +import org.apache.catalina.core.StandardContext; +import org.apache.catalina.loader.WebappLoader; +import org.apache.catalina.startup.Tomcat; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.http.client.utils.URIBuilder; +import org.apache.tomcat.util.scan.StandardJarScanner; import org.chorem.pollen.persistence.PollenPersistenceContext; import org.chorem.pollen.persistence.PollenTopiaPersistenceContext; import org.chorem.pollen.persistence.entity.PollenPrincipal; import org.chorem.pollen.persistence.entity.SessionToken; +import org.chorem.pollen.rest.api.converter.JacksonConfig; import org.chorem.pollen.services.PollenServiceContext; import org.chorem.pollen.services.bean.PollenEntityId; import org.chorem.pollen.services.service.security.PollenSecurityContext; import org.chorem.pollen.services.test.FakePollenApplicationContext; import org.chorem.pollen.services.test.FakePollenSecurityContext; import org.chorem.pollen.services.test.FakePollenServiceContext; -import org.debux.webmotion.unittest.WebMotionTest; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -42,6 +49,7 @@ import org.nuiton.util.DateUtil; import java.io.File; import java.util.Locale; +import java.util.concurrent.atomic.AtomicBoolean; /** * TODO @@ -49,7 +57,7 @@ import java.util.Locale; * @author Tony Chemit - dev@tchemit.fr * @since 2.0 */ -public class AbstractPollenRestApiTest extends WebMotionTest { +public class AbstractPollenRestApiTest { /** Logger. */ private static final Log log = LogFactory.getLog(AbstractPollenRestApiTest.class); @@ -57,24 +65,19 @@ public class AbstractPollenRestApiTest extends WebMotionTest { @Rule public final FakePollenApplicationContext application = new FakePollenApplicationContext("pollen-rest-api-test.properties"); - protected JsonHelper jsonHelper; + protected ObjectMapper objectMapper; - @Override - protected int getPort() { - return application.getPort(); - } - - protected JsonHelper getJsonHelper() { + static AtomicBoolean isStarted = new AtomicBoolean(false); - if (jsonHelper == null) { + protected Tomcat server; - TopiaIdFactory topiaIdFactory = application.getTopiaApplicationContext().getTopiaIdFactory(); + protected ObjectMapper getObjectMapper() { - // do not pretty print otherwise adding a pretty print json in header fails (last '}' missing) - jsonHelper = new JsonHelper(topiaIdFactory, false); + if (objectMapper == null) { + JacksonConfig jacksonConfig = new JacksonConfig(); + objectMapper = jacksonConfig.getContext(ObjectMapper.class); } - - return jsonHelper; + return objectMapper; } protected void loadFixtures(String fixturesSetName) { @@ -134,11 +137,40 @@ public class AbstractPollenRestApiTest extends WebMotionTest { PollenRestApiApplicationContext.setApplicationContext(applicationContext); - super.startServer(); + // set catalina base directory + System.setProperty(Globals.CATALINA_BASE_PROP, new File(getServerBaseDirectory()).getAbsolutePath()); + + // create server + server = new Tomcat(); + server.setPort(application.getPort()); + + // Create webapp loader with jar in classpath as repository + WebappLoader loader = new WebappLoader(this.getClass().getClassLoader()); + String classpaths = System.getProperty("java.class.path"); + String[] classpath = classpaths.split(":"); + for (String path : classpath) { + loader.addRepository(new File(path).toURI().toURL().toString()); + } + + // Create a new webbapp + StandardContext rootContext = (StandardContext) server.addWebapp(getContextPath(), new File(getWebappLocation()).getAbsolutePath()); + rootContext.setLoader(loader); + rootContext.setReloadable(true); + rootContext.setUnpackWAR(false); + ((StandardJarScanner) rootContext.getJarScanner()).setScanAllDirectories(true); + + // Enabled JNDI + server.enableNaming(); + + // Start server for the theard + server.start(); + + } + protected String getWebappLocation() { + return "src/main/webapp"; } - @Override protected String getServerBaseDirectory() { return new File(application.getTestBasedir(), @@ -169,4 +201,30 @@ public class AbstractPollenRestApiTest extends WebMotionTest { } + protected String getContextPath() { + return "/"; + } + + public URIBuilder createRequest(String url) { + String contextPath = getContextPath(); + + String path; + if (contextPath.endsWith("/") && url.startsWith("/")) { + path = getContextPath() + url.substring(1); + + } else if (contextPath.endsWith("/") ^ url.startsWith("/")) { + path = getContextPath() + url; + + } else { + path = getContextPath() + "/" + url; + } + + URIBuilder builder = new URIBuilder() + .setScheme("http") + .setHost("localhost") + .setPort(application.getPort()) + .setPath(path); + return builder; + } + } diff --git a/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/AuthApiTest.java b/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/AuthApiTest.java index c409fbd6..383bbab6 100644 --- a/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/AuthApiTest.java +++ b/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/AuthApiTest.java @@ -21,7 +21,7 @@ package org.chorem.pollen.rest.api; * #L% */ -import com.google.common.reflect.TypeToken; +import com.fasterxml.jackson.core.type.TypeReference; import org.apache.http.client.fluent.Request; import org.apache.http.client.fluent.Response; import org.chorem.pollen.persistence.entity.PollenUser; @@ -30,7 +30,7 @@ import org.junit.Assert; import org.junit.Test; import java.io.IOException; -import java.lang.reflect.Type; +import java.net.URI; import java.net.URISyntaxException; @@ -45,10 +45,13 @@ public class AuthApiTest extends AbstractPollenRestApiTest { @Test public void login() throws URISyntaxException, IOException { - Request request = createRequest(RestApiFixtures.login()) + + URI uri = createRequest(RestApiFixtures.login()) .addParameter("login", "admin@pollen.org") .addParameter("password", "admin") - .Post(); + .build(); + + Request request = Request.Post(uri); String content = request.execute().returnContent().asString(); showTestResult(content); @@ -59,21 +62,22 @@ public class AuthApiTest extends AbstractPollenRestApiTest { @Test public void loginThenLogout() throws URISyntaxException, IOException { - Request login = createRequest(RestApiFixtures.login()) + URI uri = createRequest(RestApiFixtures.login()) .addParameter("login", "admin@pollen.org") .addParameter("password", "admin") - .Post(); + .build(); + + Request login = Request.Post(uri); String loginContent = login.execute().returnContent().asString(); showTestResult(loginContent); Assert.assertNotNull(loginContent); - Type type = new TypeToken<PollenEntityRef<PollenUser>>() { - }.getType(); + PollenEntityRef createBeanRef = getObjectMapper().readValue(loginContent, new TypeReference<PollenEntityRef<PollenUser>>() {}); - PollenEntityRef createBeanRef = getJsonHelper().fromJson(loginContent, type); + URI uriOut = createRequest(RestApiFixtures.logout()).build(); - Request logout = createRequest(RestApiFixtures.logout()).Get(); + Request logout = Request.Get(uriOut); logout.addHeader(PollenRestApiRequestFilter.REQUEST_HEADER_SESSION_TOKEN, createBeanRef.getPermission()); String logoutContent = logout.execute().returnContent().asString(); @@ -85,10 +89,12 @@ public class AuthApiTest extends AbstractPollenRestApiTest { @Test public void badLogin() throws URISyntaxException, IOException { - Request request = createRequest(RestApiFixtures.login()) + URI uri = createRequest(RestApiFixtures.login()) .addParameter("login", "admin@pollen.org" + System.nanoTime()) .addParameter("password", "admin" + System.nanoTime()) - .Post(); + .build(); + + Request request = Request.Post(uri); Response response = request.execute(); int statusCode = response.returnResponse().getStatusLine().getStatusCode(); @@ -99,10 +105,12 @@ public class AuthApiTest extends AbstractPollenRestApiTest { @Test public void badPassword() throws URISyntaxException, IOException { - Request request = createRequest(RestApiFixtures.login()) + URI uri = createRequest(RestApiFixtures.login()) .addParameter("login", "admin@pollen.org") .addParameter("password", "admin" + System.nanoTime()) - .Post(); + .build(); + + Request request = Request.Post(uri); Response response = request.execute(); int statusCode = response.returnResponse().getStatusLine().getStatusCode(); diff --git a/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/PollApiTest.java b/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/PollApiTest.java index da278766..61df2599 100644 --- a/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/PollApiTest.java +++ b/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/PollApiTest.java @@ -23,25 +23,29 @@ package org.chorem.pollen.rest.api; import org.apache.http.client.HttpResponseException; import org.apache.http.client.fluent.Request; -import org.chorem.pollen.persistence.entity.Choice; +import org.apache.http.client.fluent.Response; +import org.apache.http.entity.ContentType; import org.chorem.pollen.persistence.entity.ChoiceType; import org.chorem.pollen.persistence.entity.CommentVisibility; import org.chorem.pollen.persistence.entity.Poll; -import org.chorem.pollen.persistence.entity.PollImpl; import org.chorem.pollen.persistence.entity.PollType; import org.chorem.pollen.persistence.entity.ResultVisibility; import org.chorem.pollen.persistence.entity.VoteVisibility; +import org.chorem.pollen.rest.api.beans.PollCreateBean; import org.chorem.pollen.services.PollenFixtures; import org.chorem.pollen.services.bean.ChoiceBean; +import org.chorem.pollen.services.bean.PollBean; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; +import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** @@ -59,7 +63,8 @@ public class PollApiTest extends AbstractPollenRestApiTest { @Test public void getPollsNew() throws URISyntaxException, IOException { - Request request = createRequest(RestApiFixtures.polls("new", null)).Get(); + URI uri = createRequest(RestApiFixtures.polls("new", null)).build(); + Request request = Request.Get(uri); String content = request.execute().returnContent().asString(); showTestResult(content); assertNotNull(content); @@ -70,7 +75,8 @@ public class PollApiTest extends AbstractPollenRestApiTest { public void getPolls() throws URISyntaxException, IOException { //TODO Login as admin before - Request request = createRequest(RestApiFixtures.polls(null, null)).Get(); + URI uri = createRequest(RestApiFixtures.polls(null, null)).build(); + Request request = Request.Get(uri); String content = request.execute().returnContent().asString(); showTestResult(content); assertNotNull(content); @@ -79,7 +85,8 @@ public class PollApiTest extends AbstractPollenRestApiTest { @Ignore @Test public void getPollsCreated() throws URISyntaxException, IOException { - Request request = createRequest(RestApiFixtures.polls("created", null)).Get(); + URI uri = createRequest(RestApiFixtures.polls("created", null)).build(); + Request request = Request.Get(uri); String content = request.execute().returnContent().asString(); showTestResult(content); assertNotNull(content); @@ -88,7 +95,8 @@ public class PollApiTest extends AbstractPollenRestApiTest { @Ignore @Test public void getPollsInvited() throws URISyntaxException, IOException { - Request request = createRequest(RestApiFixtures.polls("invited", null)).Get(); + URI uri = createRequest(RestApiFixtures.polls("invited", null)).build(); + Request request = Request.Get(uri); String content = request.execute().returnContent().asString(); showTestResult(content); assertNotNull(content); @@ -97,7 +105,8 @@ public class PollApiTest extends AbstractPollenRestApiTest { @Ignore @Test public void getPollsParticipated() throws URISyntaxException, IOException { - Request request = createRequest(RestApiFixtures.polls("participated", null)).Get(); + URI uri = createRequest(RestApiFixtures.polls("participated", null)).build(); + Request request = Request.Get(uri); String content = request.execute().returnContent().asString(); showTestResult(content); assertNotNull(content); @@ -108,7 +117,8 @@ public class PollApiTest extends AbstractPollenRestApiTest { Poll poll = fixture(PollenFixtures.POLL_NORMAL_ID); String pollId = encodeId(poll.getTopiaId()); - Request request = createRequest(RestApiFixtures.polls(pollId, null)).Get(); + URI uri = createRequest(RestApiFixtures.polls(pollId, null)).build(); + Request request = Request.Get(uri); String content = request.execute().returnContent().asString(); showTestResult(content); assertNotNull(content); @@ -118,7 +128,7 @@ public class PollApiTest extends AbstractPollenRestApiTest { @Test public void postPoll() throws Throwable { - Poll poll = new PollImpl(); + PollBean poll = new PollBean(); poll.setPollType(PollType.FREE); poll.setCommentVisibility(CommentVisibility.EVERYBODY); poll.setResultVisibility(ResultVisibility.EVERYBODY); @@ -126,6 +136,7 @@ public class PollApiTest extends AbstractPollenRestApiTest { poll.setVoteCountingType(1); poll.setTitle("title"); poll.setChoiceType(ChoiceType.TEXT); + poll.setClosed(false); List<ChoiceBean> choices = new ArrayList<>(); ChoiceBean choice1 = new ChoiceBean(); @@ -137,17 +148,18 @@ public class PollApiTest extends AbstractPollenRestApiTest { choice2.setChoiceValue("choiceB"); choices.add(choice2); - String choiceStr = getJsonHelper().toJson(choices); - String pollStr = getJsonHelper().toJson(poll); + PollCreateBean pollCreateBean = new PollCreateBean(); + pollCreateBean.setPoll(poll); + pollCreateBean.setChoices(choices); - Request request = createRequest(RestApiFixtures.polls(null, null)) - .addParameter("poll", pollStr) - .addParameter("choices", choiceStr) - .addParameter("voterLists", "[]") - .addParameter("voterListMembers", "[]") - .Post().setHeader(PollenRestApiRequestFilter.REQUEST_HEADER_UI_CONTEXT, - getJsonHelper().toJson(fixture("pollenUIContext_chorem"))); + String pollCreateStr = getObjectMapper().writeValueAsString(pollCreateBean); + URI uri = createRequest(RestApiFixtures.polls(null, null)).build(); + + Request request = Request.Post(uri); + request.bodyString(pollCreateStr, ContentType.APPLICATION_JSON); + request.setHeader(PollenRestApiRequestFilter.REQUEST_HEADER_UI_CONTEXT, + getObjectMapper().writeValueAsString(fixture("pollenUIContext_chorem"))); String content = request.execute().returnContent().asString(); showTestResult(content); assertNotNull(content); @@ -157,7 +169,7 @@ public class PollApiTest extends AbstractPollenRestApiTest { @Test(expected = HttpResponseException.class) public void postBadPoll() throws Throwable { - Poll poll = new PollImpl(); + PollBean poll = new PollBean(); poll.setPollType(PollType.FREE); poll.setCommentVisibility(CommentVisibility.EVERYBODY); poll.setResultVisibility(ResultVisibility.EVERYBODY); @@ -165,19 +177,19 @@ public class PollApiTest extends AbstractPollenRestApiTest { poll.setVoteCountingType(1); poll.setTitle("title"); - List<Choice> choices = new ArrayList<>(); + List<ChoiceBean> choices = new ArrayList<>(); - String choiceStr = getJsonHelper().toJson(choices); - String pollStr = getJsonHelper().toJson(poll); + PollCreateBean pollCreateBean = new PollCreateBean(); + pollCreateBean.setPoll(poll); + pollCreateBean.setChoices(choices); - Request request = createRequest(RestApiFixtures.polls(null, null)) - .addParameter("poll", pollStr) - .addParameter("choices", choiceStr) - .addParameter("voterLists", "[]") - .addParameter("voterListMembers", "[]") - .Post().setHeader(PollenRestApiRequestFilter.REQUEST_HEADER_UI_CONTEXT, - getJsonHelper().toJson(fixture("pollenUIContext_chorem"))); + String pollCreateStr = getObjectMapper().writeValueAsString(pollCreateBean); + URI uri = createRequest(RestApiFixtures.polls(null, null)).build(); + Request request = Request.Post(uri); + request.bodyString(pollCreateStr, ContentType.APPLICATION_JSON); + request.setHeader(PollenRestApiRequestFilter.REQUEST_HEADER_UI_CONTEXT, + getObjectMapper().writeValueAsString(fixture("pollenUIContext_chorem"))); String content = request.execute().returnContent().asString(); showTestResult(content); assertNotNull(content); @@ -189,7 +201,8 @@ public class PollApiTest extends AbstractPollenRestApiTest { public void putPoll() throws URISyntaxException, IOException { Poll poll = fixture(PollenFixtures.POLL_NORMAL_ID); String pollId = poll.getTopiaId(); - Request request = createRequest(RestApiFixtures.polls(pollId, null)).Put(); + URI uri = createRequest(RestApiFixtures.polls(pollId, null)).build(); + Request request = Request.Put(uri); String content = request.execute().returnContent().asString(); showTestResult(content); assertNotNull(content); @@ -199,12 +212,13 @@ public class PollApiTest extends AbstractPollenRestApiTest { public void deletePoll() throws URISyntaxException, IOException { Poll poll = fixture(PollenFixtures.POLL_NORMAL_ID); String pollId = encodeId(poll.getTopiaId()); - Request request = createRequest(RestApiFixtures.polls(pollId, null)) + URI uri = createRequest(RestApiFixtures.polls(pollId, null)) .addParameter(PollenRestApiRequestFilter.REQUEST_PERMISSION_PARAMETER, poll.getCreator().getPermission().getToken()) - .Delete(); - String content = request.execute().returnContent().asString(); - showTestResult(content); - assertNotNull(content); + .build(); + Request request = Request.Delete(uri); + + Response response = request.execute(); + assertEquals(204, response.returnResponse().getStatusLine().getStatusCode()); } @Ignore @@ -212,7 +226,8 @@ public class PollApiTest extends AbstractPollenRestApiTest { public void clonePoll() throws URISyntaxException, IOException { Poll poll = fixture(PollenFixtures.POLL_NORMAL_ID); String pollId = encodeId(poll.getTopiaId()); - Request request = createRequest(RestApiFixtures.polls(pollId, null)).Post(); + URI uri = createRequest(RestApiFixtures.polls(pollId, null)).build(); + Request request = Request.Post(uri); String content = request.execute().returnContent().asString(); showTestResult(content); assertNotNull(content); @@ -223,7 +238,8 @@ public class PollApiTest extends AbstractPollenRestApiTest { public void exportPoll() throws URISyntaxException, IOException { Poll poll = fixture(PollenFixtures.POLL_NORMAL_ID); String pollId = encodeId(poll.getTopiaId()); - Request request = createRequest(RestApiFixtures.polls(pollId, "export")).Get(); + URI uri = createRequest(RestApiFixtures.polls(pollId, "export")).build(); + Request request = Request.Get(uri); String content = request.execute().returnContent().asString(); showTestResult(content); assertNotNull(content); @@ -234,7 +250,8 @@ public class PollApiTest extends AbstractPollenRestApiTest { public void closePoll() throws URISyntaxException, IOException { Poll poll = fixture(PollenFixtures.POLL_NORMAL_ID); String pollId = encodeId(poll.getTopiaId()); - Request request = createRequest(RestApiFixtures.polls(pollId, "close")).Post(); + URI uri = createRequest(RestApiFixtures.polls(pollId, "close")).build(); + Request request = Request.Post(uri); String content = request.execute().returnContent().asString(); showTestResult(content); assertNotNull(content); @@ -247,9 +264,10 @@ public class PollApiTest extends AbstractPollenRestApiTest { Poll poll = fixture(PollenFixtures.POLL_NORMAL_ID); String pollId = encodeId(poll.getTopiaId()); - Request request = createRequest(RestApiFixtures.polls(pollId, "assign")) + URI uri = createRequest(RestApiFixtures.polls(pollId, "assign")) .addParameter(PollenRestApiRequestFilter.REQUEST_PERMISSION_PARAMETER, poll.getCreator().getPermission().getToken()) - .Put(); + .build(); + Request request = Request.Put(uri); String content = request.execute().returnContent().asString(); showTestResult(content); assertNotNull(content); diff --git a/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/PollenUserApiTest.java b/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/PollenUserApiTest.java index 7f6ff76f..7bd1d92e 100644 --- a/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/PollenUserApiTest.java +++ b/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/PollenUserApiTest.java @@ -21,7 +21,7 @@ package org.chorem.pollen.rest.api; * #L% */ -import com.google.common.reflect.TypeToken; +import com.fasterxml.jackson.core.type.TypeReference; import org.apache.http.client.fluent.Request; import org.chorem.pollen.persistence.entity.PollenUser; import org.chorem.pollen.services.bean.PollenEntityRef; @@ -31,7 +31,7 @@ import org.junit.Ignore; import org.junit.Test; import java.io.IOException; -import java.lang.reflect.Type; +import java.net.URI; import java.net.URISyntaxException; import static org.junit.Assert.assertTrue; @@ -55,7 +55,11 @@ public class PollenUserApiTest extends AbstractPollenRestApiTest { String sessionToken = login(); - Request request = createRequest(RestApiFixtures.users(null, null)).Get(); + URI uri = createRequest(RestApiFixtures.users(null, null)) + .addParameter("pageNumber", "0") + .addParameter("pageSize", "-1") + .build(); + Request request = Request.Get(uri); request.addHeader(PollenRestApiRequestFilter.REQUEST_HEADER_SESSION_TOKEN, sessionToken); String content = request.execute().returnContent().asString(); showTestResult(content); @@ -70,7 +74,8 @@ public class PollenUserApiTest extends AbstractPollenRestApiTest { PollenUser pollenUser = fixture("user_jean"); String userId = encodeId(pollenUser.getTopiaId()); - Request request = createRequest(RestApiFixtures.users(userId, null)).Get(); + URI uri = createRequest(RestApiFixtures.users(userId, null)).build(); + Request request = Request.Get(uri); request.addHeader(PollenRestApiRequestFilter.REQUEST_HEADER_SESSION_TOKEN, sessionToken); String content = request.execute().returnContent().asString(); showTestResult(content); @@ -83,7 +88,8 @@ public class PollenUserApiTest extends AbstractPollenRestApiTest { @Test public void postUser() throws Exception { - Request request = createRequest(RestApiFixtures.users(null, null)).Post(); + URI uri = createRequest(RestApiFixtures.users(null, null)).build(); + Request request = Request.Post(uri); String content = request.execute().returnContent().asString(); showTestResult(content); assertTrue(content.contains("email2")); @@ -96,7 +102,8 @@ public class PollenUserApiTest extends AbstractPollenRestApiTest { PollenUser pollenUser = fixture("user_jean"); String userId = pollenUser.getTopiaId(); - Request request = createRequest(RestApiFixtures.users(userId, null)).Get(); + URI uri = createRequest(RestApiFixtures.users(userId, null)).build(); + Request request = Request.Get(uri); String content = request.execute().returnContent().asString(); showTestResult(content); assertTrue(content.contains("email3")); @@ -109,7 +116,8 @@ public class PollenUserApiTest extends AbstractPollenRestApiTest { PollenUser pollenUser = fixture("user_jean"); String userId = encodeId(pollenUser.getTopiaId()); - Request request = createRequest(RestApiFixtures.users(userId, null)).Delete(); + URI uri = createRequest(RestApiFixtures.users(userId, null)).build(); + Request request = Request.Delete(uri); String content = request.execute().returnContent().asString(); showTestResult(content); assertTrue(content.contains("OK!")); @@ -123,7 +131,8 @@ public class PollenUserApiTest extends AbstractPollenRestApiTest { PollenUser pollenUser = fixture("user_jean"); String userId = encodeId(pollenUser.getTopiaId()); String token = ""; - Request request = createRequest(RestApiFixtures.users(userId, token)).Put(); + URI uri = createRequest(RestApiFixtures.users(userId, token)).build(); + Request request = Request.Put(uri); String content = request.execute().returnContent().asString(); showTestResult(content); assertTrue(content.contains("OK!")); @@ -131,18 +140,19 @@ public class PollenUserApiTest extends AbstractPollenRestApiTest { private String login() throws URISyntaxException, IOException { - Request loginRequest = createRequest(RestApiFixtures.login()) + URI uri = createRequest(RestApiFixtures.login()) .addParameter("login", "admin@pollen.org") .addParameter("password", "admin") - .Post(); + .build(); + Request request = Request.Post(uri); - String loginContent = loginRequest.execute().returnContent().asString(); + String loginContent = request.execute().returnContent().asString(); showTestResult(loginContent); - Type type = new TypeToken<PollenEntityRef<PollenUser>>() { - }.getType(); + TypeReference<PollenEntityRef<PollenUser>> type = new TypeReference<PollenEntityRef<PollenUser>>() { + }; - PollenEntityRef<PollenUser> createBeanRef = getJsonHelper().fromJson(loginContent, type); + PollenEntityRef<PollenUser> createBeanRef = getObjectMapper().readValue(loginContent, type); Assert.assertNotNull(createBeanRef); Assert.assertNotNull(createBeanRef.getEntityId()); Assert.assertNotNull(createBeanRef.getReducedId()); diff --git a/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/converter/JsonArrayConverterTest.java b/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/converter/JsonArrayConverterTest.java deleted file mode 100644 index 3a8599e2..00000000 --- a/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/converter/JsonArrayConverterTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.chorem.pollen.rest.api.converter; - -/* - * #%L - * Pollen :: Rest Api - * %% - * Copyright (C) 2009 - 2017 Code Lutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import org.chorem.pollen.persistence.entity.ChoiceType; -import org.chorem.pollen.services.bean.ChoiceBean; -import org.junit.Assert; -import org.junit.Test; -import org.nuiton.topia.persistence.internal.FullyQualifiedNamePlusUuidTopiaIdFactory; - -public class JsonArrayConverterTest { - - @Test - public void convertToType() throws Exception { - - String choicesStr = "[ {id: \"AAAA\", choiceValue: \"choice1\", choiceType: \"TEXT\", choiceOrder: 1}, " + - " {id: \"BBBB\", choiceValue: \"choice2\", choiceType: \"RESOURCE\", choiceOrder: 2} ]"; - - JsonArrayConverter converter = JsonArrayConverter.newConverter(new FullyQualifiedNamePlusUuidTopiaIdFactory(), ChoiceBean.class); - - ChoiceBean[] choices = converter.convert(ChoiceBean[].class, choicesStr); - Assert.assertNotNull(choices); - Assert.assertEquals(2, choices.length); - - Assert.assertNotNull(choices[0]); - Assert.assertEquals("choice1", choices[0].getChoiceValue()); - Assert.assertEquals(ChoiceType.TEXT, choices[0].getChoiceType()); - Assert.assertEquals(1, choices[0].getChoiceOrder()); - - Assert.assertNotNull(choices[1]); - Assert.assertEquals("choice2", choices[1].getChoiceValue()); - Assert.assertEquals(ChoiceType.RESOURCE, choices[1].getChoiceType()); - Assert.assertEquals(2, choices[1].getChoiceOrder()); - - } -} diff --git a/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/converter/JsonConverterTest.java b/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/converter/JsonConverterTest.java deleted file mode 100644 index 2d61e0e4..00000000 --- a/pollen-rest-api/src/test/java/org/chorem/pollen/rest/api/converter/JsonConverterTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.chorem.pollen.rest.api.converter; - -/* - * #%L - * Pollen :: Rest Api - * %% - * Copyright (C) 2009 - 2017 Code Lutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import org.chorem.pollen.persistence.entity.CommentVisibility; -import org.chorem.pollen.persistence.entity.Poll; -import org.chorem.pollen.persistence.entity.PollType; -import org.chorem.pollen.persistence.entity.VoteVisibility; -import org.chorem.pollen.services.bean.VoteBean; -import org.chorem.pollen.services.bean.VoteToChoiceBean; -import org.junit.Assert; -import org.junit.Test; -import org.nuiton.topia.persistence.internal.FullyQualifiedNamePlusUuidTopiaIdFactory; - -public class JsonConverterTest { - - @Test - public void convertBean() { - - String pollStr = "{voterId:\"voterId\",voterName:\"toto\",anonymous:true,choice:[{voteValue:1.5,choiceId:\"AA\"}]}"; - - JsonConverter<VoteBean> converter = JsonConverter.newConverter(new FullyQualifiedNamePlusUuidTopiaIdFactory(), VoteBean.class); - - VoteBean voteBean = converter.convert(VoteBean.class, pollStr); - - Assert.assertNotNull(voteBean); - Assert.assertEquals(true, voteBean.getAnonymous()); - - Assert.assertEquals("toto", voteBean.getVoterName()); - Assert.assertEquals("voterId", voteBean.getVoterId().getReducedId()); - - Assert.assertNotNull(voteBean.getChoice()); - Assert.assertEquals(1, voteBean.getChoice().size()); - VoteToChoiceBean voteToChoiceBean = voteBean.getChoice().iterator().next(); - Assert.assertNotNull(voteToChoiceBean); - Assert.assertEquals(1.5, voteToChoiceBean.getVoteValue(), 0); - Assert.assertEquals("AA", voteToChoiceBean.getChoiceId().getReducedId()); - - String convert = converter.convert(String.class, voteBean); - Assert.assertNotNull(convert); - - } - - @Test - public void convertEntity() { - - String pollStr = "{topiaCreateDate: 1399033089600, title: \"pollTitle\", " + - "choice: [ {value: \"choice1\", choiceType: \"TEXT\"}, " + - "{value: \"choice2\", choiceType: \"IMAGE\"} ], voteVisibility: \"ANONYMOUS\", " + - "commentVisibility:\"CREATOR\", pollType: \"FREE\" }"; - - JsonConverter<Poll> converter = JsonConverter.newEntityConverter(new FullyQualifiedNamePlusUuidTopiaIdFactory(), Poll.class); - - Poll poll = converter.convert(Poll.class, pollStr); - - Assert.assertNotNull(poll); - Assert.assertEquals("pollTitle", poll.getTitle()); - Assert.assertEquals(VoteVisibility.ANONYMOUS, poll.getVoteVisibility()); - Assert.assertEquals(CommentVisibility.CREATOR, poll.getCommentVisibility()); - Assert.assertEquals(PollType.FREE, poll.getPollType()); -// Assert.assertEquals(2, poll.sizeChoice()); -// Assert.assertEquals("choice1", poll.getChoice(0).getChoiceValue()); -// Assert.assertEquals(ChoiceType.TEXT, poll.getChoice(0).getChoiceType()); -// Assert.assertEquals("choice2", poll.getChoice(1).getChoiceValue()); -// Assert.assertEquals(ChoiceType.IMAGE, poll.getChoice(1).getChoiceType()); - - String convert = converter.convert(String.class, poll); - Assert.assertNotNull(convert); - - } - -} diff --git a/pollen-services/pom.xml b/pollen-services/pom.xml index 755343ed..7bc05ad7 100644 --- a/pollen-services/pom.xml +++ b/pollen-services/pom.xml @@ -223,6 +223,15 @@ <artifactId>log4j</artifactId> <scope>test</scope> </dependency> + <dependency> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-annotations</artifactId> + </dependency> + + <dependency> + <groupId>org.jboss.resteasy</groupId> + <artifactId>resteasy-jaxrs</artifactId> + </dependency> </dependencies> diff --git a/pollen-services/src/main/java/org/chorem/pollen/services/bean/PaginationParameterBean.java b/pollen-services/src/main/java/org/chorem/pollen/services/bean/PaginationParameterBean.java index b4261902..7eec3ab4 100644 --- a/pollen-services/src/main/java/org/chorem/pollen/services/bean/PaginationParameterBean.java +++ b/pollen-services/src/main/java/org/chorem/pollen/services/bean/PaginationParameterBean.java @@ -23,6 +23,8 @@ package org.chorem.pollen.services.bean; import org.nuiton.util.pagination.PaginationParameter; +import javax.ws.rs.QueryParam; + /** * Created on 5/27/14. * @@ -75,6 +77,7 @@ public class PaginationParameterBean { return pageNumber; } + @QueryParam("pageNumber") public void setPageNumber(int pageNumber) { this.pageNumber = pageNumber; } @@ -83,6 +86,7 @@ public class PaginationParameterBean { return pageSize; } + @QueryParam("pageSize") public void setPageSize(int pageSize) { this.pageSize = pageSize; } @@ -91,6 +95,7 @@ public class PaginationParameterBean { return order; } + @QueryParam("order") public void setOrder(String order) { this.order = order; } @@ -99,6 +104,7 @@ public class PaginationParameterBean { return desc; } + @QueryParam("desc") public void setDesc(boolean desc) { this.desc = desc; } diff --git a/pollen-services/src/main/java/org/chorem/pollen/services/bean/PollenBean.java b/pollen-services/src/main/java/org/chorem/pollen/services/bean/PollenBean.java index 24779cfd..9a2fe4ed 100644 --- a/pollen-services/src/main/java/org/chorem/pollen/services/bean/PollenBean.java +++ b/pollen-services/src/main/java/org/chorem/pollen/services/bean/PollenBean.java @@ -21,7 +21,7 @@ package org.chorem.pollen.services.bean; * #L% */ -import com.google.common.base.Preconditions; +import com.fasterxml.jackson.annotation.JsonIgnore; import org.nuiton.topia.persistence.TopiaEntity; import java.util.Objects; @@ -44,14 +44,21 @@ public abstract class PollenBean<E extends TopiaEntity> { } public void setId(PollenEntityId<E> id) { - Preconditions.checkNotNull("id can not be null", id); - this.id = id; + if (id == null) { + this.id.setEntityId(null); + this.id.setReducedId(null); + } else { + this.id = id; + } + } + @JsonIgnore public boolean isPersisted() { return id != null && id.isNotEmpty() && !id.isTemporaryId(); } + @JsonIgnore public String getEntityId() { return id.getEntityId(); } @@ -60,6 +67,7 @@ public abstract class PollenBean<E extends TopiaEntity> { return id; } + @JsonIgnore public boolean isTemporaryId() { return id.isTemporaryId(); } diff --git a/pollen-services/src/main/java/org/chorem/pollen/services/bean/PollenEntityId.java b/pollen-services/src/main/java/org/chorem/pollen/services/bean/PollenEntityId.java index 0fc6801a..526ccc3e 100644 --- a/pollen-services/src/main/java/org/chorem/pollen/services/bean/PollenEntityId.java +++ b/pollen-services/src/main/java/org/chorem/pollen/services/bean/PollenEntityId.java @@ -25,9 +25,6 @@ import org.apache.commons.lang3.StringUtils; import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.TopiaIdFactory; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - /** * Created on 5/23/14. * @@ -44,13 +41,6 @@ public class PollenEntityId<E extends TopiaEntity> { protected String reducedId; - public static <E extends TopiaEntity> PollenEntityId<E> newId(Type typeOfT) { - - Type[] actualTypeArguments = ((ParameterizedType) typeOfT).getActualTypeArguments(); - return newId((Class<E>) actualTypeArguments[0]); - - } - public static <E extends TopiaEntity> PollenEntityId<E> newId(Class<E> entityType) { return new PollenEntityId<>(entityType); @@ -141,4 +131,9 @@ public class PollenEntityId<E extends TopiaEntity> { return result; } + + @Override + public String toString() { + return reducedId; + } } diff --git a/pollen-services/src/main/java/org/chorem/pollen/services/bean/PollenEntityRef.java b/pollen-services/src/main/java/org/chorem/pollen/services/bean/PollenEntityRef.java index 45fc609c..4d7f6b3d 100644 --- a/pollen-services/src/main/java/org/chorem/pollen/services/bean/PollenEntityRef.java +++ b/pollen-services/src/main/java/org/chorem/pollen/services/bean/PollenEntityRef.java @@ -31,9 +31,6 @@ import org.chorem.pollen.persistence.entity.SessionToken; import org.chorem.pollen.persistence.entity.Vote; import org.nuiton.topia.persistence.TopiaEntity; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - /** * Created on 5/15/14. * @@ -86,13 +83,6 @@ public class PollenEntityRef<E extends TopiaEntity> extends PollenEntityId<E> { } - public static <E extends TopiaEntity> PollenEntityRef<E> newRef(Type typeOfT) { - - Type[] actualTypeArguments = ((ParameterizedType) typeOfT).getActualTypeArguments(); - return newRef((Class<E>) actualTypeArguments[0]); - - } - public static <E extends TopiaEntity> PollenEntityRef<E> newRef(Class<E> entityType) { return new PollenEntityRef<>(entityType); diff --git a/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoteBean.java b/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoteBean.java index 3be138ca..58fd29d8 100644 --- a/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoteBean.java +++ b/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoteBean.java @@ -81,7 +81,7 @@ public class VoteBean extends PollenBean<Vote> { } setAnonymous(vote.isAnonymous()); - setVoterId(vote.getVoter().getTopiaId()); + getVoterId().setEntityId(vote.getVoter().getTopiaId()); setVoterName(vote.getVoter().getName()); setWeight(vote.getWeight()); @@ -148,10 +148,6 @@ public class VoteBean extends PollenBean<Vote> { this.voterId = voterId; } - public void setVoterId(String voterId) { - getVoterId().setEntityId(voterId); - } - public String getPermission() { return permission; } diff --git a/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoteToChoiceBean.java b/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoteToChoiceBean.java index 1cc738d6..031a5705 100644 --- a/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoteToChoiceBean.java +++ b/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoteToChoiceBean.java @@ -47,7 +47,7 @@ public class VoteToChoiceBean extends PollenBean<VoteToChoice> { setEntityId(entity.getTopiaId()); setVoteValue(entity.getVoteValue()); - setChoiceId(entity.getChoice().getTopiaId()); + getChoiceId().setEntityId(entity.getChoice().getTopiaId()); } @@ -75,10 +75,6 @@ public class VoteToChoiceBean extends PollenBean<VoteToChoice> { this.choiceId = choiceId; } - public void setChoiceId(String choiceId) { - getChoiceId().setEntityId(choiceId); - } - public Double getVoteValue() { return voteValue; } diff --git a/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoterListBean.java b/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoterListBean.java index dc550754..1f8a34b0 100644 --- a/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoterListBean.java +++ b/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoterListBean.java @@ -49,7 +49,7 @@ public class VoterListBean extends PollenBean<VoterList> { setName(entity.getName()); setWeight(entity.getWeight()); if (entity.getParent() != null) { - setParentId(entity.getParent().getTopiaId()); + getParentId().setEntityId(entity.getParent().getTopiaId()); } } @@ -88,7 +88,7 @@ public class VoterListBean extends PollenBean<VoterList> { return parentId; } - public void setParentId(String parentId) { - getParentId().setEntityId(parentId); + public void setParentId(PollenEntityId<VoterList> parentId) { + this.parentId = parentId; } } diff --git a/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoterListMemberBean.java b/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoterListMemberBean.java index 9ac026cc..09825fd6 100644 --- a/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoterListMemberBean.java +++ b/pollen-services/src/main/java/org/chorem/pollen/services/bean/VoterListMemberBean.java @@ -58,7 +58,7 @@ public class VoterListMemberBean extends PollenBean<VoterListMember> { setEmail(entity.getMember().getEmail()); } setWeight(entity.getWeight()); - setVoterListId(entity.getVoterList().getTopiaId()); + getVoterListId().setEntityId(entity.getVoterList().getTopiaId()); } @@ -111,8 +111,8 @@ public class VoterListMemberBean extends PollenBean<VoterListMember> { return voterListId; } - public void setVoterListId(String voterListId) { - getVoterListId().setEntityId(voterListId); + public void setVoterListId(PollenEntityId<VoterList> voterListId) { + this.voterListId = voterListId; } public boolean isVoting() { diff --git a/pollen-services/src/main/java/org/chorem/pollen/services/service/FavoriteListService.java b/pollen-services/src/main/java/org/chorem/pollen/services/service/FavoriteListService.java index fbdb61f2..60ad57ce 100644 --- a/pollen-services/src/main/java/org/chorem/pollen/services/service/FavoriteListService.java +++ b/pollen-services/src/main/java/org/chorem/pollen/services/service/FavoriteListService.java @@ -495,7 +495,7 @@ public class FavoriteListService extends PollenServiceSupport { if (nameNotBlank) { Optional<FavoriteList> sameName = existingFavoriteLists.stream() - .filter(favoriteList1 -> !favoriteList1.getTopiaId().equals(favoriteList.getEntityId())) + .filter(favoriteList1 -> favoriteList1.getTopiaId() == null || !favoriteList1.getTopiaId().equals(favoriteList.getEntityId())) .filter(favoriteList1 -> favoriteList1.getName().equals(favoriteListName)) .findFirst(); diff --git a/pollen-services/src/main/java/org/chorem/pollen/services/service/NotificationService.java b/pollen-services/src/main/java/org/chorem/pollen/services/service/NotificationService.java index 90fce101..ea9b86ac 100644 --- a/pollen-services/src/main/java/org/chorem/pollen/services/service/NotificationService.java +++ b/pollen-services/src/main/java/org/chorem/pollen/services/service/NotificationService.java @@ -32,7 +32,6 @@ import org.chorem.pollen.persistence.entity.Report; import org.chorem.pollen.persistence.entity.Vote; import org.chorem.pollen.persistence.entity.VoterList; import org.chorem.pollen.persistence.entity.VoterListMember; -import org.chorem.pollen.services.PollenUIContext; import org.chorem.pollen.services.service.mail.ChoiceAddedEmail; import org.chorem.pollen.services.service.mail.ChoiceReportEmail; import org.chorem.pollen.services.service.mail.ChoiceReportForAdminEmail; @@ -73,16 +72,16 @@ import java.util.Set; */ public class NotificationService extends PollenServiceSupport { - public void onUserCreated(PollenUser user, PollenUIContext pollenUIContext) { + public void onUserCreated(PollenUser user) { EmailService emailService = getEmailService(); - UserAccountCreatedEmail email = emailService.newUserAccountCreatedEmail(user, pollenUIContext); + UserAccountCreatedEmail email = emailService.newUserAccountCreatedEmail(user); email.addTo(user.getEmail()); emailService.send(email); } - public void onResendValidation(PollenUser user, PollenUIContext pollenUIContext) { + public void onResendValidation(PollenUser user) { EmailService emailService = getEmailService(); - ResendValidationEmail email = emailService.newUserResendValidationEmail(user, pollenUIContext); + ResendValidationEmail email = emailService.newUserResendValidationEmail(user); email.addTo(user.getEmail()); emailService.send(email); } diff --git a/pollen-services/src/main/java/org/chorem/pollen/services/service/PollService.java b/pollen-services/src/main/java/org/chorem/pollen/services/service/PollService.java index 49483f5e..f43cc72c 100644 --- a/pollen-services/src/main/java/org/chorem/pollen/services/service/PollService.java +++ b/pollen-services/src/main/java/org/chorem/pollen/services/service/PollService.java @@ -39,6 +39,7 @@ import org.chorem.pollen.services.bean.PollenEntityRef; import org.chorem.pollen.services.bean.ReportResumeBean; import org.chorem.pollen.services.bean.VoterListBean; import org.chorem.pollen.services.bean.VoterListMemberBean; +import org.chorem.pollen.services.bean.export.ExportBean; import org.chorem.pollen.services.config.PollenServicesConfig; import org.chorem.pollen.services.service.security.PermissionVerb; import org.chorem.pollen.services.service.security.PollenUnauthorizedException; @@ -46,7 +47,6 @@ import org.chorem.pollen.votecounting.VoteCountingNotFound; import org.nuiton.util.pagination.PaginationParameter; import org.nuiton.util.pagination.PaginationResult; -import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -371,7 +371,7 @@ public class PollService extends PollenServiceSupport { } - public File exportPoll(String pollId) { + public ExportBean exportPoll(String pollId) { checkNotNull(pollId); checkPermission(PermissionVerb.exportPoll, pollId); diff --git a/pollen-services/src/main/java/org/chorem/pollen/services/service/PollenUserService.java b/pollen-services/src/main/java/org/chorem/pollen/services/service/PollenUserService.java index 7516c3ef..f7975f36 100644 --- a/pollen-services/src/main/java/org/chorem/pollen/services/service/PollenUserService.java +++ b/pollen-services/src/main/java/org/chorem/pollen/services/service/PollenUserService.java @@ -31,7 +31,6 @@ import org.chorem.pollen.persistence.entity.PollenUser; import org.chorem.pollen.persistence.entity.PollenUserTopiaDao; import org.chorem.pollen.persistence.entity.Vote; import org.chorem.pollen.services.PollenService; -import org.chorem.pollen.services.PollenUIContext; import org.chorem.pollen.services.bean.PaginationParameterBean; import org.chorem.pollen.services.bean.PaginationResultBean; import org.chorem.pollen.services.bean.PollenEntityRef; @@ -92,10 +91,6 @@ public class PollenUserService extends PollenServiceSupport implements PollenSer } public PollenEntityRef<PollenUser> createUser(PollenUserBean user) throws InvalidFormException { - return createUser(user, new PollenUIContext()); - } - - public PollenEntityRef<PollenUser> createUser(PollenUserBean user, PollenUIContext pollenUIContext) throws InvalidFormException { checkNotNull(user); checkIsNotPersisted(user); @@ -107,7 +102,7 @@ public class PollenUserService extends PollenServiceSupport implements PollenSer PollenUser result = savePollenUser(user); commit(); - getNotificationService().onUserCreated(result, pollenUIContext); + getNotificationService().onUserCreated(result); return PollenEntityRef.of(result); @@ -252,7 +247,7 @@ public class PollenUserService extends PollenServiceSupport implements PollenSer } - public void resendValidation(String email, PollenUIContext pollenUIContext) { + public void resendValidation(String email) { checkNotNull(email); PollenUser user = getPollenUserDao().forEmailEquals(email).findUniqueOrNull(); @@ -265,7 +260,7 @@ public class PollenUserService extends PollenServiceSupport implements PollenSer commit(); } - getNotificationService().onResendValidation(user, pollenUIContext); + getNotificationService().onResendValidation(user); } diff --git a/pollen-services/src/main/java/org/chorem/pollen/services/service/VoterListService.java b/pollen-services/src/main/java/org/chorem/pollen/services/service/VoterListService.java index cd501114..39312b3a 100644 --- a/pollen-services/src/main/java/org/chorem/pollen/services/service/VoterListService.java +++ b/pollen-services/src/main/java/org/chorem/pollen/services/service/VoterListService.java @@ -718,7 +718,7 @@ public class VoterListService extends PollenServiceSupport { PollenEntityId<VoterList> parentId = voterList.getParentId(); if (parentId.isNotEmpty() && parentId.isTemporaryId()) { String parentIdString = voterListBeanByTempId.get(parentId.getReducedId()).getEntityId(); - voterList.setParentId(parentIdString); + voterList.getParentId().setEntityId(parentIdString); } voterList.setEntityId(null); @@ -736,7 +736,7 @@ public class VoterListService extends PollenServiceSupport { PollenEntityId<VoterList> voterListId = voterListMember.getVoterListId(); if (voterListId.isEmpty() || voterListId.isTemporaryId()) { String voterListIdString = voterListBeanByTempId.get(voterListId.getReducedId()).getEntityId(); - voterListMember.setVoterListId(voterListIdString); + voterListMember.getVoterListId().setEntityId(voterListIdString); } voterListMember.setEntityId(null); diff --git a/pollen-services/src/main/java/org/chorem/pollen/services/service/mail/EmailService.java b/pollen-services/src/main/java/org/chorem/pollen/services/service/mail/EmailService.java index 8552b21c..dfd31ced 100644 --- a/pollen-services/src/main/java/org/chorem/pollen/services/service/mail/EmailService.java +++ b/pollen-services/src/main/java/org/chorem/pollen/services/service/mail/EmailService.java @@ -45,7 +45,6 @@ import org.chorem.pollen.persistence.entity.PollenResource; import org.chorem.pollen.persistence.entity.PollenUser; import org.chorem.pollen.persistence.entity.Report; import org.chorem.pollen.persistence.entity.Vote; -import org.chorem.pollen.services.PollenUIContext; import org.chorem.pollen.services.bean.PollenEntityId; import org.chorem.pollen.services.config.PollenServicesConfig; import org.chorem.pollen.services.service.PollenServiceSupport; @@ -198,14 +197,14 @@ public class EmailService extends PollenServiceSupport { return email; } - public UserAccountCreatedEmail newUserAccountCreatedEmail(PollenUser user, PollenUIContext pollenUIContext) { + public UserAccountCreatedEmail newUserAccountCreatedEmail(PollenUser user) { UserAccountCreatedEmail email = new UserAccountCreatedEmail(getLocale()); email.setUser(user); - email.setPollenUrl(pollenUIContext.getUiEndPoint()); + email.setPollenUrl(getUIContext().getUiEndPoint()); PollenEntityId<PollenUser> userId = getPollenEntityId(user); - email.setValidateUrl(getPollenUIUrlRenderService().getUserValidateUrl(pollenUIContext.getUserValidateUrl(), + email.setValidateUrl(getPollenUIUrlRenderService().getUserValidateUrl(getUIContext().getUserValidateUrl(), userId.getReducedId(), user.getEmailActivationToken().getToken())); @@ -230,13 +229,13 @@ public class EmailService extends PollenServiceSupport { return email; } - public ResendValidationEmail newUserResendValidationEmail(PollenUser user, PollenUIContext pollenUIContext) { + public ResendValidationEmail newUserResendValidationEmail(PollenUser user) { ResendValidationEmail email = new ResendValidationEmail(getLocale()); email.setUser(user); - email.setPollenUrl(pollenUIContext.getUiEndPoint()); + email.setPollenUrl(getUIContext().getUiEndPoint()); PollenEntityId<PollenUser> userId = getPollenEntityId(user); - email.setValidateUrl(getPollenUIUrlRenderService().getUserValidateUrl(pollenUIContext.getUserValidateUrl(), + email.setValidateUrl(getPollenUIUrlRenderService().getUserValidateUrl(getUIContext().getUserValidateUrl(), userId.getReducedId(), user.getEmailActivationToken().getToken())); diff --git a/pollen-services/src/main/java/org/chorem/pollen/services/test/FakePollenServiceContext.java b/pollen-services/src/main/java/org/chorem/pollen/services/test/FakePollenServiceContext.java index 349a79ea..3469dc27 100644 --- a/pollen-services/src/main/java/org/chorem/pollen/services/test/FakePollenServiceContext.java +++ b/pollen-services/src/main/java/org/chorem/pollen/services/test/FakePollenServiceContext.java @@ -27,6 +27,7 @@ import org.apache.commons.logging.LogFactory; import org.chorem.pollen.persistence.PollenTopiaApplicationContext; import org.chorem.pollen.persistence.PollenTopiaPersistenceContext; import org.chorem.pollen.services.DefaultPollenServiceContext; +import org.chorem.pollen.services.PollenUIContext; import org.chorem.pollen.services.config.PollenServicesConfig; import org.chorem.pollen.votecounting.VoteCountingFactory; @@ -55,6 +56,7 @@ public class FakePollenServiceContext extends DefaultPollenServiceContext { serviceContext.setSecurityContext(new FakePollenSecurityContext()); serviceContext.setLocale(locale); serviceContext.setDate(now); + serviceContext.setUIContext(new PollenUIContext()); return serviceContext; } diff --git a/pollen-services/src/test/java/org/chorem/pollen/services/service/VoteCountingServiceTest.java b/pollen-services/src/test/java/org/chorem/pollen/services/service/VoteCountingServiceTest.java index a86d9044..5840a8d1 100644 --- a/pollen-services/src/test/java/org/chorem/pollen/services/service/VoteCountingServiceTest.java +++ b/pollen-services/src/test/java/org/chorem/pollen/services/service/VoteCountingServiceTest.java @@ -107,7 +107,7 @@ public class VoteCountingServiceTest extends AbstractPollenServiceTest { vote1.setVoterName("voter1"); VoteToChoiceBean vote1Choice1 = new VoteToChoiceBean(); - vote1Choice1.setChoiceId(createdChoiceBean1.getEntityId()); + vote1Choice1.getChoiceId().setEntityId(createdChoiceBean1.getEntityId()); vote1Choice1.setVoteValue(1d); vote1.addChoice(vote1Choice1); voteService.addVote(pollId, vote1); @@ -116,7 +116,7 @@ public class VoteCountingServiceTest extends AbstractPollenServiceTest { VoteBean vote2 = new VoteBean(); vote2.setVoterName("voter2"); VoteToChoiceBean vote2Choice2 = new VoteToChoiceBean(); - vote2Choice2.setChoiceId(createdChoiceBean2.getEntityId()); + vote2Choice2.getChoiceId().setEntityId(createdChoiceBean2.getEntityId()); vote2Choice2.setVoteValue(1d); vote2.addChoice(vote2Choice2); voteService.addVote(pollId, vote2); @@ -125,7 +125,7 @@ public class VoteCountingServiceTest extends AbstractPollenServiceTest { VoteBean vote3 = new VoteBean(); vote3.setVoterName("voter3"); VoteToChoiceBean vote3Choice1 = new VoteToChoiceBean(); - vote3Choice1.setChoiceId(createdChoiceBean1.getEntityId()); + vote3Choice1.getChoiceId().setEntityId(createdChoiceBean1.getEntityId()); vote3Choice1.setVoteValue(1d); vote3.addChoice(vote3Choice1); voteService.addVote(pollId, vote3); diff --git a/pollen-ui-riot-js/src/main/web/css/custom-code-lutin.css b/pollen-ui-riot-js/src/main/web/css/custom-code-lutin.css new file mode 100644 index 00000000..ae831f39 --- /dev/null +++ b/pollen-ui-riot-js/src/main/web/css/custom-code-lutin.css @@ -0,0 +1,59 @@ + +:root{ + --main: #ff9306; + --background: #3a2913; + --default: #f3ebe1; + + --winner: #ff9e0d; + --anonymous: #666666; + + --poll-created: grey; + --poll-adding_choices: orange; + --poll-voting: #13a2ff; + --poll-closed: #53bd41; + + --separator: #b2c7d3; + + --dropdown: #f9f9f9; + --dropdown-text: #ff9306; + --dropdown-shadow: #00000004; + --dropdown-hover: #f1f1f1; + + --footer: black; + --footer-text: #ffffff; + --footer-text-hover: #ff9306; + + --qrcode: #ff9306; + + --focus: #f3ebe1; + --shadow: #f3ebe1; + --active: #7b929e; + --btn-hover: #b0bec5; + --disabled: #888888; + + --brand: hsl( 34, 100%, 50%); + --brand-active: hsl( 34, 100%, 40%); + --brand-hover: hsl( 34, 100%, 60%); + --info: hsl( 45, 100%, 50%); + --info-active: hsl( 45, 100%, 40%); + --info-hover: hsl( 45, 100%, 60%); + --warning: hsl(271, 72%, 60%); + --warning-active: hsl(271, 72%, 50%); + --warning-hover: hsl(271, 72%, 70%); + --success: hsl( 85, 100%, 50%); + --success-active: hsl( 85, 100%, 40%); + --success-hover: hsl( 85, 100%, 60%); + --error: hsl( 0, 100%, 50%); + --error-active: hsl( 0, 100%, 40%); + --error-hover: hsl( 0, 100%, 60%); + + --overlay: hsla(0, 100%, 90%, 0.22); + + --toggle: #ffc477; + --toggle-shadow: #ff9306; + + --code: #000000; + --code-text: #ffffff; + + --title: "Votation des lutins"; +} diff --git a/pollen-ui-riot-js/src/main/web/js/AuthService.js b/pollen-ui-riot-js/src/main/web/js/AuthService.js index 7238ed5b..54f272c4 100644 --- a/pollen-ui-riot-js/src/main/web/js/AuthService.js +++ b/pollen-ui-riot-js/src/main/web/js/AuthService.js @@ -36,9 +36,12 @@ class AuthService extends FetchService { } signUp(user) { - return this.form("/v1/users", { - user: user - }); + let user1 = { + name: user.name, + email: user.email, + password: user.password + }; + return this.post("/v1/users", user1); } signOut() { @@ -62,7 +65,7 @@ class AuthService extends FetchService { } resendValidation(email) { - return this.form("/v1/resendValidation", {login: email}); + return this.post("/v1/resendValidation", email); } } diff --git a/pollen-ui-riot-js/src/main/web/js/ChoiceService.js b/pollen-ui-riot-js/src/main/web/js/ChoiceService.js index 01c7975e..d908b5e4 100644 --- a/pollen-ui-riot-js/src/main/web/js/ChoiceService.js +++ b/pollen-ui-riot-js/src/main/web/js/ChoiceService.js @@ -28,27 +28,27 @@ class ChoiceService extends FetchService { if (permission) { args.permission = permission; } - return this.getWithParams("/v1/polls/" + pollId + "/choices", args); + return this.getWithParams("/v1/choices/" + pollId, args); } addChoice(pollId, form, permission) { - let url = "/v1/polls/" + pollId + "/choices"; + let url = "/v1/choices/" + pollId + "/"; if (permission) { url += "?permission=" + permission; } - return this.form(url, {choice: form}); + return this.post(url, form); } updateChoice(pollId, form, permission) { - let url = "/v1/polls/" + pollId + "/choices/" + form.id; + let url = "/v1/choices/" + pollId + "/" + form.id; if (permission) { url += "?permission=" + permission; } - return this.form(url, {choice: form}); + return this.post(url, form); } deleteChoice(pollId, choiceId, permission) { - let url = "/v1/polls/" + pollId + "/choices/" + choiceId; + let url = "/v1/choices/" + pollId + "/" + choiceId; if (permission) { url += "?permission=" + permission; } @@ -56,11 +56,11 @@ class ChoiceService extends FetchService { } addReport(pollId, choiceId, report, permission) { - let url = "/v1/polls/" + pollId + "/choices/" + choiceId + "/reports"; + let url = "/v1/choices/" + pollId + "/" + choiceId + "/reports"; if (permission) { url += "?permission=" + permission; } - return this.form(url, {report: report}); + return this.post(url, report); } getReports(pollId, choiceId, permission) { @@ -68,15 +68,15 @@ class ChoiceService extends FetchService { if (permission) { args.permission = permission; } - return this.getWithParams("/v1/polls/" + pollId + "/choices/" + choiceId + "/reports", args); + return this.getWithParams("/v1/choices/" + pollId + "/" + choiceId + "/reports", args); } saveReport(pollId, choiceId, report, permission) { - let url = "/v1/polls/" + pollId + "/choices/" + choiceId + "/reports/" + report.id; + let url = "/v1/choices/" + pollId + "/" + choiceId + "/reports/" + report.id; if (permission) { url += "?permission=" + permission; } - return this.form(url, {report: report}); + return this.post(url, report); } } diff --git a/pollen-ui-riot-js/src/main/web/js/CommentService.js b/pollen-ui-riot-js/src/main/web/js/CommentService.js index 135a170e..4e9870cb 100644 --- a/pollen-ui-riot-js/src/main/web/js/CommentService.js +++ b/pollen-ui-riot-js/src/main/web/js/CommentService.js @@ -24,11 +24,11 @@ let FetchService = require("./FetchService"); class CommentService extends FetchService { getComments(pollId, pagination, permission) { - let args = {paginationParameter: pagination}; + let params = Object.assign({}, pagination); if (permission) { - args.permission = permission; + params.permission = permission; } - return this.getWithParams("/v1/polls/" + pollId + "/comments", args); + return this.getWithParams("/v1/comments/" + pollId, params); } getNewComment(pollId, permission) { @@ -36,27 +36,27 @@ class CommentService extends FetchService { if (permission) { args.permission = permission; } - return this.getWithParams("/v1/polls/" + pollId + "/comments/new", args); + return this.getWithParams("/v1/comments/" + pollId + "/new", args); } createComment(pollId, form, permission) { - let url = "/v1/polls/" + pollId + "/comments"; + let url = "/v1/comments/" + pollId; if (permission) { url += "?permission=" + permission; } - return this.form(url, {comment: form}); + return this.post(url, form); } updateComment(pollId, form, permission) { - let url = "/v1/polls/" + pollId + "/comments/" + form.id; + let url = "/v1/comments/" + pollId + "/" + form.id; if (permission) { url += "?permission=" + permission; } - return this.form(url, {comment: form}); + return this.post(url, form); } deleteComment(pollId, commentId, permission) { - let url = "/v1/polls/" + pollId + "/comments/" + commentId; + let url = "/v1/comments/" + pollId + "/" + commentId; if (permission) { url += "?permission=" + permission; } @@ -64,11 +64,11 @@ class CommentService extends FetchService { } addReport(pollId, commentId, report, permission) { - let url = "/v1/polls/" + pollId + "/comments/" + commentId + "/reports"; + let url = "/v1/comments/" + pollId + "/" + commentId + "/reports"; if (permission) { url += "?permission=" + permission; } - return this.form(url, {report: report}); + return this.post(url, report); } getReports(pollId, commentId, permission) { @@ -76,7 +76,7 @@ class CommentService extends FetchService { if (permission) { args.permission = permission; } - return this.getWithParams("/v1/polls/" + pollId + "/comments/" + commentId + "/reports", args); + return this.getWithParams("/v1/comments/" + pollId + "/" + commentId + "/reports", args); } ignoreReport(pollId, commentId, reportId, permission) { @@ -84,15 +84,15 @@ class CommentService extends FetchService { if (permission) { args.permission = permission; } - return this.getWithParams("/v1/polls/" + pollId + "/comments/" + commentId + "/reports/" + reportId + "/ignore", args); + return this.getWithParams("/v1/comments/" + pollId + "/" + commentId + "/reports/" + reportId + "/ignore", args); } saveReport(pollId, commentId, report, permission) { - let url = "/v1/polls/" + pollId + "/comments/" + commentId + "/reports/" + report.id; + let url = "/v1/comments/" + pollId + "/" + commentId + "/reports/" + report.id; if (permission) { url += "?permission=" + permission; } - return this.form(url, {report: report}); + return this.post(url, report); } } diff --git a/pollen-ui-riot-js/src/main/web/js/FavoriteListService.js b/pollen-ui-riot-js/src/main/web/js/FavoriteListService.js index 5934a82c..fba20a2b 100644 --- a/pollen-ui-riot-js/src/main/web/js/FavoriteListService.js +++ b/pollen-ui-riot-js/src/main/web/js/FavoriteListService.js @@ -24,7 +24,9 @@ let FetchService = require("./FetchService"); class FavoriteListService extends FetchService { favoriteLists(pagination, search) { - return this.getWithParams("/v1/favoriteLists", {paginationParameter: pagination, search: search || ""}); + let params = Object.assign({}, pagination); + params.search = search || ""; + return this.getWithParams("/v1/favoriteLists", params); } favoriteList(favoriteListId) { @@ -40,15 +42,15 @@ class FavoriteListService extends FetchService { } importLdap(favoriteListId, ldap) { - return this.form("/v1/favoriteLists/" + favoriteListId + "/importLdap", {ldap: ldap}); + return this.post("/v1/favoriteLists/" + favoriteListId + "/importLdap", ldap); } createFavoriteList(favoriteList) { - return this.form("/v1/favoriteLists", {favoriteList: favoriteList}); + return this.post("/v1/favoriteLists", favoriteList); } saveFavoriteList(favoriteList) { - return this.form("/v1/favoriteLists/" + favoriteList.id, {favoriteList: favoriteList}); + return this.post("/v1/favoriteLists/" + favoriteList.id, favoriteList); } deleteFavoriteList(favoriteListId) { @@ -56,7 +58,9 @@ class FavoriteListService extends FetchService { } members(favoriteListId, search, pagination) { - return this.getWithParams("/v1/favoriteLists/" + favoriteListId + "/members", {paginationParameter: pagination, search: search || ""}); + let params = Object.assign({}, pagination); + params.search = search || ""; + return this.getWithParams("/v1/favoriteLists/" + favoriteListId + "/members", params); } member(favoriteListId, memberId) { @@ -64,11 +68,11 @@ class FavoriteListService extends FetchService { } addMember(favoriteListId, member) { - return this.form("/v1/favoriteLists/" + favoriteListId + "/members", {member: member}); + return this.post("/v1/favoriteLists/" + favoriteListId + "/members", member); } saveMember(favoriteListId, member) { - return this.form("/v1/favoriteLists/" + favoriteListId + "/members/" + member.id, {member: member}); + return this.post("/v1/favoriteLists/" + favoriteListId + "/members/" + member.id, member); } deleteMember(favoriteListId, memberId) { @@ -76,7 +80,9 @@ class FavoriteListService extends FetchService { } childrenLists(favoriteListId, search, pagination) { - return this.getWithParams("/v1/favoriteLists/" + favoriteListId + "/lists", {paginationParameter: pagination, search: search || ""}); + let params = Object.assign({}, pagination); + params.search = search || ""; + return this.getWithParams("/v1/favoriteLists/" + favoriteListId + "/lists", params); } childList(favoriteListId, childListId) { @@ -84,11 +90,11 @@ class FavoriteListService extends FetchService { } addChildList(favoriteListId, childList) { - return this.form("/v1/favoriteLists/" + favoriteListId + "/lists", {childList: childList}); + return this.post("/v1/favoriteLists/" + favoriteListId + "/lists", childList); } saveChildList(favoriteListId, childList) { - return this.form("/v1/favoriteLists/" + favoriteListId + "/lists/" + childList.id, {childList: childList}); + return this.post("/v1/favoriteLists/" + favoriteListId + "/lists/" + childList.id, childList); } deleteChildList(favoriteListId, childListId) { @@ -96,11 +102,13 @@ class FavoriteListService extends FetchService { } importFromVoterList(voterListId) { - return this.form("/v1/favoriteLists/importVoterList", {voterListId: voterListId}); + return this.post("/v1/favoriteLists/importVoterList", voterListId); } allChildren(favoriteListId, pagination, search) { - return this.getWithParams("/v1/favoriteLists/" + favoriteListId + "/all", {paginationParameter: pagination, search: search || ""}); + let params = Object.assign({}, pagination); + params.search = search || ""; + return this.getWithParams("/v1/favoriteLists/" + favoriteListId + "/all", params); } } diff --git a/pollen-ui-riot-js/src/main/web/js/FetchService.js b/pollen-ui-riot-js/src/main/web/js/FetchService.js index 5c81334e..72abddfc 100644 --- a/pollen-ui-riot-js/src/main/web/js/FetchService.js +++ b/pollen-ui-riot-js/src/main/web/js/FetchService.js @@ -41,7 +41,7 @@ class FetchService { headers, method, credentials: "include", - body: body instanceof FormData ? body : body && JSON.stringify(body) + body: (body instanceof FormData || typeof body === "string") ? body : body && JSON.stringify(body) }) .then((response) => { bus.trigger("loaded", loadEvent); @@ -117,7 +117,6 @@ class FetchService { formData.set(key, value); } }); - formData.set("pollenUIContext", JSON.stringify(require("./Session").pollenUIContext)); } return this.fetch(url, "POST", null, formData); } diff --git a/pollen-ui-riot-js/src/main/web/js/PollService.js b/pollen-ui-riot-js/src/main/web/js/PollService.js index 4ecbc1d2..23af7667 100644 --- a/pollen-ui-riot-js/src/main/web/js/PollService.js +++ b/pollen-ui-riot-js/src/main/web/js/PollService.js @@ -28,27 +28,41 @@ class PollService extends FetchService { } create(poll, choices, voterLists, voterListMembers) { - return this.form("/v1/polls/create", {poll: poll, choices: choices, voterLists: voterLists, voterListMembers: voterListMembers}); + let poll2 = Object.assign({}, poll); + delete poll2.participant; + delete poll2.votePeriod; + delete poll2.addChoices; + delete poll2.anonymousVote; + delete poll2.alreadyParticipants; + delete poll2.limitChoices; + return this.post("/v1/polls", {poll: poll2, choices: choices, voterLists: voterLists, voterListMembers: voterListMembers}); } save(poll) { - return this.form("/v1/polls/edit?permission=" + poll.permission, {poll: poll}); + let poll2 = Object.assign({}, poll); + delete poll2.participant; + delete poll2.votePeriod; + delete poll2.addChoices; + delete poll2.anonymousVote; + delete poll2.alreadyParticipants; + delete poll2.limitChoices; + return this.post("/v1/polls/" + poll.id + "?permission=" + poll.permission, poll2); } createdPolls(pagination) { - return this.getWithParams("/v1/polls/created", {paginationParameter: pagination}); + return this.getWithParams("/v1/polls/created", pagination); } invitedPolls(pagination) { - return this.getWithParams("/v1/polls/invited", {paginationParameter: pagination}); + return this.getWithParams("/v1/polls/invited", pagination); } participatedPolls(pagination) { - return this.getWithParams("/v1/polls/participated", {paginationParameter: pagination}); + return this.getWithParams("/v1/polls/participated", pagination); } polls(pagination) { - return this.getWithParams("/v1/polls", {paginationParameter: pagination}); + return this.getWithParams("/v1/polls", pagination); } deletePoll(pollId, permission) { diff --git a/pollen-ui-riot-js/src/main/web/js/ResultService.js b/pollen-ui-riot-js/src/main/web/js/ResultService.js index 74b88b37..d6e70ccc 100644 --- a/pollen-ui-riot-js/src/main/web/js/ResultService.js +++ b/pollen-ui-riot-js/src/main/web/js/ResultService.js @@ -28,7 +28,7 @@ class ResultService extends FetchService { if (permission) { args.permission = permission; } - return this.getWithParams("/v1/polls/" + pollId + "/results", args); + return this.getWithParams("/v1/results/" + pollId, args); } } diff --git a/pollen-ui-riot-js/src/main/web/js/Session.js b/pollen-ui-riot-js/src/main/web/js/Session.js index 52c7c7ad..67fed2ef 100644 --- a/pollen-ui-riot-js/src/main/web/js/Session.js +++ b/pollen-ui-riot-js/src/main/web/js/Session.js @@ -150,6 +150,7 @@ class Session { return authService.signOut().then(() => { this.user = null; bus.trigger("user", this.user); + return this.user; }); } diff --git a/pollen-ui-riot-js/src/main/web/js/UIHelper.js b/pollen-ui-riot-js/src/main/web/js/UIHelper.js index ff0c963e..b82eca21 100644 --- a/pollen-ui-riot-js/src/main/web/js/UIHelper.js +++ b/pollen-ui-riot-js/src/main/web/js/UIHelper.js @@ -51,6 +51,10 @@ module.exports = { return this.formatDate(date, "YYYY-MM-DDTHH:mm"); }, + formatDateTimeForSubmit(date) { + return this.formatDate(date, "YYYY-MM-DDTHH:mm:ss.SSS"); + }, + bus: require("./PollenBus.js"), listen(events, callback) { diff --git a/pollen-ui-riot-js/src/main/web/js/UserService.js b/pollen-ui-riot-js/src/main/web/js/UserService.js index 6ed3f3c9..93c7605d 100644 --- a/pollen-ui-riot-js/src/main/web/js/UserService.js +++ b/pollen-ui-riot-js/src/main/web/js/UserService.js @@ -24,7 +24,7 @@ let FetchService = require("./FetchService"); class UserService extends FetchService { users(pagination) { - return this.getWithParams("/v1/users", {paginationParameter: pagination}); + return this.getWithParams("/v1/users", pagination); } user(userId, permission) { @@ -56,12 +56,15 @@ class UserService extends FetchService { } saveUser(user) { - return this.form("/v1/users/edit", {user: user}); + return this.post("/v1/users/edit", user); } changePassword(userId, oldPassword, newPassword) { - let body = {oldPassword: oldPassword, newPassword: newPassword}; - return this.form("/v1/users/" + userId + "/password", body); + let body = { + oldPassword: oldPassword, + newPassword: newPassword + }; + return this.post("/v1/users/" + userId + "/password", body); } } diff --git a/pollen-ui-riot-js/src/main/web/js/VoteService.js b/pollen-ui-riot-js/src/main/web/js/VoteService.js index cb6a68be..92c71e43 100644 --- a/pollen-ui-riot-js/src/main/web/js/VoteService.js +++ b/pollen-ui-riot-js/src/main/web/js/VoteService.js @@ -28,15 +28,15 @@ class VoteService extends FetchService { if (permission) { args.permission = permission; } - return this.getWithParams("/v1/polls/" + pollId + "/votes", args); + return this.getWithParams("/v1/votes/" + pollId, args); } addVote(pollId, form, permission) { - let url = "/v1/polls/" + pollId + "/votes"; + let url = "/v1/votes/" + pollId; if (permission) { url += "?permission=" + permission; } - return this.form(url, {vote: form}); + return this.post(url, form); } getNewVote(pollId, permission) { @@ -44,19 +44,19 @@ class VoteService extends FetchService { if (permission) { args.permission = permission; } - return this.getWithParams("/v1/polls/" + pollId + "/votes/new", args); + return this.getWithParams("/v1/votes/" + pollId + "/new", args); } updateVote(pollId, form, permission) { - let url = "/v1/polls/" + pollId + "/votes/" + form.id; + let url = "/v1/votes/" + pollId + "/" + form.id; if (permission) { url += "?permission=" + permission; } - return this.form(url, {vote: form}); + return this.post(url, form); } deleteVote(pollId, voteId, permission) { - let url = "/v1/polls/" + pollId + "/votes/" + voteId; + let url = "/v1/votes/" + pollId + "/" + voteId; if (permission) { url += "?permission=" + permission; } diff --git a/pollen-ui-riot-js/src/main/web/js/VoterListService.js b/pollen-ui-riot-js/src/main/web/js/VoterListService.js index aae9bc26..ac81784f 100644 --- a/pollen-ui-riot-js/src/main/web/js/VoterListService.js +++ b/pollen-ui-riot-js/src/main/web/js/VoterListService.js @@ -51,7 +51,7 @@ class VoterListService extends FetchService { this.pollForm = pollForm; let mainVoterListPromise = Promise.resolve(); if (this.pollForm.model && this.pollForm.model.id) { - mainVoterListPromise = this.getWithParams("/v1/polls/" + pollForm.model.id + "/mainVoterList", {permission: pollForm.model.permission}); + mainVoterListPromise = this.getWithParams("/v1/voterLists/" + pollForm.model.id + "/main", {permission: pollForm.model.permission}); } mainVoterListPromise = mainVoterListPromise.then(list => { let mainList = list || this._newVoterList(); @@ -67,8 +67,8 @@ class VoterListService extends FetchService { voterListPromise = Promise.resolve([[], []]); if (this.pollForm.model && this.pollForm.model.id && !voterList.subLists && !voterList.id.startsWith(this.tempPrefix)) { voterListPromise = Promise.all([ - this.getWithParams("/v1/polls/" + this.pollForm.model.id + "/voterLists/" + voterList.id + "/lists", {permission: this.pollForm.model.permission}), - this.getWithParams("/v1/polls/" + this.pollForm.model.id + "/voterLists/" + voterList.id + "/members", {permission: this.pollForm.model.permission})]); + this.getWithParams("/v1/voterLists/" + this.pollForm.model.id + "/" + voterList.id + "/lists", {permission: this.pollForm.model.permission}), + this.getWithParams("/v1/voterLists/" + this.pollForm.model.id + "/" + voterList.id + "/members", {permission: this.pollForm.model.permission})]); } voterListPromise.then(result => { voterList.subLists = result[0]; @@ -167,7 +167,7 @@ class VoterListService extends FetchService { } save() { - return this.form("/v1/polls/" + this.pollForm.model.id + "/voterLists/save?permission=" + this.pollForm.model.permission, + return this.post("/v1/voterLists/" + this.pollForm.model.id + "/save?permission=" + this.pollForm.model.permission, { listsToSave: this.getVoterLists(), membersToSave: this.getVoterListMembers(), @@ -207,15 +207,15 @@ class VoterListService extends FetchService { resendInvitationList(voterList) { if (!voterList.temp) { - return this.getWithParams("/v1/polls/" + this.pollForm.model.id + "/voterLists/" + voterList.id + "/resend", {permission: this.pollForm.model.permission}); + return this.getWithParams("/v1/voterLists/" + this.pollForm.model.id + "/" + voterList.id + "/resend", {permission: this.pollForm.model.permission}); } return Promise.reject(); } resendInvitationMember(member) { if (!member.temp) { - return this.getWithParams("/v1/polls/" + this.pollForm.model.id - + "/voterLists/" + member.voterListId + return this.getWithParams("/v1/voterLists/" + this.pollForm.model.id + + "/" + member.voterListId + "/members/" + member.id + "/resend", {permission: this.pollForm.model.permission}); } diff --git a/pollen-ui-riot-js/src/main/web/tag/UserCard.tag.html b/pollen-ui-riot-js/src/main/web/tag/UserCard.tag.html index 0cf64484..f10dd637 100644 --- a/pollen-ui-riot-js/src/main/web/tag/UserCard.tag.html +++ b/pollen-ui-riot-js/src/main/web/tag/UserCard.tag.html @@ -5,7 +5,7 @@ require("./components/HumanInput.tag.html"); <span> {opts.user.name} - {opts.user.email} <i class="fa fa-refresh" if={!user.emailIsValidate} title={__.emailValidate}></i> - <i class="fa fa-ban" if={user.isBanned} title={__.banned}></i> + <i class="fa fa-ban" if={user.banned} title={__.banned}></i> <i class="fa fa-cog" if={user.administrator} title={__.administrator}></i> </span> </div> diff --git a/pollen-ui-riot-js/src/main/web/tag/components/date-time-picker.tag.html b/pollen-ui-riot-js/src/main/web/tag/components/date-time-picker.tag.html index 032d1d95..0f02308c 100644 --- a/pollen-ui-riot-js/src/main/web/tag/components/date-time-picker.tag.html +++ b/pollen-ui-riot-js/src/main/web/tag/components/date-time-picker.tag.html @@ -48,7 +48,7 @@ require("./time-picker.tag.html"); this.getValue = () => { if (this.session.dateInputSupported) { - return this.refs.dateInputSupportedField.value; + return this.formatDateTimeForSubmit(this.refs.dateInputSupportedField.value); } if (!this.date.date || !this.time.time) { return null; @@ -60,7 +60,7 @@ require("./time-picker.tag.html"); hour: this.time.time.hour(), minute: this.time.time.minute() }); - return this.formatDateTimeForInput(selectedMoment.valueOf()); + return this.formatDateTimeForSubmit(selectedMoment.valueOf()); }; this.reset = () => { diff --git a/pollen-ui-riot-js/src/main/web/tag/favoriteList/FavoriteList.tag.html b/pollen-ui-riot-js/src/main/web/tag/favoriteList/FavoriteList.tag.html index 7677196c..6320f749 100644 --- a/pollen-ui-riot-js/src/main/web/tag/favoriteList/FavoriteList.tag.html +++ b/pollen-ui-riot-js/src/main/web/tag/favoriteList/FavoriteList.tag.html @@ -47,7 +47,7 @@ require("../components/LoadingCard.tag.html"); </LoadingCard> </yield> </LazyLoad> - + <ContextualMenu> <a onclick={parent.addMember} > {parent.__.member_new} @@ -127,6 +127,7 @@ require("../components/LoadingCard.tag.html"); this.createChildList = () => { this.refs.createChildListModal.open().then(() => { + this.update(); this.refresh(); }, () => {}); this.update(); diff --git a/pollen-ui-riot-js/src/main/web/tag/favoriteList/FavoriteLists.tag.html b/pollen-ui-riot-js/src/main/web/tag/favoriteList/FavoriteLists.tag.html index c1216a51..10845333 100644 --- a/pollen-ui-riot-js/src/main/web/tag/favoriteList/FavoriteLists.tag.html +++ b/pollen-ui-riot-js/src/main/web/tag/favoriteList/FavoriteLists.tag.html @@ -19,7 +19,7 @@ require("./FavoriteListEditModal.tag.html"); <div class="c-alert c-alert--info"> {count === 0 ? __.noFavoriteList : (count + " " + (count === 1 ? __.one : __.many))} <a class="c-button c-button--info" - if={pagination.count > 0} + if={count > 0} href="{session.configuration.endPoint}/v1/favoriteLists/exports" target="_blank" title={__.export}> @@ -107,18 +107,19 @@ require("./FavoriteListEditModal.tag.html"); }; this.openImportModal = () => { - this.refs.importModal.open(); + this.refs.importModal.open().then(() => { + this.update(); + this.refresh(); + }, () => {}); this.update(); }; - this.import = (e) => { - e.preventDefault(); - e.stopPropagation(); - let importFile = this.refs.importFile.files[0]; - favoriteListService.importFavoriteLists(importFile).then(() => { + this.import = () => { + let importFile = this.refs.importModal.refs.importFile.files[0]; + return favoriteListService.importFavoriteLists(importFile).then(() => { this.importErrors = {}; - this.refs.importFile.value = ""; - this.refresh(); + this.refs.importModal.refs.importFile.value = ""; + this.update(); }, errors => { this.importErrors = errors; this.bus.trigger("message", errors); diff --git a/pom.xml b/pom.xml index f7b20abc..8a322595 100644 --- a/pom.xml +++ b/pom.xml @@ -173,7 +173,7 @@ <projectId>pollen</projectId> <!-- customized versions --> - <webmotionVersion>2.5.3</webmotionVersion> + <resteasy.version>3.0.17.Final</resteasy.version> <nuitonI18nVersion>3.6.2</nuitonI18nVersion> <eugenePluginVersion>3.0-alpha-10</eugenePluginVersion> @@ -367,22 +367,31 @@ </dependency> <dependency> - <groupId>org.debux.webmotion</groupId> - <artifactId>webmotion</artifactId> - <version>${webmotionVersion}</version> - <exclusions> - <exclusion> - <groupId>javassist</groupId> - <artifactId>javassist</artifactId> - </exclusion> - </exclusions> + <groupId>org.jboss.resteasy</groupId> + <artifactId>resteasy-jaxrs</artifactId> + <version>${resteasy.version}</version> + </dependency> + <dependency> + <groupId>org.jboss.resteasy</groupId> + <artifactId>resteasy-servlet-initializer</artifactId> + <version>${resteasy.version}</version> </dependency> <dependency> - <groupId>org.debux.webmotion</groupId> - <artifactId>webmotion-unittest</artifactId> - <version>${webmotionVersion}</version> - <scope>test</scope> + <groupId>org.jboss.resteasy</groupId> + <artifactId>resteasy-jackson2-provider</artifactId> + <version>${resteasy.version}</version> + </dependency> + <dependency> + <groupId>org.jboss.resteasy</groupId> + <artifactId>resteasy-multipart-provider</artifactId> + <version>${resteasy.version}</version> + </dependency> + + <dependency> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-annotations</artifactId> + <version>2.8.0</version> </dependency> <!-- Nuiton libs --> -- To stop receiving notification emails like this one, please contact chorem.org SCM administrator <admin+scm@chorem.org>.