Commits

Juan Carlos Picado Herrera  committed ec0e434

Error Handlers Improved, json and views
Error i18n

  • Participants
  • Parent commits 6adfe1a

Comments (0)

Files changed (53)

File enme-business/src/main/java/org/encuestame/business/service/PictureService.java

         user.append("/");
         user.append(userAccount.getUid());
         user.append("/");
-        log.debug("getAccountUserPicturePath:{"+user.toString());
+        log.trace("getAccountUserPicturePath:{"+user.toString());
         return user.toString();
     }
 
         url.append(PathUtil.DEFAUL_PICTURE_PREFIX);
         url.append(size.toInt().toString());
         url.append(".jpg");
-        log.debug("getProfileURl "+url);
+        log.trace("getProfileURl "+url);
         final File file = new File(url.toString());
         InputStream is = new FileInputStream(file);
         // Get the size of the file
 
         // Close the input stream and return bytes
         is.close();
-        log.debug("getProfileURl "+bytes);
+        log.trace("getProfileURl "+bytes);
         return bytes;
     }
 

File enme-core/src/main/java/org/encuestame/core/security/SecurityUtils.java

      */
     public static void socialAuthentication(final SocialAccount accountConnection) {
         final UserAccount account = accountConnection.getUserOwner();
-        log.info("Register SOCIAL LOGIN USER: " + account.getUsername());
+        log.trace("Register SOCIAL LOGIN USER: " + account.getUsername());
         // building granted authorities
         final Collection<GrantedAuthority> authorities = ConvertDomainsToSecurityContext
                 .convertEnMePermission(account.getSecUserPermissions());
                 }
             }
         }
-        log.debug("checkIsSessionIsExpired->"+session);
+        log.trace("checkIsSessionIsExpired->"+session);
         return session;
     }
 
             if (EnMeUtils.ANONYMOUS_USER.equals(authentication.getName())) {
                 anonymous = true;
             }
-            log.debug("checkIsSessionIsExpired->"+anonymous);
+            log.trace("checkIsSessionIsExpired->"+anonymous);
         }
         return anonymous;
     }

File enme-core/src/main/java/org/encuestame/core/service/AbstractDataSource.java

      * @throws EnMeNoResultsFoundException exception
      */
     public final UserAccount getUserAccount(final String username) throws EnMeNoResultsFoundException {
-    	log.debug("getUserAccount username:: "+username);
+        log.debug("getUserAccount username:: "+username);
         final UserAccount userAccount =  this.findUserByUserName(username);
         if (userAccount == null) {
-        	log.info(" user not found {"+username+"}");
+            log.info(" user not found {"+username+"}");
             throw new EnMeNoResultsFoundException(" user not found {"+username+"}");
         } else {
             //TODO: we can add others validations, like is disabled, banned or the account is expired.
      * @return {@link UserAccount}
      */
     public UserAccount findUserByUserName(final String username) {
-    	log.debug("findUserByUserName username: "+username);
+        log.trace("findUserByUserName username: "+username);
         return getAccountDao().getUserByUsername(username);
     }
 

File enme-core/src/main/resources/org/encuestame/core/config/encuestame-config.properties

 # if false use the compressed static files if not, development status is enabled and
 # use uncompressed static files, useful to development
 encuestame.development = false
+
+#-----------------------------------------------------------------------------
+# Error level, display a different size of error on depends the error level
+# 0 - None
+# 1 - Medium
+# 2 - High
 #-----------------------------------------------------------------------------
+encuestame.error.level = 0
+encuestame.error.display_bugtracking = false
 
 #-----------------------------------------------------------------------------
 # Required configuration settings

File enme-mvc/src/main/java/org/encuestame/mvc/controller/AbstractJsonController.java

  */
 package org.encuestame.mvc.controller;
 
-import java.util.ArrayList;
-import java.util.Collections;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
 import java.util.StringTokenizer;
 
 import org.encuestame.core.util.EnMeUtils;
 import org.encuestame.persistence.dao.INotification;
 import org.encuestame.persistence.dao.imp.NotificationDao;
+import org.encuestame.persistence.exception.EnMeExpcetion;
 import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
 import org.encuestame.utils.web.UserAccountBean;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
 import org.springframework.security.access.AccessDeniedException;
-import org.springframework.security.acls.model.NotFoundException;
 import org.springframework.ui.ModelMap;
 import org.springframework.util.Assert;
-import org.springframework.validation.FieldError;
-import org.springframework.validation.ObjectError;
-import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.ServletRequestBindingException;
+import org.springframework.web.bind.annotation.ControllerAdvice;
 import org.springframework.web.bind.annotation.ExceptionHandler;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.bind.annotation.ResponseStatus;
 import org.springframework.web.servlet.ModelAndView;
 import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
  * Abstract Json Controller.
  * @author Picado, Juan juanATencuestame.org
  * @since Sep 15, 2010 11:31:20 AM
- * @version $Id:$
  */
+@ControllerAdvice
 public abstract class AbstractJsonController extends AbstractBaseOperations{
 
     /**
     @Autowired
     private INotification notificationDao;
 
-    /**
-     * Domain.
-     */
-    // @Value("${application.domain}") private String appDomainSetted;
-
-     /**
-      * Tweet Path Vote.
-      */
-    // @Value("${answers.tweetPathVote}") private String tweetPathVote;
-
     /** Success. **/
     private Map<String, Object> sucess = new HashMap<String, Object>();
 
-    /** Error Json. **/
+    /** Error JSON. **/
     private Map<String, Object> error = new HashMap<String, Object>();
 
     /**
+     * This is a successful message, when a services got nothing to answer.
+     */
+    private final Integer SUCCESS_RESPONSE = 0;
+
+    /**
+     * This error means a negative response, it's used when the something happends wrong.
+     */
+    private final Integer ERROR_RESPONSE = -1;
+
+    /**
      * Return Data.
      * @return
      */
-    protected ModelMap returnData(){
+    protected ModelMap returnData() {
          Map<String, Object> response = new HashMap<String, Object>();
          Assert.notNull(this.sucess);
          Assert.notNull(this.error);
      */
     protected void setSuccesResponse() {
         final Map<String, Object> response = new HashMap<String, Object>();
-        response.put("r", 0);
+        response.put("r", this.SUCCESS_RESPONSE);
         setItemResponse(response);
     }
 
      */
     protected void setSuccesResponse(final String message) {
         final Map<String, Object> response = new HashMap<String, Object>();
-        response.put("r", 0);
+        response.put("r", this.SUCCESS_RESPONSE);
         response.put("message", message == null ? "" : message);
         setItemResponse(response);
     }
     /**
      * Set a failed response.
      */
-    protected void setFailedResponse(){
+    protected void setFailedResponse() {
         final Map<String, Object> response = new HashMap<String, Object>();
-        response.put("r", -1);
+        response.put("r", this.ERROR_RESPONSE);
         setItemResponse(response);
     }
 
      * @param ex exception
      * @return {@link ModelAndView}.
      */
+    @SuppressWarnings("static-access")
     @ResponseStatus(value = HttpStatus.FORBIDDEN)
     @ExceptionHandler(AccessDeniedException.class)
-    public ModelAndView handleException (final AccessDeniedException ex, HttpServletResponse httpResponse) {
-      log.error("handleException "+ ex.getMessage());
-      httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
+    public ModelAndView handleException (final AccessDeniedException ex, HttpServletResponse httpResponse,
+            final HttpServletRequest request) {
       ModelAndView mav = new ModelAndView();
-      mav.setViewName("MappingJacksonJsonView");
+      mav.setViewName("jsonView");
       final Map<String, Object> response = new HashMap<String, Object>();
       response.put("message", ex.getMessage());
-      //TODO: add internationalitazion
-      response.put("description", "Application does not have permission for this action");
+      response.put("description", getMessage("error.access.denied", request, null));
       response.put("status", httpResponse.SC_FORBIDDEN);
       response.put("session", SecurityUtils.checkIsSessionIsExpired(getSecCtx().getAuthentication()));
       response.put(EnMeUtils.ANONYMOUS_USER, SecurityUtils.checkIsSessionIsAnonymousUser(getSecCtx().getAuthentication()));
+      httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
       mav.addObject("error",  response);
       return mav;
     }
 
-//    @ExceptionHandler(NoSuchRequestHandlingMethodException.class)
-//    public ModelAndView handleException (NoSuchRequestHandlingMethodException ex) {
-//      ModelAndView mav = new ModelAndView();
-//      log.error("Exception found: " + ex);
-//      mav.setViewName("404");
-//      return mav;
-//    }
-
-//    public class BadStatus {
-//        String errorMessage;
-//        boolean status = false;
-//
-//        public BadStatus(String msg) { errorMessage = msg; }
-//    }
-
-//    @ExceptionHandler(Exception.class)
-//    public BadStatus handleException(Exception ex, HttpServletRequest request) {
-//      return new BadStatus(ex.getMessage());
-//    }
-//
-//    @ExceptionHandler
-//    @ResponseStatus(value = HttpStatus.NOT_FOUND)
-//    public ModelAndView notFoundHandler(NotFoundException e){
-//        ModelAndView mav = new ModelAndView();
-//        mav.setViewName("MappingJacksonJsonView");
-//        final Map<String, Object> response = new HashMap<String, Object>();
-//        response.put("message", e.getMessage());
-//        //TODO: add internationalitazion
-//        mav.addObject("error",  response);
-//        return mav;
-//    }
+    /**
+     * Customized error for {@link NoSuchRequestHandlingMethodException}.
+     * @param ex {@link NoSuchRequestHandlingMethodException}.
+     * @return {@link ResponseEntity}
+     */
+    @ExceptionHandler(NoSuchRequestHandlingMethodException.class)
+    public ResponseEntity<String> handleNoSuchRequestHandlingMethodException(NoSuchRequestHandlingMethodException ex)   {
+       return this.errorManage(ex);
+    }
+
+
+    /**
+     * Build a JSON error response based on the Exception message.
+     * @param ex {@link Exception}
+     * @return {@link ResponseEntity}
+     */
+    private ResponseEntity<String> errorManage(Exception ex) {
+        ex.printStackTrace();
+        log.debug("ServletRequestBindingException" + ex.getMessage());
+        HttpHeaders headers = new HttpHeaders();
+        headers.add("Content-Type", "application/json");
+        final String text_error = ex.getMessage().replace("'", "");
+        final String error = "{error : '" + text_error + "', success : null}";
+        return new ResponseEntity<String>(error, headers, HttpStatus.BAD_REQUEST);
+    }
+
+    /**
+     * Customized error for {@link ServletRequestBindingException}.
+     * @param ex {@link ServletRequestBindingException}
+     * @return {@link ResponseEntity}
+     */
+    @ExceptionHandler(ServletRequestBindingException.class)
+    public ResponseEntity<String> handleServletRequestBindingException(ServletRequestBindingException ex)   {
+        return this.errorManage(ex);
+    }
+
+    /**
+     * Customized error for {@link EnMeExpcetion}.
+     * @param ex {@link EnMeExpcetion}
+     * @return {@link ResponseEntity}
+     */
+    @ExceptionHandler(EnMeExpcetion.class)
+    public ResponseEntity<String> handleEnMeExpcetion(EnMeExpcetion ex)   {
+        return this.errorManage(ex);
+    }
+
 
     /**
-     * Get Url Domain.
+     * Get URL Domain.
      * @param request
      * @param realDomain
      * @return
         final StringBuilder builder = new StringBuilder();
         if(realDomain){
             String header = request.getHeader("X-Forwarded-Host");
-            log.debug("Host header  "+header);
-            if(header != null) {
+            log.trace("Host header  "+header);
+            if (header != null) {
                     // we are only interested in the first header entry
                     header = new StringTokenizer(header,",").nextToken().trim();
             }
-            if(header == null) {
+            if (header == null) {
                     header = request.getHeader("Host");
             }
             builder.append(header);
-            log.debug("Host "+builder.toString());
+            log.trace("Host "+builder.toString());
         } else {
             builder.append("/");
         }
      * @param label
      * @param object
      */
-    public void setSingleResponse(final String label, Object object){
+    public void setSingleResponse(final String label, Object object) {
         final Map<String, Object> jsonResponse = new HashMap<String, Object>();
         jsonResponse.put(label, object);
         setItemResponse(jsonResponse);

File enme-mvc/src/main/java/org/encuestame/mvc/controller/AbstractViewController.java

+package org.encuestame.mvc.controller;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.lang.exception.ExceptionUtils;
+import org.apache.log4j.Logger;
+import org.encuestame.core.config.EnMePlaceHolderConfigurer;
+import org.encuestame.core.security.SecurityUtils;
+import org.encuestame.core.util.EnMeUtils;
+import org.encuestame.persistence.exception.EnMeExpcetion;
+import org.encuestame.utils.web.frontEnd.WebMessage;
+import org.encuestame.utils.web.frontEnd.WebMessage.WebInfoType;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.web.bind.ServletRequestBindingException;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.ResponseStatus;
+import org.springframework.web.servlet.ModelAndView;
+import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
+
+/**
+ * Collection of utilities for Controller Views, Error Handlers only for Controller.
+ * @author Picado, Juan juanATencuestame.org
+ * @since Feb 08, 2013 06:31:20 AM
+ */
+@ControllerAdvice
+public abstract class AbstractViewController extends AbstractBaseOperations{
+
+    /**
+    *
+    */
+   @Value("${encuestame.error.level}") protected Integer errorLevel;
+
+   /**
+    *
+    */
+   @Value("${encuestame.error.display_bugtracking}") protected Boolean bugTracking;
+
+
+     /**
+     * Log.
+     */
+    private Logger log = Logger.getLogger(this.getClass());
+
+    /**
+     * Customized error for {@link NoSuchRequestHandlingMethodException}.
+     * @param ex {@link NoSuchRequestHandlingMethodException}.
+     * @return {@link ResponseEntity}
+     */
+    @ExceptionHandler(NoSuchRequestHandlingMethodException.class)
+    public ResponseEntity<String> handleNoSuchRequestHandlingMethodException(NoSuchRequestHandlingMethodException ex)   {
+       return this.errorManage(ex);
+    }
+
+
+    /**
+     * Build a JSON error response based on the Exception message.
+     * @param ex {@link Exception}
+     * @return {@link ResponseEntity}
+     */
+    private ResponseEntity<String> errorManage(Exception ex) {
+        ex.printStackTrace();
+        log.debug("ServletRequestBindingException" + ex.getMessage());
+        HttpHeaders headers = new HttpHeaders();
+        headers.add("Content-Type", "application/json");
+        final String text_error = ex.getMessage().replace("'", "");
+        final String error = "{error : '" + text_error + "', success : null}";
+        return new ResponseEntity<String>(error, headers, HttpStatus.BAD_REQUEST);
+    }
+
+    /**
+     * Customized error for {@link ServletRequestBindingException}.
+     * @param ex {@link ServletRequestBindingException}
+     * @return {@link ResponseEntity}
+     */
+    @ExceptionHandler(ServletRequestBindingException.class)
+    public ResponseEntity<String> handleServletRequestBindingException(ServletRequestBindingException ex)   {
+        return this.errorManage(ex);
+    }
+
+    /**
+     * Handler for {@link AccessDeniedException}
+     * @param ex exception
+     * @return {@link ModelAndView}.
+     */
+    @SuppressWarnings("static-access")
+    @ResponseStatus(value = HttpStatus.FORBIDDEN)
+    @ExceptionHandler(AccessDeniedException.class)
+    public ModelAndView handleException (final AccessDeniedException ex, HttpServletResponse httpResponse,
+            HttpServletRequest request) {
+       ModelAndView mav = new ModelAndView();
+       mav.setViewName("tilesResolver");
+       mav.setViewName("error/denied");
+      final Map<String, Object> response = new HashMap<String, Object>();
+      response.put("status", httpResponse.SC_FORBIDDEN);
+      response.put("session", SecurityUtils.checkIsSessionIsExpired(getSecCtx().getAuthentication()));
+      response.put(EnMeUtils.ANONYMOUS_USER, SecurityUtils.checkIsSessionIsAnonymousUser(getSecCtx().getAuthentication()));
+      httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
+      mav.addObject("error",  response);
+      return mav;
+    }
+
+    /**
+     *
+     * @param ex
+     * @param request
+     * @return
+     */
+    @ExceptionHandler
+    @ResponseStatus(HttpStatus.BAD_REQUEST)
+    @ResponseBody
+    ModelAndView handleException(EnMeExpcetion ex, HttpServletRequest request) {
+        ModelAndView mav = new ModelAndView();
+        mav.setViewName("tilesResolver");
+        mav.setViewName("error");
+        WebMessage emptyError = new WebMessage(WebInfoType.ERROR, ex.getMessage(), ExceptionUtils.getFullStackTrace(ex),
+                EnMePlaceHolderConfigurer.getIntegerProperty("encuestame.error.level"),
+                EnMePlaceHolderConfigurer.getBooleanProperty("encuestame.error.display_bugtracking"));
+        request.setAttribute("message", emptyError);
+        return mav;
+    }
+}

File enme-mvc/src/main/java/org/encuestame/mvc/controller/AdmonController.java

-/*
- ************************************************************************************
- * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
- * encuestame Development Team.
- * Licensed under the Apache Software License version 2.0
- * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to  in writing,  software  distributed
- * under the License is distributed  on  an  "AS IS"  BASIS,  WITHOUT  WARRANTIES  OR
- * CONDITIONS OF ANY KIND, either  express  or  implied.  See  the  License  for  the
- * specific language governing permissions and limitations under the License.
- ************************************************************************************
- */
-
-package org.encuestame.mvc.controller;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.springframework.security.access.prepost.PreAuthorize;
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.ModelMap;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-
-/**
- * Admon View Controller.
- * @author Picado, Juan juanATencuestame.org
- * @since Mar 6, 2010 10:58:02 AM
- * @version $Id: $
- */
-
-@Controller
-public class AdmonController extends AbstractBaseOperations {
-
-    private Log log = LogFactory.getLog(this.getClass());
-
-    /**
-     * Tweet Poll Controller.
-     * @param model model
-     * @param id id tweet
-     * @return template
-     */
-    @PreAuthorize("hasRole('ENCUESTAME_OWNER')")
-    @RequestMapping(value = "/admon/location", method = RequestMethod.GET)
-    public String admonLocation(ModelMap model) {
-        log.debug("LOCATION");
-        return "location";
-    }
-
-    /**
-     *
-     * @param model
-     * @return
-     */
-    @PreAuthorize("hasRole('ENCUESTAME_OWNER')")
-    @RequestMapping(value = "/admon/members", method = RequestMethod.GET)
-    public String membersLocation(ModelMap model) {
-        log.debug("MEMBERS");
-        addi18nProperty(model, "admon_create_user", getMessage("admon_create_user"));
-        addi18nProperty(model, "admon_username", getMessage("admon_username"));
-        addi18nProperty(model, "admon_group", getMessage("admon_group"));
-        addi18nProperty(model, "admon_user_from", getMessage("admon_user_from"));
-        addi18nProperty(model, "admon_status", getMessage("admon_status"));
-        addi18nProperty(model, "admon_tweetpoll_count", getMessage("admon_tweetpoll_count"));
-        addi18nProperty(model, "admon_poll_count", getMessage("admon_poll_count"));
-        addi18nProperty(model, "admon_survey_count", getMessage("admon_survey_count"));
-        addi18nProperty(model, "admon_last_logged", getMessage("admon_last_logged"));
-        addi18nProperty(model, "followers", getMessage("followers"));
-        return "members";
-    }
-
-    /**
-     *
-     * @param model
-     * @return
-     */
-    @PreAuthorize("hasRole('ENCUESTAME_OWNER')")
-    @RequestMapping(value = "/admon/project", method = RequestMethod.GET)
-    public String admonProject(ModelMap model) {
-        log.debug("PROJECT");
-        return "project";
-    }
-}

File enme-mvc/src/main/java/org/encuestame/mvc/controller/DashBoardController.java

-/*
- ************************************************************************************
- * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
- * encuestame Development Team.
- * Licensed under the Apache Software License version 2.0
- * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to  in writing,  software  distributed
- * under the License is distributed  on  an  "AS IS"  BASIS,  WITHOUT  WARRANTIES  OR
- * CONDITIONS OF ANY KIND, either  express  or  implied.  See  the  License  for  the
- * specific language governing permissions and limitations under the License.
- ************************************************************************************
- */
-
-package org.encuestame.mvc.controller;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.encuestame.persistence.domain.security.UserAccount;
-import org.springframework.security.access.prepost.PreAuthorize;
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.ModelMap;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-
-/**
- * DashBoard Controller.
- * @author Picado, Juan juanATencuestame.org
- * @since Mar 6, 2010 10:58:02 AM
- */
-
-@Controller
-public class DashBoardController extends AbstractBaseOperations {
-
-    private Log log = LogFactory.getLog(this.getClass());
-
-    /**
-     * DashBoard Controller.
-     * @param model model
-     * @return template
-     */
-    @PreAuthorize("hasRole('ENCUESTAME_USER')")
-    @RequestMapping(value = "/user/dashboard", method = RequestMethod.GET)
-    public String dashBoardController(ModelMap model, UserAccount account) {
-        log.debug("dashboard");
-        return "dashboard";
-    }
-}

File enme-mvc/src/main/java/org/encuestame/mvc/controller/ErrorController.java

-/*
- ************************************************************************************
- * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
- * encuestame Development Team.
- * Licensed under the Apache Software License version 2.0
- * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to  in writing,  software  distributed
- * under the License is distributed  on  an  "AS IS"  BASIS,  WITHOUT  WARRANTIES  OR
- * CONDITIONS OF ANY KIND, either  express  or  implied.  See  the  License  for  the
- * specific language governing permissions and limitations under the License.
- ************************************************************************************
- */
-
-package org.encuestame.mvc.controller;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.ModelMap;
-import org.springframework.web.bind.annotation.RequestMapping;
-
-/**
- * Error Controller
- * @author Picado, Juan juanATencuestame.org
- * @since Mar 11, 2010 9:21:37 PM
- * @version $Id: $
- */
-@Controller
-public class ErrorController  extends AbstractBaseOperations {
-
-    private Log log = LogFactory.getLog(this.getClass());
-
-    /**
-     *
-     * @param model
-     * @return
-     */
-    @RequestMapping("/error")
-    public String errorController(final ModelMap model, final HttpServletRequest request, final HttpServletResponse  response) {
-        // if the error message is missing, nothing to display, it's redirected to home
-        if (request.getAttribute("message") == null) {
-             log.error("*********************************************************************************************");
-             log.error("*********************************************************************************************");
-             log.error("*********************************************************************************************");
-             log.error("*********************************************************************************************");
-             log.error("redirect to home no error message, redirect to home");
-             log.error("*********************************************************************************************");
-             log.error("*********************************************************************************************");
-             log.error("*********************************************************************************************");
-             log.error("*********************************************************************************************");
-             return "redirect:/home";
-        } else {
-            log.error("*********************************************************************************************");
-                log.error("*********************************************************************************************");
-                log.error("*********************************************************************************************");
-                log.error("*********************************************************************************************");
-            log.error("error no error message, redirect to home");
-            log.error("*********************************************************************************************");
-            log.error("*********************************************************************************************");
-            log.error("*********************************************************************************************");
-            log.error("*********************************************************************************************");
-            return "error";
-        }
-    }
-
-    /**
-     * Display a user denied view, used by spring security, see the main configuration.
-     * @param model
-     * @return
-     */
-    @RequestMapping("/user/denied")
-    public String errorDeniedController(final ModelMap model) {
-        return "error/denied";
-    }
-
-
-}

File enme-mvc/src/main/java/org/encuestame/mvc/controller/FileUploadController.java

-/*
- ************************************************************************************
- * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
- * encuestame Development Team.
- * Licensed under the Apache Software License version 2.0
- * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to  in writing,  software  distributed
- * under the License is distributed  on  an  "AS IS"  BASIS,  WITHOUT  WARRANTIES  OR
- * CONDITIONS OF ANY KIND, either  express  or  implied.  See  the  License  for  the
- * specific language governing permissions and limitations under the License.
- ************************************************************************************
- */
-package org.encuestame.mvc.controller;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.log4j.Logger;
-import org.encuestame.core.files.PathUtil;
-import org.encuestame.core.image.ThumbnailGeneratorEngine;
-import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
-import org.encuestame.persistence.exception.EnmeFailOperation;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.access.prepost.PreAuthorize;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.multipart.MultipartFile;
-import org.springframework.web.servlet.ModelAndView;
-import org.springframework.web.servlet.view.json.MappingJacksonJsonView;
-
-/**
- * Upload File Controller.
- * @author Picado, Juan juanATencuestame.org
- * @since Jan 16, 2011 11:47:33 AM
- * @version $Id:$
- */
-@Controller
-public class FileUploadController extends AbstractBaseOperations {
-
-    /**
-     * Log.
-     */
-    private Logger log = Logger.getLogger(this.getClass());
-
-    /**
-     * {@link ThumbnailGeneratorEngine}.
-     */
-    @Autowired
-    private ThumbnailGeneratorEngine thumbnailGeneratorEngine;
-
-    /**
-     * Upload Profile for User Account.
-     * @param multipartFile
-     * @return
-     */
-    @PreAuthorize("hasRole('ENCUESTAME_USER')")
-    @RequestMapping(value = "/file/upload/profile", method = RequestMethod.POST)
-    public ModelAndView handleUserProfileFileUpload(
-            @RequestParam("file") MultipartFile multipartFile) {
-        ModelAndView mav = new ModelAndView(new MappingJacksonJsonView());
-        if (!multipartFile.isEmpty()) {
-            log.debug(multipartFile.getName());
-            String orgName = multipartFile.getOriginalFilename();
-            log.debug("org name "+orgName);
-            //TODO: convert name to numbers, MD5 hash.
-            String filePath = null;
-            try {
-                log.debug("getting file path for this user");
-                filePath = getPictureService().getAccountUserPicturePath(getSecurityService().getUserAccount(getUserPrincipalUsername()));
-                InputStream stream = multipartFile.getInputStream();
-                try {
-                    //generate thumbnails
-                    thumbnailGeneratorEngine.generateThumbnails(
-                            PathUtil.DEFAUL_PICTURE_PREFIX,
-                            stream,
-                            multipartFile.getContentType(),
-                            filePath);
-                } catch (Exception e) {
-                    log.error(e);
-                } finally {
-                    stream.close();
-                }
-                //TODO: after save image, we need relationship user with profile picture.
-                //I suggest store ID on user account table, to retrieve easily future profile image.
-                //BUG 102
-            } catch (IllegalStateException e) {
-                log.error("File uploaded failed:" + orgName);
-            } catch (IOException e) {
-                log.error("File uploaded failed:" + orgName);
-            } catch (EnMeNoResultsFoundException e) {
-                log.error("File uploaded failed:" + orgName);
-            } catch (EnmeFailOperation e) {
-                log.error("File uploaded failed:" + orgName);
-            }
-            // Save the file here
-            mav.addObject("status", "saved");
-            mav.addObject("id", filePath);
-        } else {
-            mav.addObject("status", "failed");
-        }
-        return mav;
-    }
-
-    /**
-     * @return the thumbnailGeneratorEngine
-     */
-    public ThumbnailGeneratorEngine getThumbnailGeneratorEngine() {
-        return thumbnailGeneratorEngine;
-    }
-
-    /**
-     * @param thumbnailGeneratorEngine the thumbnailGeneratorEngine to set
-     */
-    public void setThumbnailGeneratorEngine(
-            ThumbnailGeneratorEngine thumbnailGeneratorEngine) {
-        this.thumbnailGeneratorEngine = thumbnailGeneratorEngine;
-    }
-
-
-
-    /**  TODO: we can add more methods to upload different types of files. **/
-}

File enme-mvc/src/main/java/org/encuestame/mvc/controller/GlobalExceptionHandler.java

-package org.encuestame.mvc.controller;
-
-import org.springframework.web.bind.annotation.ControllerAdvice;
-import org.springframework.web.bind.annotation.ExceptionHandler;
-import org.springframework.web.bind.annotation.ResponseBody;
-
-//@ControllerAdvice
-public class GlobalExceptionHandler {
-
-    @ExceptionHandler
-    public @ResponseBody String handleBusinessException(Exception ex) {
-        System.out.print(ex);
-        ex.printStackTrace();
-        return "Handled BusinessException";
-    }
-
-}

File enme-mvc/src/main/java/org/encuestame/mvc/controller/HashTagController.java

-/*
- ************************************************************************************
- * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
- * encuestame Development Team.
- * Licensed under the Apache Software License version 2.0
- * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to  in writing,  software  distributed
- * under the License is distributed  on  an  "AS IS"  BASIS,  WITHOUT  WARRANTIES  OR
- * CONDITIONS OF ANY KIND, either  express  or  implied.  See  the  License  for  the
- * specific language governing permissions and limitations under the License.
- ************************************************************************************
- */
-package org.encuestame.mvc.controller;
-
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.encuestame.core.service.imp.IFrontEndService;
-import org.encuestame.core.util.ConvertDomainBean;
-import org.encuestame.persistence.domain.HashTag;
-import org.encuestame.persistence.exception.EnmeFailOperation;
-import org.encuestame.utils.enums.HitCategory;
-import org.encuestame.utils.enums.TypeSearchResult;
-import org.encuestame.utils.json.HomeBean;
-import org.encuestame.utils.web.HashTagBean;
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.ModelMap;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-
-/**
- * HashTag Controller.
- *
- * @author Morales, Diana Paola paolaATencuestame.org
- * @since Apr 15, 2011
- */
-@Controller
-public class HashTagController extends AbstractBaseOperations {
-
-    /** Log. **/
-    private Log log = LogFactory.getLog(this.getClass());
-
-    /** HashTag max results. **/
-    private final Integer MAX_HASHTAG = 80;
-
-    /** HashTag max results. **/
-    private final Integer LIMIT_HASHTAG = 15;
-
-    /** INIT_RESULTS **/
-    private final Integer INIT_RESULTS = 0;
-
-    /**
-     * HashTag List.
-     *
-     * @param model
-     * @param request
-     * @param response
-     * @return
-     */
-    @RequestMapping(value = "/cloud", method = RequestMethod.GET)
-    public String hashTagController(ModelMap model, HttpServletRequest request,
-            HttpServletResponse response) {
-        final IFrontEndService service = getFrontService();
-        final List<HashTagBean> hashTagList = service.getHashTags(MAX_HASHTAG,
-                0, "hashTagsCloud"); // TODO: Add to file properties number 20
-        model.addAttribute("hashtags", hashTagList);
-        return "cloud";
-    }
-
-    /**
-     * HashTag detail
-     *
-     * @param model
-     * @param request
-     * @param response
-     * @param name
-     * @return
-     * @throws EnmeFailOperation
-     */
-    @RequestMapping(value = "/tag/{name}", method = RequestMethod.GET)
-    public String tagController(ModelMap model, HttpServletRequest request,
-            HttpServletResponse response, @PathVariable String name) {
-        name = filterValue(name);
-
-        final HashTag tag;
-        try {
-
-            tag = getFrontService().getHashTagItem(name);
-            if (tag == null) {
-                return "404";
-            } else {
-                try {
-                     log.debug("tagController tag =>"+tag);
-                     final String IP = getIpClient(request);
-                     boolean hashTagVisite = getFrontService().checkPreviousHit(IP, tag.getHashTagId(), TypeSearchResult.HASHTAG);
-                     // TODO: Check that previous hash Tag hit has been visited the same day.
-                     log.debug("hashTagVisite =>"+hashTagVisite);
-                     if (!hashTagVisite) {
-                         getFrontService().registerHit(null, null, null, tag, IP, HitCategory.VISIT);
-                     }
-                } catch (Exception e) {
-                    log.warn("Imposible register vote " + "tag id: " + tag.getHashTagId());
-                }
-                final List<HomeBean> lastPublications = getFrontService()
-                        .searchLastPublicationsbyHashTag(tag, null, this.INIT_RESULTS,
-                                LIMIT_HASHTAG, "hashtag", request);
-                log.debug("tagController tweetPollbyTags =>"+lastPublications.size());
-                log.debug("tagController tag =>"+tag);
-                final HashTagBean bean =  ConvertDomainBean.convertHashTagDomain(tag);
-                model.addAttribute("tagName", bean);
-                model.addAttribute("tweetPolls", lastPublications);
-            }
-        } catch (Exception e) {
-            e.printStackTrace();
-            log.error(e);
-            return "404";
-        }
-        return "tag/detail";
-    }
-}

File enme-mvc/src/main/java/org/encuestame/mvc/controller/HomeController.java

-/*
- ************************************************************************************
- * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
- * encuestame Development Team.
- * Licensed under the Apache Software License version 2.0
- * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to  in writing,  software  distributed
- * under the License is distributed  on  an  "AS IS"  BASIS,  WITHOUT  WARRANTIES  OR
- * CONDITIONS OF ANY KIND, either  express  or  implied.  See  the  License  for  the
- * specific language governing permissions and limitations under the License.
- ************************************************************************************
- */
-
-package org.encuestame.mvc.controller;
-
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.collections.ListUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.encuestame.core.config.EnMePlaceHolderConfigurer;
-import org.encuestame.core.service.imp.IFrontEndService;
-import org.encuestame.core.util.ConvertDomainBean;
-import org.encuestame.core.util.EnMeUtils;
-import org.encuestame.persistence.domain.security.UserAccount;
-import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
-import org.encuestame.persistence.exception.EnMeSearchException;
-import org.encuestame.utils.json.HomeBean;
-import org.encuestame.utils.web.UserAccountBean;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.Model;
-import org.springframework.ui.ModelMap;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-
-/**
- * Home or FrontEnd Controller.
- * @author Picado, Juan juanATencuestame.org
- * @since Mar 6, 2010 10:58:02 AM
- */
-@Controller
-public class HomeController extends AbstractBaseOperations {
-
-   /**
-    * Log.
-    */
-    private Log log = LogFactory.getLog(this.getClass());
-
-    /**
-     * Default max of home beans to display.
-     */
-    @Value("${front.home.items}") private Integer homeMaxItems;
-
-    /**
-     * Default max of hashtag to display.
-     */
-    @Value("${front.hashtags.items}") private Integer homeHashtagMaxItems;
-
-    /**
-     *
-     */
-    @Value("${front.profile.items}") private Integer profileDefaultItems;
-
-    /**
-     * Default date range.
-     */
-    private final String SHOW_ALL_RESULTS = "all";
-
-   /**
-    * Home Controller.
-    * @param model model
-    * @return template
-    */
-    @RequestMapping(value = "/home", method = RequestMethod.GET)
-    public String homeController(ModelMap model, HttpServletRequest request,
-            HttpServletResponse response) {
-        final Boolean privateHome = EnMePlaceHolderConfigurer
-                .getBooleanProperty("application.private");
-        addi18nProperty(model, "home_item_comments");
-        addi18nProperty(model, "submited_by");
-        addi18nProperty(model, "home_item_votes");
-        addi18nProperty(model, "home_item_views");
-        addi18nProperty(model, "added");
-        if (privateHome) {
-            log.debug("signup is disabled");
-            return "redirect:/user/signin";
-        } else {
-            final String view = filterValue(request.getParameter("view"));
-            String period = filterValue(request.getParameter("period"));
-            period = (period.isEmpty() ? SHOW_ALL_RESULTS : period);
-            final IFrontEndService service = getFrontService();
-            try {
-                if (view.isEmpty()) {
-                    model.addAttribute("items", service.getFrontEndItems(period, EnMeUtils.DEFAULT_START , this.homeMaxItems, request));
-                } else {
-                    if ("tweetpoll".equals(view)) {
-                        model.addAttribute("items", ConvertDomainBean
-                                .convertTweetPollListToHomeBean(service
-                                        .searchItemsByTweetPoll(period, EnMeUtils.DEFAULT_START,
-                                                this.homeMaxItems, request)));
-                    } else if ("poll".equals(view)) {
-                        model.addAttribute("items",
-                                ConvertDomainBean
-                                        .convertPollListToHomeBean(service
-                                                .searchItemsByPoll(period, EnMeUtils.DEFAULT_START,
-                                                        this.homeMaxItems)));
-                    } else if ("survey".equals(view)) {
-                        //TODO: ENCUESTAME-345
-                        model.addAttribute("items", ListUtils.EMPTY_LIST);
-                    } else {
-                        model.addAttribute("items", service
-                                .searchItemsByTweetPoll(period, EnMeUtils.DEFAULT_START, this.homeMaxItems,
-                                        request));
-                    }
-                }
-                //TODO: review this code, is used?
-                model.addAttribute("hashTags", service.getHashTags(this.homeHashtagMaxItems, EnMeUtils.DEFAULT_START, ""));
-                //TODO: search hashtags and other information.
-                //TODO: comments: ENCUESTAME-346
-            } catch (EnMeSearchException e) {
-                log.error(e);
-                return "error";
-            }
-            return "home";
-        }
-    }
-
-    /**
-    * Index view.
-    * @param model
-    * @param request
-    * @param response
-    * @return
-    */
-    @RequestMapping(value = "/", method = RequestMethod.GET)
-    public String index(ModelMap model, HttpServletRequest request,
-            HttpServletResponse response) {
-        return "redirect:/home";
-    }
-
-    /**
-     * Help View.
-     * @param model model
-     * @return template
-     */
-    @RequestMapping(value = "/user/help", method = RequestMethod.GET)
-    public String dashBoardController(ModelMap model, UserAccount account) {
-        return "user/help";
-    }
-
-    /**
-     * Display a question view.
-     * @param model {@link Model}
-     * @param id the question id
-     * @param slug the slug question name
-     * @param request {@link HttpServletRequest}
-     * @param response {@link HttpServletResponse}
-     * @return the tile view
-     */
-    @RequestMapping(value = "/question/detail/{id}/{slug}", method = RequestMethod.GET)
-    public String questionController(
-            final ModelMap model,
-            @PathVariable String id,
-            @PathVariable String slug,
-            HttpServletRequest request,
-            HttpServletResponse response) {
-
-
-            return "question/detail";
-    }
-
-    /**
-     * Display the user profile.
-     * @param model
-     * @param username
-     * @return
-     */
-    @RequestMapping(value = "/profile/{username}", method = RequestMethod.GET)
-    public String userProfileController(
-            final ModelMap model,
-            @PathVariable String username,
-            HttpServletRequest request,
-            HttpServletResponse response) {
-        username = filterValue(username);
-        try {
-        final UserAccountBean accountBean = getSecurityService().searchUserByUsername(username);
-            if (accountBean == null) {
-                return "404";
-            } else {
-                //1 - load all items poll / survey / poll for {username} order by date
-                //2 - hashtag created by {username}
-                //3 - social link published by {username}
-                //4 - last comments
-                log.debug("user --> "+accountBean);
-                model.put("profile", accountBean);
-                final List<HomeBean> lastItems = getFrontService().getLastItemsPublishedFromUserAccount(username, this.profileDefaultItems, false,
-                                     request);
-                model.put("lastItems", lastItems);
-                return "profile/view";
-            }
-        } catch (EnMeNoResultsFoundException e) {
-             e.printStackTrace();
-             log.error(e);
-            return "500";
-        }
-    }
-
-    /**
-     * @param profileDefaultItems the profileDefaultItems to set
-     */
-    public void setProfileDefaultItems(final Integer profileDefaultItems) {
-        this.profileDefaultItems = profileDefaultItems;
-    }
-
-    /**
-     * @param homeMaxItems the homeMaxItems to set
-     */
-    public void setHomeMaxItems(final Integer homeMaxItems) {
-        this.homeMaxItems = homeMaxItems;
-    }
-
-    /**
-     * @param homeHashtagMaxItems the homeHashtagMaxItems to set
-     */
-    public void setHomeHashtagMaxItems(final Integer homeHashtagMaxItems) {
-        this.homeHashtagMaxItems = homeHashtagMaxItems;
-    }
-}

File enme-mvc/src/main/java/org/encuestame/mvc/controller/NotificationController.java

-/*
- ************************************************************************************
- * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
- * encuestame Development Team.
- * Licensed under the Apache Software License version 2.0
- * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to  in writing,  software  distributed
- * under the License is distributed  on  an  "AS IS"  BASIS,  WITHOUT  WARRANTIES  OR
- * CONDITIONS OF ANY KIND, either  express  or  implied.  See  the  License  for  the
- * specific language governing permissions and limitations under the License.
- ************************************************************************************
- */
-package org.encuestame.mvc.controller;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.springframework.security.access.prepost.PreAuthorize;
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.ModelMap;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-
-/**
- * Notifications Controller.
- * @author Picado, Juan juanATencuestame.org
- * @since Jun 27, 2011
- */
-@Controller
-public class NotificationController extends AbstractBaseOperations{
-
-    /**
-        * Log.
-        */
-        private Log log = LogFactory.getLog(this.getClass());
-
-    /**
-     * List all notifications.
-     * @param model
-     * @param request
-     * @param response
-     * @return
-     */
-    @PreAuthorize("hasRole('ENCUESTAME_USER')")
-    @RequestMapping(value = "/user/notifications", method = RequestMethod.GET)
-    public String notificationListController(ModelMap model,
-            HttpServletRequest request, HttpServletResponse response) {
-        //final HashMap<DateClasificatedEnum, List<UtilNotification>> list = classifyNotificationList(convertNotificationList(getSecurityService()
-        //        .loadNotificationByUserAndLimit(200), request));
-        ///log.debug(list);
-        //model.addAttribute("notifications", list);
-        return "user/notifications";
-    }
-}

File enme-mvc/src/main/java/org/encuestame/mvc/controller/PictureProfileFactoryController.java

-/*
- ************************************************************************************
- * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
- * encuestame Development Team.
- * Licensed under the Apache Software License version 2.0
- * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to  in writing,  software  distributed
- * under the License is distributed  on  an  "AS IS"  BASIS,  WITHOUT  WARRANTIES  OR
- * CONDITIONS OF ANY KIND, either  express  or  implied.  See  the  License  for  the
- * specific language governing permissions and limitations under the License.
- ************************************************************************************
- */
-package org.encuestame.mvc.controller;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.log4j.Logger;
-import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
-import org.encuestame.utils.enums.PictureType;
-import org.encuestame.utils.exception.EnMeGenericException;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.ResponseBody;
-
-/**
- * Render Image.
- * @author Picado, Juan juanATencuestame.org
- * @since Jan 16, 2011 3:56:50 PM
- * @version Id:
- */
-@Controller
-public class PictureProfileFactoryController extends AbstractBaseOperations {
-
-    /**
-     * Log.
-     */
-    private Logger log = Logger.getLogger(this.getClass());
-
-
-    /**
-     *
-     * @param username
-     * @param pictureType
-     * @return
-     */
-    private byte[] getPicture(String username, final PictureType pictureType){
-        byte[] bytes = {};
-        username = filterValue(username);
-        try {
-            bytes = getPictureService().getProfilePicture(username, pictureType);
-        } catch (FileNotFoundException e) {
-            log.error("file not found "+e);
-        } catch (IOException e) {
-            log.error("IOException "+e);
-        } catch (EnMeGenericException e) {
-            log.error("EnMeGenericException "+e);
-        }
-        return bytes;
-    }
-
-    /**
-     * Returns the byte[] that contains the requested thumbnail image (128x128 constrained).
-     * @return A byte[] that contains the requested image
-     * @throws EnMeNoResultsFoundException
-     */
-    @RequestMapping( value = "/picture/profile/{username}/thumbnail", method = RequestMethod.GET )
-    @ResponseBody
-    public byte[] getPictureThumbnail(
-            @PathVariable String username, final HttpServletResponse response){
-        return this.getPicture(username, PictureType.THUMBNAIL);
-    }
-
-    /**
-     * Returns the byte[] that contains the requested default image.
-     * @return A byte[] that contains the requested image
-     * @throws EnMeNoResultsFoundException
-     */
-    @RequestMapping( value = "/picture/profile/{username}/default", method = RequestMethod.GET )
-    @ResponseBody
-    public byte[] getPictureMaster(
-            @PathVariable String username ) {
-        return this.getPicture(username, PictureType.DEFAULT);
-    }
-
-    /**
-     * Returns the byte[] that contains the requested preview image (256x256 constrained)
-     * @param username
-     * @return
-     */
-    @RequestMapping( value = "/picture/profile/{username}/profile", method = RequestMethod.GET )
-    @ResponseBody
-    public byte[] getPictureProfile(
-            @PathVariable String username ) {
-        return this.getPicture(username, PictureType.PROFILE);
-    }
-
-    /**
-     * Returns the byte[] that contains the requested preview image (375x375 constrained)
-     * @return A byte[] that contains the requested image
-     * @throws EnMeNoResultsFoundException
-     */
-    @RequestMapping( value = "/picture/profile/{username}/preview", method = RequestMethod.GET)
-    @ResponseBody
-    public byte[] getPicturePreview(
-            @PathVariable String username ){
-          return this.getPicture(username, PictureType.PREVIEW);
-    }
-
-    /**
-     * Returns the byte[] that contains the requested preview image (900x900 constrained)
-     * @param id The identifier of the image
-     * @return A byte[] that contains the requested image
-     * @throws EnMeNoResultsFoundException
-     */
-    @RequestMapping( value = "/picture/profile/{username}/web", method = RequestMethod.GET)
-    @ResponseBody
-    public byte[] getPictureWeb(
-            @PathVariable String username ){
-          return this.getPicture(username, PictureType.WEB);
-    }
-}

File enme-mvc/src/main/java/org/encuestame/mvc/controller/PollController.java

-/*
- ************************************************************************************
- * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
- * encuestame Development Team.
- * Licensed under the Apache Software License version 2.0
- * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to  in writing,  software  distributed
- * under the License is distributed  on  an  "AS IS"  BASIS,  WITHOUT  WARRANTIES  OR
- * CONDITIONS OF ANY KIND, either  express  or  implied.  See  the  License  for  the
- * specific language governing permissions and limitations under the License.
- ************************************************************************************
- */
-
-package org.encuestame.mvc.controller;
-
-import java.net.UnknownHostException;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.log4j.Logger;
-import org.encuestame.core.filter.RequestSessionMap;
-import org.encuestame.core.util.ConvertDomainBean;
-import org.encuestame.persistence.domain.survey.Poll;
-import org.encuestame.persistence.domain.survey.PollResult;
-import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
-import org.encuestame.persistence.exception.EnMePollNotFoundException;
-import org.encuestame.utils.web.PollBeanResult;
-import org.encuestame.utils.web.QuestionAnswerBean;
-import org.springframework.security.access.prepost.PreAuthorize;
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.Model;
-import org.springframework.ui.ModelMap;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RequestParam;
-
-/**
- * Poll controller.
- *
- * @author Picado, Juan juanATencuestame.org
- * @since Mar 11, 2010 9:21:37 PM
- * @version $Id: $
- */
-@Controller
-public class PollController extends AbstractBaseOperations {
-
-    /**
-     * Log.
-     */
-    private Logger log = Logger.getLogger(this.getClass());
-
-    /**
-     * Poll Controller.
-     *
-     * @param model
-     *            model
-     * @return template
-     */
-    @RequestMapping(value = "/poll/{id}/{slug}", method = RequestMethod.GET)
-    public String pollController(final ModelMap model, @PathVariable Long id,
-            @PathVariable String slug) {
-        log.debug("poll Id -->" + id);
-        log.debug("poll slug -->" + slug);
-        try {
-            final Poll poll = getPollService().getPollSlugById(id, slug);
-            // final List<QuestionAnswerBean> answer =
-            // getPollService().retrieveAnswerByQuestionId(poll.getQuestion().getQid());
-            final List<PollBeanResult> results = getPollService()
-                    .getResultVotes(poll);
-            log.debug("Poll Detail Answers " + results.size());
-            log.debug("poll--> " + poll);
-            // TODO: reuse this code on vote poll.
-            model.addAttribute("poll",
-                    ConvertDomainBean.convertPollDomainToBean(poll));
-            model.addAttribute("answers", results);
-            return "poll/detail";
-        } catch (Exception e) {
-            log.error(e);
-            return "404";
-        }
-    }
-
-    /**
-     * Display the succesfully vote interface.
-     *
-     * @param model
-     * @return
-     */
-    @RequestMapping(value = "/poll/voted", method = RequestMethod.GET)
-    public String pollVoted(final ModelMap model) {
-        return "poll/voted";
-    }
-
-    /**
-     * Called when user vote from Vote Interface, validate the vote and return a
-     * page for different cases.
-     *
-     * @param responses
-     * @param password
-     * @param usernameForm
-     * @param req
-     * @return
-     */
-    @RequestMapping(value = "/poll/vote/post", method = RequestMethod.POST)
-    public String submit(
-            @RequestParam(value = "poll", required = false) Long responseId,
-            @RequestParam(value = "itemId", required = false) Long itemId,
-            @RequestParam("type") String type,
-            @RequestParam("slugName") String slugName,
-            final HttpServletRequest req, final ModelMap model) {
-        log.debug("*************************************************");
-        log.debug("/poll/vote/post VOTE POLL " + responseId);
-        log.debug("/poll/vote/post VOTE POLL " + itemId);
-        log.debug("/poll/vote/post VOTE POLL " + type);
-        log.debug("/poll/vote/post VOTE POLL " + type);
-        log.debug("*************************************************");
-        // default path
-        String pathVote = "redirect:/poll/voted/";
-        try {
-            type = filterValue(type);
-            slugName = filterValue(slugName);
-            if (itemId == null) {
-                throw new EnMePollNotFoundException(
-                        "poll id has not been found");
-            }
-            if (responseId == null) {
-
-                final Poll poll = getPollService().getPollById(itemId);
-                model.addAttribute("poll",
-                        ConvertDomainBean.convertPollDomainToBean(poll));
-                RequestSessionMap.getCurrent(req).put("votePollError",
-                        Boolean.TRUE);
-                pathVote = "redirect:/poll/vote/" + itemId + "/" + slugName;
-            } else {
-
-                final String IP = getIpClient(req);
-                // validations
-                final Boolean checkBannedIp = checkIPinBlackList(IP);
-                if (checkBannedIp) {
-                    // if banned send to banned view.
-                    pathVote = "poll/banned";
-                } else {
-                    final Poll poll = getPollService().getPollByAnswerId(
-                            itemId, responseId, null);
-                    final PollResult result = getPollService().validatePollIP(
-                            IP, poll);
-                    if (result == null) {
-                        getPollService().vote(poll, slugName, IP, responseId);
-                    } else {
-                        pathVote = "poll/repeated";
-                    }
-                }
-            }
-        } catch (EnMeNoResultsFoundException e) {
-            log.error("error poll vote 1" + e);
-            e.printStackTrace();
-            pathVote = "poll/bad";
-        } catch (UnknownHostException e) {
-            log.error("error poll vote 2 " + e);
-            e.printStackTrace();
-            pathVote = "poll/bad";
-        }
-        log.debug("poll vote path: " + pathVote);
-        return pathVote;
-    }
-
-    /**
-     * TweetPoll Redirect.
-     *
-     * @param model
-     *            model
-     * @return template
-     */
-    @PreAuthorize("hasRole('ENCUESTAME_USER')")
-    @RequestMapping(value = "/user/poll", method = RequestMethod.GET)
-    public String tweetPollControllerRedirect(final ModelMap model) {
-        log.debug("tweetpoll");
-        return "redirect:/user/poll/list";
-    }
-
-    /**
-     *
-     * @param model
-     * @return
-     */
-    @PreAuthorize("hasRole('ENCUESTAME_USER')")
-    @RequestMapping(value = "/user/poll/list", method = RequestMethod.GET)
-    public String pollListController(final ModelMap model) {
-        log.debug("poll list render view");
-        addItemsManangeMessages(model);
-        addi18nProperty(model, "commons_no_results");
-        addi18nProperty(model, "poll_admon_poll_options");
-        addi18nProperty(model, "poll_admon_poll_answers");
-        //
-        addi18nProperty(model, "poll_admon_poll_edit");
-        addi18nProperty(model, "poll_admon_poll_preview");
-        addi18nProperty(model, "poll_admon_poll_publish_options");
-        addi18nProperty(model, "poll_admon_poll_embebed");
-        //
-        addi18nProperty(model, "commons_success");
-
-        addi18nProperty(model, "detail_manage_today");
-
-        addi18nProperty(model, "poll_admon_poll_votes");
-        //
-        addi18nProperty(model, "detail_manage_poll_title");
-        addi18nProperty(model, "detail_manage_filters");
-        addi18nProperty(model, "detail_manage_poll_dropdown_title");
-        // menu items
-        addi18nProperty(model, "poll_admon_poll_new");
-        addi18nProperty(model, "commons_remove");
-
-        // poll options
-        addi18nProperty(model, "poll_options_close");
-        addi18nProperty(model, "poll_options_quota");
-        addi18nProperty(model, "poll_options_ip");
-        addi18nProperty(model, "poll_options_password");
-        addi18nProperty(model, "poll_options_info");
-        addi18nProperty(model, "poll_options_public");
-        addi18nProperty(model, "poll_options_notifications");
-
-        // confirm
-        addi18nProperty(model, "commons_confirm");
-        addi18nProperty(model, "commons_no");
-        addi18nProperty(model, "commons_yes");
-        addi18nProperty(model, "detail_manage_today");
-        return "poll/list";
-    }
-
-    /**
-     * Display the